In the previous examples, we have applied the simple thresholding operation to a custom-made image in order to see how the different parameters work. In this section, we are going to apply cv2.threshold() to a real image. The thresholding_example.py script performs this. We applied the cv2.threshold() function with different thresholding values as follows – 60,70,80,90,100,110,120,130:
ret1, thresh1 = cv2.threshold(gray_image, 60, 255, cv2.THRESH_BINARY)
ret2, thresh2 = cv2.threshold(gray_image, 70, 255, cv2.THRESH_BINARY)
ret3, thresh3 = cv2.threshold(gray_image, 80, 255, cv2.THRESH_BINARY)
ret4, thresh4 = cv2.threshold(gray_image, 90, 255, cv2.THRESH_BINARY)
ret5, thresh5 = cv2.threshold(gray_image, 100, 255, cv2.THRESH_BINARY)
ret6, thresh6 = cv2.threshold(gray_image, 110, 255, cv2.THRESH_BINARY)
ret7, thresh7 = cv2.threshold(gray_image, 120, 255, cv2.THRESH_BINARY)
ret8, thresh8 = cv2.threshold(gray_image, 130, 255, cv2.THRESH_BINARY)
And finally, we show the thresholded images as follows:
show_img_with_matplotlib(cv2.cvtColor(thresh1, cv2.COLOR_GRAY2BGR), "threshold = 60", 2)
show_img_with_matplotlib(cv2.cvtColor(thresh2, cv2.COLOR_GRAY2BGR), "threshold = 70", 3)
show_img_with_matplotlib(cv2.cvtColor(thresh3, cv2.COLOR_GRAY2BGR), "threshold = 80", 4)
show_img_with_matplotlib(cv2.cvtColor(thresh4, cv2.COLOR_GRAY2BGR), "threshold = 90", 5)
show_img_with_matplotlib(cv2.cvtColor(thresh5, cv2.COLOR_GRAY2BGR), "threshold = 100", 6)
show_img_with_matplotlib(cv2.cvtColor(thresh6, cv2.COLOR_GRAY2BGR), "threshold = 110", 7)
show_img_with_matplotlib(cv2.cvtColor(thresh7, cv2.COLOR_GRAY2BGR), "threshold = 120", 8)
show_img_with_matplotlib(cv2.cvtColor(thresh8, cv2.COLOR_GRAY2BGR), "threshold = 130", 9)
The output of this script can be seen in the following screenshot:
As you can see, the threshold value plays a critical role when thresholding images using cv2.threshold(). Suppose that your image-processing algorithm tries to recognize the digits inside the grid. If the threshold value is low (for example, threshold = 60), there are some digits missing in the thresholded image. On the other hand, if the threshold value is high (for example, threshold = 120), there are some digits occluded by black pixels. Therefore, establishing a global threshold value for the entire image is quite difficult. Moreover, if the image is affected by different illumination conditions, this task is almost impossible. This is why other thresholding algorithms can be applied to threshold the images. In the next section, the adaptive thresholding algorithm will be introduced.