How to Convert a Torch Tensor to PIL Image

To convert a Torch Tensor to a PIL Image, you can “use the transforms.ToPILImage() function.” The ToPILImage() accepts torch tensors of shape [C, H, W] where C, H, and W are the number of channels, image height, and width of the corresponding PIL images, respectively.

Here is the step-by-step guide to convert a torch tensor to a PIL image.

Step 1: Install the necessary  library

pip install torch torchvision Pillow

Step 2: Use the transforms.ToPILImage() for conversion

import torch
from torchvision.transforms import ToPILImage

tensor = torch.rand(3, 256, 256)

# Convert tensor to PIL Image
to_pil = ToPILImage()
pil_image = to_pil(tensor)
pil_image.show()

Output

Use the transforms.ToPILImage() for conversion

Ensure that the tensor is in the correct shape (C, H, W) where C is the number of channels (e.g., 3 for RGB), H is the height, and W is the image’s width.

If your tensor values are in the range [0, 1], you can use the above method directly. However, if they’re in the range [0, 255], you might need to first divide by 255 to bring them into the [0, 1] range.

If the tensor is on the GPU (CUDA), you should first move it to the CPU using the .cpu() method before converting it to a PIL image.

That’s it!

Related posts

PyTorch Tensor to Numpy Array

PyTorch Tensor to Python List

Pandas DataFrame to a PyTorch Tensor

Leave a Comment