def crop_image(x, target_height=227, target_width=227):
print x
# skimage.img_as_float convert image np.ndarray into float type, with range (0, 1)
image = skimage.img_as_float(skimage.io.imread(x)).astype(np.float32)
if image.ndim == 2:
image = image[:,:,np.newaxis][:,:,[0,0,0]] # convert the gray image to rgb image
height, width, rgb = image.shape
if width == height:
resized_image = cv2.resize(image, (target_width,target_height))
elif height < width:
resized_image = cv2.resize(image, (int(width * float(target_height)/height), target_height))
cropping_length = int((resized_image.shape[1] - target_width) / 2)
resized_image = resized_image[:,cropping_length:resized_image.shape[1] - cropping_length]
else:
resized_image = cv2.resize(image, (target_width, int(height * float(target_width) / width)))
cropping_length = int((resized_image.shape[0] - target_height) / 2)
resized_image = resized_image[cropping_length:resized_image.shape[0] - cropping_length,:]
return cv2.resize(resized_image, (target_width, target_height))
评论列表
文章目录