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.

Without wasting your time, Let’s start This Article.

Table of Contents

## How do I display a single image in PyTorch?

**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:**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[2], tensor_image.shape[0], tensor_image.shape[1]) 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[1], tensor_image.shape[2], tensor_image.shape[0]) 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.

**Also, Read**