Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Pytorch tensor as image using Matplotlib

I am trying to display an image stored as a pytorch tensor.

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())

This method is displaying a 3 by 3 grid of the same image, always in greyscale. For example:

enter image description here

How do I fix this so that the single color image is displayed correctly?

like image 692
rocksNwaves Avatar asked Jun 23 '20 18:06

rocksNwaves


1 Answers

That's very odd. Try putting the channels last by permuting rather than reshaping:

image.permute(1, 2, 0)
like image 104
Nicolas Gervais Avatar answered Oct 06 '22 19:10

Nicolas Gervais