You can convert an image into black and white using OpenCV Python by following the given steps. I highly recommend you get the “Computer Vision: Models, Learning, and Inference Book” to learn Computer Vision.
Step 1
Import the OpenCV library. If OpenCV is not installed in your system then first install it using This Method.
import cv2 #cv2 is used for OpenCV library
Step 2
Now read the image from the location. In my case “F:\\AiHints” is the location and “top30.png” is the name of the image. Change it according to your image location and name.
image = cv2.imread("F:\\AiHints\\top30.png") #imread is use to read an image from a location
Step 3
First, convert the image into grayscale then use this grayscale image and convert it into black and white using the cv2.threshold function.
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) (thresh, binary) = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY)
Step 4
Now display the original, grayscale, and black and white image using the following code.
cv2.imshow("Original Image",img) cv2.imshow("Gray Image",gray_image) cv2.imshow("Black and White Image",binary)
Step 5
waitKey() open the image for a specific time in milliseconds until you press any key. The function cv2.destroyAllWindows() will destroy all the windows that we created.
cv2.waitKey(0) cv2.destroyAllWindows()