def crop_image(fname,target_size):
print('Processing image: %s' % fname)
#otsu thresholding
img = Image.open(fname)
blurred = img.filter(ImageFilter.BLUR)
ba = np.array(blurred)
gray_image = cv2.cvtColor(ba, cv2.COLOR_BGR2GRAY)
retval2, threshold2 = cv2.threshold(gray_image, 125, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
#storing white pixel in each row and column in two arrays
#these arrays are later used to find boundaries for cropping image
row_white_pixel_count=np.count_nonzero(threshold2,axis=1)
col_white_pixel_count=np.count_nonzero(threshold2,axis=0)
#find x,y,w,h for cropping image
y=find_boundary(row_white_pixel_count,col_white_pixel_count.size)
h=find_boundary_reverse(row_white_pixel_count,col_white_pixel_count.size)
x=find_boundary(col_white_pixel_count,row_white_pixel_count.size)
w=find_boundary_reverse(col_white_pixel_count,row_white_pixel_count.size)
crop_array = ba[y:h, x:w]
#resize the image
crop_img=Image.fromarray(crop_array)
resized = crop_img.resize([target_size, target_size])
#uncomment below line to see histogram of both white pixel vs rows and white pixel vs columns
subplots(threshold2, row_white_pixel_count, col_white_pixel_count, crop_img)
return resized
评论列表
文章目录