将灰度图像转换为 rgb 损坏图像

Converting a grayscale image to rgb damages image

我在 NumPy 数组中有一组灰度图像。我想在将图像输入 CNN 之前将它们转换为 RGB(我正在使用迁移学习)。但是当我尝试将图像转换为 RGB 时,图像中的几乎所有信息都丢失了!我尝试了几个库,但它们都导致(几乎)相同的结果:

原图:

import matplotlib.pyplot as plt
plt.imshow(X[0])

使用 cv2:

import cv2

img = X[0].astype('float32') #cv2 needs float32 or uint8 for handling images
rgb_image = cv2.cvtColor(img,cv2.COLOR_GRAY2RGB)
plt.imshow(rgb_image)

img = X[0].astype('uint8') #cv2 needs float32 or uint8 for handling images
rgb_image = cv2.cvtColor(img,cv2.COLOR_GRAY2RGB)
plt.imshow(rgb_image)

使用 PIL

from PIL import Image

img = Image.fromarray(X[0])
img_rgb = img.convert("RGB")
plt.imshow(img_rgb)

使用 NumPy

从这里开始:

stacked_img = np.stack((X[0],)*3, axis=-1)
plt.imshow(stacked_img)

我应该怎么做才能确保图像在没有质量损失的情况下进行转换?

如果我错了请纠正我,但我怀疑 X[0] 中的值在 0,255 范围内。在

img = X[0].astype('float32') #cv2 needs float32 or uint8 for handling images
rgb_image = cv2.cvtColor(img,cv2.COLOR_GRAY2RGB)
plt.imshow(rgb_image)

尝试将第一行替换为。

img = X[0]/255

这使得值不仅 float32 而且在 0 和 1 之间。