python - 将灰度图像内容复制到 3 个 channel

标签 python tensorflow keras deep-learning

我正在使用 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。


您可以使用 ImageDataGeneratorpreprocessing_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/

相关文章:

python - 从 TensorFlow 中的检查点恢复后修改变量名称

python - Tensorflow 重新训练.py tensorflow.python.framework.errors_impl.FailedPreconditionError

TensorFlow 中 C 代码的代码完成

machine-learning - 如何在Keras中实现自定义加权MSE损失函数?

neural-network - 我应该使用损失还是准确度作为提前停止指标?

python - 在 Python 中, ".append()"和 "+= []"有什么区别?

python - 在 numpy 中正确执行以下操作的正确方法

python - 安装 Pandas : UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 72: ordinal not in range(128)

python - 如何实时运行Python程序?

keras - 使用相同的数据训练相同的模型会产生截然不同的测试精度