⊕
⊖
Contents
Python OpenCV – Convert image to grayscale
To convert an image to grayscale with OpenCV in Python, you can use cv2.cvtColor() function.
In this tutorial, you will learn how to use cv2.cvtColor() function to convert a given color image to grayscale, with examples.
Syntax of cvtColor()
The syntax of cv2.cvtColor() function is
cv2.cvtColor(src, code, dst, dstCn)
where
Parameter | Description |
---|---|
src | Input/source image array. |
code | Color space conversion code. Refer for list of conversion codes. |
dst | [Optional] Output array of the same size and type as src. |
dstCn | [Optional] Number of channels in the destination image. |
To convert given color image to grayscale image, we can use the code of cv2.COLOR_BGR2GRAY.
Steps to convert an image to grayscale
- Read an image into an array using cv2.imread() function.
- Call the cv2.cvtColor() function and pass the input image array and color code of cv2.COLOR_BGR2GRAY as arguments. It returns the grayscale image array.
- Save the grayscale image using cv2.imwrite() function.
Example
In the following program, we convert an input image to grayscale image using cvtColor() function of cv2 module.
Python Program
import cv2
# Load the image
img = cv2.imread('test_image_house.jpg')
# Convert input image to grayscale
grayscale_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Save grayscale image
cv2.imwrite('grayscale_img.jpg', grayscale_img)
CopyInput Image – test_image_house.jpg
grayscale_img.jpg
Summary
In this Python OpenCV Tutorial, we converted a color image into a grayscale image using cv2.cvtColor() function, with the help of examples.