使用Matplotlib将Pytorch张量显示为图像

时间:2020-06-23 18:11:49

标签: python 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网格。例如:

enter image description here

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

1 个答案:

答案 0 :(得分:3)

这很奇怪。尝试通过置换而不是整形来使频道排在最后:

image.permute(1, 2, 0)
相关问题