Convert Image to Grayscale with OpenCV in Python

Python OpenCV – Convert image to grayscale

To convert an image to grayscale with OpenCV in Python, you can use cv2.cvtColor() function.

Python OpenCV - Convert image to grayscale

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)


srcInput/source image array.
codeColor 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

  1. Read an image into an array using cv2.imread() function.
  2. 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.
  3. Save the grayscale image using cv2.imwrite() function.


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)

Input Image – test_image_house.jpg

Python OpenCV - Convert image to grayscale - input


Python OpenCV - Convert image to grayscale - output


In this Python OpenCV Tutorial, we converted a color image into a grayscale image using cv2.cvtColor() function, with the help of examples.

Code copied to clipboard successfully 👍