We learned about thresholding in Chapter 2, Filters and Features. Now, let’s see how it can be implemented using OpenCV. OpenCV has an inbuilt threshold() function, which takes a grayscale image, threshold value, and new value to be assigned if the value is greater than the threshold and type of thresholding as input. The types of thresholding are:
The following code is an example for thresholding:
>>> import cv2>>> img = cv2.imread("image.jpg")>>> gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)>>> new_img = cv2.threshold(gray,120,255,cv2.THRESH_BINARY)>>> cv2.imwrite("thresholding.jpg", new_img)>>> cv2.imshow("thresholding", new_img) ...