How to convert image to binary image

In this article, you’ll see how to convert an image into a binary image using OpenCV in Python. I highly recommend you get the “Computer Vision: Models, Learning, and Inference Book” to learn Computer Vision. For converting an image into a binary image just follow these steps:

Step 1: Install OpenCV

If OpenCV is not installed, then first install it using this code.

pip install opencv-python

Step 2: Import the OpenCV library

import cv2

Step 3: Read the Image

Now read the image from the location.

img = cv2.imread("C:\\AiHints\\cat.jpg")

Step 4: Grayscale

Now, convert the image into grayscale using cv2.cvtColor() function.

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Step 5: Threshold (Binary Image)

In this step, convert the grayscale image into a binary image using the cv2.threshold() function. You can change the value of the threshold. Try different values and see the results.

# Set threshold and maximum value
thresh = 100
maxValue = 255

# Binary Threshold
th, binary = cv2.threshold(gray, thresh, maxValue, cv2.THRESH_BINARY)

Step 6: Display the Output

Now, display the original, gray, and binary image.

cv2.imshow("Original Image", img)
cv2.imshow("Gray Image", gray)
cv2.imshow("Binary Image", binary)

cv2.waitKey(0)
cv2.destroyAllWindows()

Output:

Original Image
Original Image
Gray Image
Gray Image
Binary Image
Binary Image

Leave a Comment

Your email address will not be published.