gpt4 book ai didi

python - Tensorflow:将灰度图像转换为RGB

转载 作者:行者123 更新时间:2023-12-01 08:17:45 25 4
gpt4 key购买 nike

我有一个 RGB 和灰度图像的数据集。在迭代数据集时,我想检测图像是否是灰度图像,以便可以将其转换为 RGB。我想使用 tf.shape(image) 来检测图像的尺寸。对于 RGB 图像,我得到类似 [1, 100, 100, 3] 的内容。对于灰度图像,该函数返回例如 [1, 100, 100]。我想使用 len(tf.shape(image)) 来检测它的长度是 4 (=rgb) 还是长度 3 (=grayscale)。那没有用。

这是我到目前为止不起作用的代码:

def process_image(image):
# Convert numpy array to tensor
image = tf.convert_to_tensor(image, dtype=tf.uint8)
# Take care of grayscale images
dims = len(tf.shape(image))
if dims == 3:
image = np.expand_dims(image, axis=3)
image = tf.image.grayscale_to_rgb(image)
return image

是否有其他方法可以将灰度图像转换为 RGB?

最佳答案

我有一个非常相似的问题,我想一次性加载 rgb 和灰度图像。 Tensorflow支持在读取图像时设置 channel 号。因此,如果图像具有不同数量的 channel ,这可能就是您正在寻找的:

# to get greyscale:
tf.io.decode_image(raw_img, expand_animations = False, dtype=tf.float32, channels=1)

# to get rgb:
tf.io.decode_image(raw_img, expand_animations = False, dtype=tf.float32, channels=3)

-> 您甚至可以在同一个图像和 tf.data.Dataset 映射中执行这两项操作!

您现在必须设置 channels 变量以匹配您需要的形状,因此所有加载的图像都将具有该形状。比你可以无条件 reshape 。

这还允许您在 Tensorflow 中直接将灰度图像加载为 RGB。这是一个例子:

    >> a = Image.open(r"Path/to/rgb_img.JPG")
>> np.array(a).shape
(666, 1050, 3)
>> a = a.convert('L')
>> np.array(a).shape
(666, 1050)
>> b = np.array(a)
>> im = Image.fromarray(b)
>> im.save(r"Path/to/now_it_is_greyscale.jpg")
>> raw_img = tf.io.read_file(r"Path/to/now_it_is_greyscale.jpg")
>> img = tf.io.decode_image(raw_img, dtype=tf.float32, channels=3)
>> img.shape
TensorShape([666, 1050, 3])
>> img = tf.io.decode_image(raw_img, dtype=tf.float32, channels=1)
>> img.shape
TensorShape([666, 1050, 1])

如果出现 ValueError: 'images' contains no shape.,请使用 expand_animations = False!请参阅:https://stackoverflow.com/a/59944421/9621080

关于python - Tensorflow:将灰度图像转换为RGB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54884305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com