How to Display a Single Image in PyTorch

Here are the steps to display a single image in PyTorch.

Step 1: Import PIL, torchvision, and matplotlib libraries

import torchvision
import matplotlib.pyplot as plt

from PIL import Image

Step 2: Loading the image

You can use the PIL library to load the image from your local system.

image = Image.open('kdl.png')

Here, you can apply your path/to/image to the image you want to display.

Step 3: Converting the Image to a PyTorch Tensor

To display the image using PyTorch, you need to convert it to a PyTorch tensor.

transform = torchvision.transforms.ToTensor()

image = transform(image)

Step 4: Displaying the Image

You can display an image using matplotlib.pyplot’s imshow() function.

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

plt.show()

Complete Code

import torchvision
import matplotlib.pyplot as plt

from PIL import Image

image = Image.open('kdl.png')

transform = torchvision.transforms.ToTensor()
image = transform(image)

plt.imshow(image.permute(1, 2, 0))
plt.show()

Output

Display a Single Image in PyTorch

That’s it!

Leave a Comment