我正在使用 ImageDataGenerator
批量加载灰度图像。我需要将每个灰度图像的内容复制到 3 个 channel 中。我尝试了以下代码,但它似乎不起作用:
def grayscale_to_rgb(images, channel_axis=-1):
images= K.expand_dims(images, axis=channel_axis)
tiling = [1] * 4 # 4 dimensions: B, H, W, C
tiling[channel_axis] *= 3
images= K.tile(images, tiling)
return images
train_images_orign= grayscale_to_rgb(train_images_orign)
valid_images_orign= grayscale_to_rgb(valid_images_orign)
test_images_orign= grayscale_to_rgb(test_images_orign)
x_train, y_train = next(train_images_orign)
x_valid, y_valid = next(valid_images_orign)
x_test, y_test = next(test_images_orign)
我应该从哪个方向来实现这一点?
最佳答案
更新:原来是load_img
Keras 中的功能已经实现in such a way如果正在加载的图像的颜色模式和给定的 color_mode
参数(默认为 'RGB'
)不同,则图像将被转换为给定的 颜色模式
。因此,在这种情况下,灰度图像将自动转换为 RGB。
您可以使用 ImageDataGenerator
的 preprocessing_function
参数同样(假设您使用的是 color_mode='grayscale'
,否则上面的说明适用):
import numpy as np
def gray_to_rgb(img):
return np.repeat(img, 3, 2)
generator = ImageDataGenerator(..., preprocessing_function=gray_to_rgb)
train_gen = generator.flow_from_directory(color_mode='grayscale', ...)
请注意,此函数在任何图像增强之后应用:
preprocessing_function: function that will be implied on each input. The function will run after the image is resized and augmented. The function should take one argument: one image (Numpy tensor with rank 3), and should output a Numpy tensor with the same shape.
关于python - 将灰度图像内容复制到 3 个 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52503396/