image-processing - 在 Keras ImageDataGenerator 或 flow_from_directory 中裁剪图像的中心

标签 image-processing machine-learning keras conv-neural-network

我正在尝试使用 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)

这个解决方案在我看来很慢,请问还有其他更有效的方法吗?你有什么建议?

提前致谢

最佳答案

我试图用这种方式解决它:

def crop_generator(batches, crop_length):
  while True:
    batch_x, batch_y = next(batches)
    start_y = (img_height - crop_length) // 2
    start_x = (img_width - crop_length) // 2
    if K.image_data_format() == 'channels_last':
        batch_crops = batch_x[:, start_x:(img_width - start_x), start_y:(img_height - start_y), :]
    else:
        batch_crops = batch_x[:, :, start_x:(img_width - start_x), start_y:(img_height - start_y)]
    yield (batch_crops, batch_y)

如果您有更好的方法,请提出您的建议。

关于image-processing - 在 Keras ImageDataGenerator 或 flow_from_directory 中裁剪图像的中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50486678/

相关文章:

c# - 使用 C# 在图像中查找黑色正方形/矩形

python-3.x - 适用于 Python 的逻辑回归和 KNN 等模型的输入格式

python - Pytorch 预期为 1D 张量,但得到了 2D 张量

python-3.x - 在 Keras 嵌入层中使用 BERT 嵌入

python - Keras - 从一个神经网络做出两个预测

c++ - 提高图像处理速度

image-processing - 在 2D 网格上插值

c++ - 如何确定 CUDA gpu 性能?

python - Keras TimeDistributed - 权重共享吗?

deep-learning - 为什么我的训练损失有规律的峰值?