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
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
Pandas DataFrame to a PyTorch Tensor

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Machine Learning frameworks like PyTorch and Tensorflow is a testament to his versatility and commitment to the craft.