Package Requirement
- Pytorch is an open-source deep learning framework available with a Python and C++ interface. Pytorch resides inside the torch module. In PyTorch, the data that has to be processed is input in the form of a tensor. whereas Torchvision is a library that goes hand in hand with PyTorch.
pip install torchvision pip install torch
- Python Pillow is built on top of PIL (Python Image Library) and is considered the fork for the same as PIL.
pip install Pillow
Image used for demonstration:
Example
The following program is to understand how to convert images to grayscale.
Syntax: torchvision.transforms.Grayscale()
Parameter:
- num_output_channels (int) – (1 or 3) number of channels desired for output image
Return: This method return an grayscale image.
Python3
# import required libraries import torch import torchvision.transforms as transforms from PIL import Image # Read the image picture = Image. open ( 'geekslogo.png' ) # Define transform transform = transforms.Grayscale() # Convert the image to grayscale image = transform(picture) # Display image.show() |
Output:
How to convert an image to grayscale in PyTorch
In this article, we are going to see how to convert an image to grayscale in PyTorch.