Convert PyTorch Tensor to PIL Image using Python

Convert PyTorch Tensor to PIL Image using Python

Pillow (PIL) library provides various functions to manipulate, analyze, and display image data. When working with images, it's often useful to convert PyTorch tensors to PIL images for visualization and analysis purposes. Fortunately, this conversion process is pretty straightforward. This tutorial shows how to do that using Python.

Prepare environment

  • Install the following packages using pip:
pip install torch torchvision
pip install Pillow


In the following code, we read the image as a PyTorch tensor. Next, we convert the tensor into a PIL image. By writing only a few lines of code, we got PIL image which can be used for various image processing tasks.

from import read_image
import torchvision.transforms as transforms

tensorImg = read_image('test.jpg')

pilImg = transforms.ToPILImage()(tensorImg)

Leave a Comment

Cancel reply

Your email address will not be published.