- Trending Categories
- Data Structure
- Operating System
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert a Torch Tensor to PIL image?
The ToPILImage() transform converts a torch tensor to PIL image. The torchvision.transforms module provides many important transforms that can be used to perform different types of manipulations on the image data. 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.
We could use the following steps to convert a torch tensor to a PIL image −
Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them.
import torch import torchvision import torchvision.transforms as T from PIL import Image
Define a torch tensor of shape [C, H, W].
tensor = torch.rand(3,256,256)
Define a transform to convert the torch tensor to PIL image.
transform = T.ToPILImage()
Apply the above-defined transform on the input torch tensor to convert it to a PIL image.
img = transform(tensor)
Show the converted PIL image.
Take a look at the following example −
# import required libraries import torch import torchvision.transforms as T from PIL import Image # define a torch tensor tensor = torch.rand(3,300,700) # define a transform to convert a tensor to PIL image transform = T.ToPILImage() # convert the tensor to PIL image using above transform img = transform(tensor) # display the PIL image img.show()
It will produce the following output −
- How to convert Matplotlib figure to PIL Image object?
- How to convert an image to a PyTorch Tensor?
- How to move a Torch Tensor from CPU to GPU and vice versa?
- How to open PIL Image in Tkinter on Canvas?
- How to convert a PyTorch tensor with gradient to a numpy array?
- How to convert a NumPy ndarray to a PyTorch Tensor and vice versa?
- OpenCV Python – How to convert a colored image to a binary image?
- Embedding an Image in a Tkinter Canvas widget using PIL
- How to convert a negative image to positive image using Java OpenCV library?
- How to convert a colored image to Sepia image using Java OpenCV library?
- PyTorch – How to convert an image to grayscale?
- How to resize a tensor in PyTorch?
- How to normalize a tensor in PyTorch?
- How to convert an RGB image to HSV image using OpenCV Python?
- How to convert a colored image to blue/green/red image using Java OpenCV library?