
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Grayscaling of Images using OpenCV
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.
Example
# 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 cv2.waitKey() # destroy all the windows cv2.destroyAllWindows()
Output
If you run the above code, then you will see the image in grayscale as shown below.
Conclusion
If you have any doubts in the tutorial, mention them in the comment section.
- Related Articles
- Erosion and Dilation of images using OpenCV in Python
- Addition and Blending of images using OpenCv in Python
- Arithmetic Operations on Images using OpenCV in Python
- Color Identification in Images using Python and OpenCV
- Dividing Images Into Equal Parts Using OpenCV Python
- How to compare histograms of two images using OpenCV Python?
- Draw geometric shapes on images using Python OpenCv module
- Drawing with Mouse on Images using Python and OpenCV
- How to blend images using image pyramids in OpenCV Python?
- OpenCV Python – Implementing feature matching between two images using SIFT
- Reading and displaying images using OpenCV
- How to join two images horizontally and vertically using OpenCV Python?
- OpenCV Python – Matching the key points of two images using ORB and BFmatcher
- Dilating images using the OpenCV function dilate()
- How to apply custom filters to images (2D convolution) using OpenCV Python?

Advertisements