- ret, thresh = cv2.threshold(gray_image, 100, 255, cv2.THRESH_BINARY)
- thresh = cv2.adaptiveThreshold(gray_image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 9, 2)
- ret, th = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
- ret, th = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_TRIANGLE)
- Otsu's thresholding using scikit-image can be applied as follows:
thresh = threshold_otsu(gray_image)
binary = gray_image > thresh
binary = img_as_ubyte(binary)
Remember that the threshold_otsu(gray_image) function returns the threshold value based on Otsu's binarization algorithm. Afterwards, with this value, the binary image is constructed (dtype= bool), which should be converted into an 8-bit unsigned integer format (dtype= uint8) for proper visualization. The img_as_ubyte() function is used for this purpose.
- Triangle thresholding using scikit-image can be applied as follows:
thresh_triangle = threshold_triangle(gray_image)
binary_triangle = gray_image > thresh_triangle
binary_triangle = img_as_ubyte(binary_triangle)
- Niblack's thresholding using scikit-image can be applied as follows:
thresh_niblack = threshold_niblack(gray_image, window_size=25, k=0.8)
binary_niblack = gray_image > thresh_niblack
binary_niblack = img_as_ubyte(binary_niblack)
This algorithm was originally designed for text recognition. See the publication, An introduction to Digital Image Processing (1986), for further details.
- Sauvola's thresholding using scikit-image and a window size of 25 can be applied as follows:
thresh_sauvola = threshold_sauvola(gray_image, window_size=25)
binary_sauvola = gray_image > thresh_sauvola
binary_sauvola = img_as_ubyte(binary_sauvola)
Two key points are worth noting:
- Sauvola is a modification of the Niblack technique
- This algorithm was originally designed for text recognition
See the publication, Adaptive document image binarization (2000), for further details.
- To get the array with the values for thresholding the image, we make use of np.arange(). As we want an array with values in the range [60-130] with step 10, the following line codes this functionality:
threshold_values = np.arange(start=60, stop=140, step=10)
Afterwards, we iterate to apply the cv2.threshold() function with the corresponding threshold value defined in threshold_values:
thresholded_images = []
for threshold in threshold_values:
ret, thresh = cv2.threshold(gray_image, threshold, 255, cv2.THRESH_BINARY)
thresholded_images.append(thresh)
Finally, we show the thresholded images contained in the thresholded_images array. The full code can be seen in the thresholding_example_arange.py script.