Untitled
folders = [40, 42, 43, 45, 46, 47, 50, 51, 52, 53] for i in range(len(folders)): path = 'D:\\curetcol\\sample%s' % (folders[i]) dstpath = 'D:\\curetcol\\Full\\train%s' % (folders[i]) try: os.makedirs(dstpath) except: print ("Directory already exist, images will be written in asme folder") files = os.listdir(path) for image in files: img = cv2.imread(os.path.join(path, image)) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) dstPath = join(dstpath, image) cv2.imwrite(dstPath, gray) def resize_image(src_image, size=(128, 128), bg_color="white"): # resize the image so the longest dimension matches our target size src_image.thumbnail(size, Image.LANCZOS) # Create a new square background image new_image = Image.new('L', size) # Paste the resized image into the center of the square background new_image.paste(src_image, (int((size[0] - src_image.size[0]) / 2), int((size[1] - src_image.size[1]) / 2))) # return the resized image return new_image training_folder_name = 'D:\\fixedSplit\\Train' classes = sorted(os.listdir(training_folder_name)) # New location for the resized images train_folder = 'D:\\curetcol\\Full\\TrainResized' if os.path.exists(train_folder): shutil.rmtree(train_folder) for root, folders, files in os.walk(training_folder_name): for sub_folder in folders: print('processing folder ' + sub_folder) # Create a matching subfolder in the output dir saveFolder = os.path.join(train_folder,sub_folder) if not os.path.exists(saveFolder): os.makedirs(saveFolder) # Loop through the files in the subfolder file_names = os.listdir(os.path.join(root,sub_folder)) for file_name in file_names: # Open the file file_path = os.path.join(root,sub_folder, file_name) #print("reading " + file_path) image = Image.open(file_path) # Create a resized version and save it resized_image = resize_image(image, size) saveAs = os.path.join(saveFolder, file_name) #print("writing " + saveAs) resized_image.save(saveAs) print('Done.')
Leave a Comment