def get_patches(filepath,patch_size,crop_sizes,save_dir=None):
'''This functions creates and return patches of given image with a specified patch_size, if save_dir is given patches are saved to the directory'''
image = cv2.imread(filepath)
filename=filepath.split('/')[-1].split('.')[0]
height, width , channels= image.shape
patches = []
for crop_size in crop_sizes: #We will crop the image to different sizes
crop_h, crop_w = int(height*crop_size),int(width*crop_size)
image_scaled = cv2.resize(image, (crop_w,crop_h), interpolation=cv2.INTER_CUBIC)
for i in range(0, crop_h-patch_size+1, patch_size):
for j in range(0, crop_w-patch_size+1, patch_size):
x = image_scaled[i:i+patch_size, j:j+patch_size] # This gets the patch from the original image with size patch_size x patch_size
if save_dir!=None: #If save_dir is specified we will save the patches to the given directory
if not os.path.exists(save_dir):
os.mkdir(save_dir)
pactch_filepath=save_dir+'/'+filename+''+str(crop_h)+''+str(i)+'_'+str(j)+'.jpg'# Creating a distinct patch filename
cv2.imwrite(pactch_filepath,x) # Saving the image to the path
patches.append(x)
return patches