How do I display a single image in PyTorch?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do I display a single image in PyTorch in Python. So Here I am Explain to you all the possible Methods here.

How do I display a single image in PyTorch?

1. How do I display a single image in PyTorch?

As you can see matplotlib works fine even without conversion to numpy array. But PyTorch Tensors (“Image tensors”) are channel first, so to use them with matplotlib you need to reshape it:

2. I display a single image in PyTorch

As you can see matplotlib works fine even without conversion to numpy array. But PyTorch Tensors (“Image tensors”) are channel first, so to use them with matplotlib you need to reshape it:

Method 1

Given a Tensor representing the image, use .permute() to put the channels as the last dimension:

plt.imshow(  tensor_image.permute(1, 2, 0)  )

Method 2

As you can see matplotlib works fine even without conversion to numpy array. But PyTorch Tensors (“Image tensors”) are channel first, so to use them with matplotlib you need to reshape it:

Code:

from scipy.misc import face
import matplotlib.pyplot as plt
import torch

np_image = face()
print(type(np_image), np_image.shape)
tensor_image = torch.from_numpy(np_image)
print(type(tensor_image), tensor_image.shape)
# reshape to channel first:
tensor_image = tensor_image.view(tensor_image.shape, tensor_image.shape, tensor_image.shape)
print(type(tensor_image), tensor_image.shape)

# If you try to plot image with shape (C, H, W)
# You will get TypeError:
# plt.imshow(tensor_image)

# So we need to reshape it to (H, W, C):
tensor_image = tensor_image.view(tensor_image.shape, tensor_image.shape, tensor_image.shape)
print(type(tensor_image), tensor_image.shape)

plt.imshow(tensor_image)
plt.show()

Output:

<class 'numpy.ndarray'> (768, 1024, 3)
<class 'torch.Tensor'> torch.Size([768, 1024, 3])
<class 'torch.Tensor'> torch.Size([3, 768, 1024])
<class 'torch.Tensor'> torch.Size([768, 1024, 3])

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.