Open In App

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

torchvision.transforms.grayscale method

Grayscaling is the process of converting an image from other color spaces e.g. RGB, CMYK, HSV, etc. to shades of gray. It varies between complete black and complete white. torchvision.transforms.grayscale() method is used to convert an image to grayscale. If the input image is torch Tensor then it is expected to have [3, H, W] shape, H, W is height and width respectively. The below syntax is used to convert an image to grayscale.



Package Requirement

pip install torchvision
pip install torch
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.




# 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:

 

Article Tags :