首页 > 解决方案 > 使用 Matplotlib 将 Pytorch 张量显示为图像

问题描述

我正在尝试显示存储为 pytorch 张量的图像。

trainset = datasets.ImageFolder('data/Cat_Dog_data/train/', transform=transforms)
trainload = torch.utils.data.DataLoader(trainset, batch_size=32, shuffle=True)

images, labels = iter(trainload).next()
image = images[0]
image.shape 

>>> torch.Size([3, 224, 224]) # pyplot doesn't like this, so reshape

image = image.reshape(224,224,3)
plt.imshow(image.numpy())

此方法显示同一图像的 3 x 3 网格,始终以灰度显示。例如:

在此处输入图像描述

如何解决此问题,以便正确显示单色图像?

标签: pythonmatplotlibmachine-learningpytorch

解决方案


这很奇怪。尝试通过排列而不是重塑将通道放在最后:

image.permute(1, 2, 0)

推荐阅读