Here are the four ways to convert an image to grayscale in Python:
- Using cv2.cvtColor()
- Using image.convert()
- Using PIL.ImageOps.grayscale()
- Using the cv2.imread()
Input Image
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
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
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()
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
See also
Python PIL Image to Numpy Array
Python RGB Image to Grayscale using OpenCV
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.