【问题标题】:Converting a grayscale image to rgb damages image将灰度图像转换为 rgb 会损坏图像
【发布时间】:2021-08-09 17:26:30
【问题描述】:

我在 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

​​>

从这里:https://stackoverflow.com/a/40119878/14420572

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

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

【问题讨论】:

  • 首先要搞清楚灰度图的数据类型是什么。
  • 灰度图像是形状为 (224, 224) 的 NumPy 数组。谢谢,
  • 什么是数据类型? uint8?整数8?整数16?浮动32?等
  • 另外,您应该找出灰度图像中的最小和最大灰度值。
  • 它是numpy.float64,图像中的最小值和最大值很奇怪,np.max(X) = 4387.0np.min(X) = -126.0。你认为这是问题所在吗?

标签: python image numpy opencv python-imaging-library


【解决方案1】:

如果我错了,请纠正我,但我怀疑 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 之间。

【讨论】:

  • 谢谢!实际上,图像是从 dicom 文件加载的,因此每个图像都有不同的范围。通过这样做,我能够正确显示它们:img = X[0].astype('float32')/np.max(X[0])。现在我需要找到一种方法将所有图像放在相似的范围内,这样我的 CNN 才能真正学到一些东西?
  • @AryaMan 我的直觉告诉你,你让没有真正亮点的图像更亮。如果我是你,我会阅读格式并避免使用有关特定图像的信息来转换它。
  • 感谢您的反馈!我目前正在研究它,我已经从一个 dicom 文件中加载了图像,所以我正在寻找一种方法来读取默认值在 0-255 之间的图像。
  • 使用这里描述的函数 rescale_intensity:stackoverflow.com/a/68513088/5239109
猜你喜欢
  • 2014-02-26
  • 2014-12-22
  • 2019-11-14
  • 1970-01-01
  • 2013-10-25
  • 1970-01-01
  • 2016-11-05
  • 2018-08-15
相关资源
最近更新 更多