카테고리 없음
Python Directory 생성 및 파일 복사 등등
Cuoong
2022. 8. 19. 13:24
import os, shutil
def createFolder(directory):
try:
if not os.path.exists(directory):
os.makedirs(directory)
except OSError:
print('Error: Creating directory. ' + directory)
save_train_image_path = r"D:\ADC_POC\transistor\train_image"
save_train_mask_path = r"D:\ADC_POC\transistor\train_mask"
save_test_image_path = r"D:\ADC_POC\transistor\test_image"
save_test_mask_path = r"D:\ADC_POC\transistor\test_mask"
root_dir = r"D:\ADC_POC\transistor\test"
ground_truth_dir = r"D:\ADC_POC\transistor\ground_truth"
createFolder(save_train_image_path)
createFolder(save_train_mask_path)
createFolder(save_test_image_path)
createFolder(save_test_mask_path)
file_count = 0
for (root, dir, file) in os.walk(root_dir) :
print(f'root: {root}')
print(dir)
print(file)
for fileName in file :
basename, extension = os.path.splitext(fileName)
print(f'basename:{basename}, extension:{extension}')
if extension != '.png' :
continue
sourcePath = os.path.join(root, fileName)
newFileName = str(file_count) + ".png"
if file_count%4 > 0 :
destImagePath = os.path.join(save_train_image_path,newFileName)
destMaskPath = os.path.join(save_train_mask_path,newFileName)
else :
destImagePath = os.path.join(save_test_image_path,newFileName)
destMaskPath = os.path.join(save_test_mask_path,newFileName)
file_count += 1
shutil.copy(sourcePath, destImagePath)
print(f'image copy : {sourcePath} -> {destImagePath}')
dirname = os.path.dirname(sourcePath)
cur_dirname = os.path.split(dirname)[-1]
print(f'dirname = {cur_dirname}')
if cur_dirname == 'good' :
img = cv2.imread(sourcePath)
height, width, _ = img.shape
mask_img = np.zeros((height, width), np.uint8)
cv2.imwrite(destMaskPath, mask_img)
print(f'empty mask : {destMaskPath}')
else :
mask_file_name = basename + "_mask.png"
mask_sourcePath = sourcePath.replace(root_dir, ground_truth_dir)
mask_sourcePath = mask_sourcePath.replace(fileName, mask_file_name)
shutil.copy(mask_sourcePath, destMaskPath)
print(f'mask copy : {mask_sourcePath} -> {destMaskPath}')