Chapter 7

  1. ret, thresh = cv2.threshold(gray_image, 100, 255, cv2.THRESH_BINARY)
  2. thresh = cv2.adaptiveThreshold(gray_image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 9, 2)
  3. ret, th = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
  4. ret, th = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_TRIANGLE)
  5. 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. 

  1. 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)
  1. 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.

  1. 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:

See the publication, Adaptive document image binarization (2000), for further details.

  1. 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.