How to Convert Image to Grayscale in Python

Visual Representation of Convert Image to Grayscale in Python

Here are the four ways to convert an image to grayscale in Python:

  1. Using cv2.cvtColor()
  2. Using image.convert()
  3. Using PIL.ImageOps.grayscale()
  4. Using the cv2.imread()

Input Image

Twin
Twin.png

Method 1: Using cv2.cvtColor()

OpenCV reads images in BGR format by default, so you need to use cv2.COLOR_BGR2GRAY to convert it to grayscale.

If you haven’t already, install OpenCV using pip:

pip install opencv-python

Example

import cv2

# Load the image from file
img = cv2.imread("Twin.png")

# Convert the loaded image to grayscale
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Display the grayscale image in a window titled 'Grayscale'
cv2.imshow('Grayscale', gray_img)

# Wait for a key press to close the window
# 0 here means wait indefinitely until a key is pressed
cv2.waitKey(0)

# After the keypress, destroy all created windows
cv2.destroyAllWindows()

Output

Using cv2.cvtColor()

Method 2: Using image.convert()

Install Pillow, if you haven’t already:

pip install pillow

Example

from PIL import Image

# Load the image
img = Image.open("Twin.png")

gray_img = img.convert("L")

gray_img.show()

Output

Using image.convert()

In this code, convert(“L”) is used for the grayscale conversion, where “L” mode stands for “luminance,” representing the image in shades of gray.

Method 3: Using PIL.ImageOps.grayscale()

This method is particularly useful if you are already working with the Pillow library for other image processing tasks.

Example

from PIL import Image, ImageOps

# Load the image
img = Image.open("Twin.png")

gray_img = ImageOps.grayscale(img)

# You can now display or save the grayscale image
gray_img.show() 

OutputUsing ImageOps.grayscale()

Method 4: Using the cv2.imread()

In OpenCV, the flag 0 is equivalent to cv2.IMREAD_GRAYSCALE, both of which indicate that the image should be read in grayscale mode.

Example

import cv2
 
# Load the image in grayscale mode by setting the flag to 0
img = cv2.imread("Twin.png", 0)
 
cv2.imshow('Grayscale', img)
cv2.waitKey(0)
 
cv2.destroyAllWindows()

Output

Using the cv2.imread()

See also

Python PIL Image to Numpy Array

Python JPG to PNG Image

Python RGB Image to Grayscale using OpenCV

Leave a Comment

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