我正在尝试使用keras裁剪图像数据生成器中的图像中心。我有大小为192x192
的图片,我想裁剪它们的中心,以便输出批次为150x150
或类似的东西。
我可以立即在Keras ImageDataGenerator
中这样做吗?我想不,因为我看到datagenerator中的target_size
参数会破坏图像。
我找到了随机裁剪的链接: https://jkjung-avt.github.io/keras-image-cropping/
我已按如下方式修改了作物:
def my_crop(img, random_crop_size):
if K.image_data_format() == 'channels_last':
# Note: image_data_format is 'channel_last'
assert img.shape[2] == 3
height, width = img.shape[0], img.shape[1]
dy, dx = random_crop_size #input desired output size
start_y = (height-dy)//2
start_x = (width-dx)//2
return img[start_y:start_y+dy, start_x:(dx+start_x), :]
else:
assert img.shape[0] == 3
height, width = img.shape[1], img.shape[2]
dy, dx = random_crop_size # input desired output size
start_y = (height - dy) // 2
start_x = (width - dx) // 2
return img[:,start_y:start_y + dy, start_x:(dx + start_x)]
def crop_generator(batches, crop_length):
'''
Take as input a Keras ImageGen (Iterator) and generate
crops from the image batches generated by the original iterator
'''
while True:
batch_x, batch_y = next(batches)
#print('the shape of tensor batch_x is:', batch_x.shape)
#print('the shape of tensor batch_y is:', batch_y.shape)
if K.image_data_format() == 'channels_last':
batch_crops = np.zeros((batch_x.shape[0], crop_length, crop_length, 3))
else:
batch_crops = np.zeros((batch_x.shape[0], 3, crop_length, crop_length))
for i in range(batch_x.shape[0]):
batch_crops[i] = my_crop(batch_x[i], (crop_length, crop_length))
yield (batch_crops, batch_y)
这个解决方案对我来说似乎很慢,请问还有其他更有效的方法吗?你会建议什么?
先谢谢
答案 0 :(得分:0)
我试图用这种方式解决它:
offset
如果你有更好的方法,请提出你的建议。
答案 1 :(得分:0)
您可以像这样定义自定义裁剪功能。
from keras.preprocessing.image import load_img
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import array_to_img
def crop(image):
start_y = (img_height - crop_length) // 2
start_y = (img_width - crop_length) // 2
cropped_image=image[start_x:(img_width - start_x), start_y:(img_height - start_y), :]
return cropped_image
该函数可以像这样包含在 Keras 自定义生成器中。
ImageDataGenerator(preprocessing_function=crop)
然后你可以根据你的选择ImageDataGenerator
对象