Simplification of image with binarization in OpenCV Python

This post will take you through the Simplification of images with binarization in OpenCV Python. Image binarization is turning a color image into a black-and-white one. Most computer vision applications transform the picture into a binary representation. The more unprocessed an image is, the simpler it is for the computer to interpret its underlying characteristics. Image binarization comes under computer vision.

Now that we have understood why we need image binarization let’s see how Python’s library OpenCV helps us.

Code for the binarization of the image:

import cv2
import numpy as np

#imread reads the image we have provided
img = cv2.imread('photo.jpg')

retval, threshold = cv2.threshold(img, 12, 255, cv2.THRESH_BINARY)
cv2.imshow('original',img)
cv2.imshow('threshold',threshold)
cv2.waitKey(0)
cv2.destroyAllWindows()

Explanation of the code:

Here, the picture is the initial input. The threshold is the following variable, and we select 10. The highest value is the following; we’ve decided to use 255. Finally, we have the threshold type, which we have set to THRESH_BINARY. A criterion of 10 would often not be the best option. Given that there is little light in the photo, we decide to go with 10, which is a low number.

Image used:

Simplification of image with binarization in OpenCV

Output:

Simplification of image with binarization in OpenCV Python

Example 2:

Sometimes we receive images of texts or books that are clicked in dim light and it’s difficult for us to read or understand the text which is written. We will take a sample picture:

Simplification of image with binarization in OpenCV in dim light image

Let’s use our newly learned code from above and make the text in the book a little bit easy for us to read. One can use adaptive thresholding, which will make an effort to change the threshold and, presumably, take the curving pages into consideration.

Code Example of binarization of image:

import cv2
import numpy as np

img = cv2.imread('book.jpg')
grayscaled = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
th = cv2.adaptiveThreshold(grayscaled, 150, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1)
cv2.imshow('original',img)
cv2.imshow('Adaptive threshold',th)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output:

Simplification of image with binarization in OpenCV in dim light image

Now the text in the image is visible and easy to understand. With this, we have concluded our tutorial. Learn, the concept of image sharpening and contrasting in Python using OpenCV

Leave a Reply

Your email address will not be published. Required fields are marked *