Converting an OpenCV Image to Black and White in Python

Here, we will learn how to change a given color picture into black and white in Python using the OpenCV module?
Submitted by Bipin Kumar, on January 20, 2021

To install OpenCV just type the below command in your command prompt:

pip install OpenCV-python

OpenCV is the most useful library in Python which makes it easier to work on image or video processing in Python. One thing that comes to your mind that how to read the image from the storage and work on it. So, no need to worry about this we will solve this problem in a simple way by using the OpenCV in Python. One thing we have to note that in the Python program cv2 is used instead of OpenCV because it makes it easier for the user to understand and import in the program in a better way. 

Suppose a color picture of mine is stored at the location "C:\Users\BIPIN KUMAR\Desktop\machine learning/bipin" and we will convert this color picture into black and white or grey color in the below program.


import cv2

A=cv2.imread(r"C:\Users\BIPIN KUMAR\Desktop\machine learning/bipin.jpg")
B=cv2.imread(r"C:\Users\BIPIN KUMAR\Desktop\machine learning/bipin.jpg",0)



OpenCV Image to Black and White in Python


Here, we have included the cv2 module in our program by using the import function. The function imread() use to read the original location of our jpg file from the storage. Since our task was to get the color image in black and white or gray that's why here we are using the zero(0). The term waitKey(0) is used to hold the output screen until the user press any key and destroyallWindows() use to close the output window and to come back on the editor page. To see the output cv2 provide imshow() function in which we have given two arguments one is the title of the output screen and another is variable in which the output picture has assigned.

Related Programs

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.