从具有3个通道的numpy数组中绘制彩色图像。

10
在我的Jupyter笔记本中,我正在尝试通过Keras迭代显示一张图片。我使用的代码如下:
def plotImages(path, num):
 batchGenerator = file_utils.fileBatchGenerator(path+"train/", num)
 imgs,labels = next(batchGenerator)
 fig = plt.figure(figsize=(224, 224))
 plt.gray()
 for i in range(num):
    sub = fig.add_subplot(num, 1, i + 1)
    sub.imshow(imgs[i,0], interpolation='nearest')

但是这仅绘制单通道,因此我的图像是灰度的。我该如何使用3个通道输出彩色图像绘图?


imgs 的形状是什么? - Suever
2242243,在上述代码中我正在打印通道1。 - Abhik
2
所以只需执行sub.imshow(imgs)来使用所有通道。如果您不提供所有通道,您如何指望它显示RGB呢? - Suever
2个回答

11

如果您想显示 RGB 图像,则必须提供 所有三个通道。基于您的代码,您实际上只显示了第一个通道,因此 matplotlib 没有信息来将其显示为 RGB。相反,它将值映射到 gray 颜色映射,因为您调用了 plt.gray()

为了正确显示颜色,请将 RGB 图像的所有通道传递给 imshow,然后将使用真彩色显示,并忽略图形的颜色映射。

sub.imshow(imgs, interpolation='nearest')

更新

由于imgs实际上是2 x 3 x 224 x 224,因此您需要对imgs进行索引并重新排列维度为224 x 224 x 3,然后再显示图像。

im2display = imgs[1].transpose((1,2,0))
sub.imshow(im2display, interpolation='nearest')

我遇到了一个错误,'TypeError: Invalid dimensions for image data'。 - Abhik
@Abhik 你说你的图像大小是 244 x 244 x 3。那么 imgs.shape 显示什么? - Suever
(2,3,224,224)- 2张3 * 224 * 224的图像。因此,我正在执行sub.imshow(imgs [i],interpolation ='nearest'),其中i是图像的索引。 - Abhik
`TypeError: transpose() received an invalid combination of arguments - got (tuple), but expected one of:
  • (int dim0, int dim1)
  • (name dim0, name dim1)`
- sh37211

0

这将对您有用: 尝试通过允许将通道放在最后。

image.permute(2 , 3 , 1 , 0)

然后通过 np.squeeze() 方法去除图像索引:

plt.imshow((np.squeeze(image.permute(2 , 3 , 1 , 0))))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接