Python Grayscaling of Images using OpenCV

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to learn how to change the grayscaling of an image using Grayscaling is the process of changing the images from different colour spaces like RGB,CMYK, etc.., to shades of gray. Install the OpenCV module if you didn't install it before.

pip install opencv-python

After installing the OpenCV module. Follow the below steps to write the code.

  • Import the cv2 module.
  • Read the image with cv2.imread(image_path) and store it in a variable.
  • Convert the image colour scale using cv2.cvtColor(image, cv2.COLOR_BGR1GRAY) and store it in a variable.
  • Show the image using cv2.imshow(image).
  • Wait until any key press to exit using the cv2.waitKey().
  • Destroy all the opened windows using cv2.destroyAllWindows() method.


# importing the opencv(cv2) module
import cv2
# reading the image
image = cv2.imread('lion.png')
# changing the color space
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# showing the resultant image
cv2.imshow('Grayscale Lion', gray_image)
# waiting until key press
# destroy all the windows


If you run the above code, then you will see the image in grayscale as shown below.


If you have any doubts in the tutorial, mention them in the comment section.

Published on 07-Jul-2020 08:59:57