AppDividend
Latest Code Tutorials

How To Convert PIL Image to Grayscale in Python

0

To convert PIL Image to Grayscale in Python, use the ImageOps.grayscale() method. PIL module provides ImageOps class, which provides various methods that can help us to modify the image.

To open the image in Python, PIL provides an Image class that has an open() image. So, we can open the image.

Pillow supports the variety of image file formats such as PNG, JPEG, PPM, GIF, TIFF, and BMP.

Pillow supports image editing operations like cropping, resizing, adding text to images, rotating, greyscaling.

ImageOps.grayscale()

The ImageOps.grayscale() function converts RGB image to Grayscale image. The complete pixel turns to grey, and no other color will be seen.

Syntax

ImageOps.grayscale(image)

Parameters

It takes an image as a parameter to convert that image into a 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

 

Convert PIL Image to Grayscale in Python

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.

If you run the above code, the image is saved inside your current project folder.

That is it for the convert PIL Image to Grayscale in Python.

See also

Convert PIL Image to Numpy Array

Convert JPG to PNG Image in Python

Convert RGB Image to Grayscale using OpenCV

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.