To convert an Image to Grayscale in Python, you can use the ImageOps.grayscale() method. The PIL module provides ImageOps class, which provides various methods to help us modify the image.
PIL provides an Image class with an open() image to open the image in Python. So we can open the image.
The pillow supports various image file formats such as PNG, JPEG, PPM, GIF, TIFF, and BMP.
The pillow supports editing operations like cropping, resizing, adding text to images, rotating, and greyscaling.
ImageOps.grayscale()
The ImageOps.grayscale() function converts RGB image to Grayscale. The complete pixel turns grey, and no other color will be seen.
Syntax
ImageOps.grayscale(image)
Parameters
It takes an image as a parameter to convert it into grayscale. It is the required parameter because it is an input image.
Example
Convert RGB Image to Grayscale image using PIL.ImageOps.grayscale() method.
# Importing Image and ImageOps module from PIL package
from PIL import Image, ImageOps
# creating an og_image object
og_image = Image.open("./forest.jpg")
og_image.show()
# applying grayscale method
gray_image = ImageOps.grayscale(og_image)
gray_image.show()
Output
You can save the grayscale image using the save() method.
# Importing Image and ImageOps module from PIL package
from PIL import Image, ImageOps
# creating an og_image object
og_image = Image.open("./forest.jpg")
# applying grayscale method
gray_image = ImageOps.grayscale(og_image)
gray_image.save('gray_image.png')
The save() method stores the image in our filesystem. It takes one parameter called a filename.
The image is saved inside your current project folder if you run the above code.
That is it for the convert PIL Image to Grayscale in Python.