ADVERTISEMENT
ADVERTISEMENT

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.

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)

cv2.imshow("bipin",B)
cv2.waitKey(0)
cv2.destroyallWindows()

Output:

OpenCV Image to Black and White in Python

Explanation:

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.

ADVERTISEMENT


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.