Another automatic thresholding algorithm is the triangle algorithm, which is considered a shape-based method because it analyzes the structure (or shape) of the histogram (for example, trying to find valleys, peaks, and other shape histogram features). This algorithm works in three steps. In the first step, a line is calculated between the maximum of the histogram at bmax on the gray level axis and the lowest value bmin on the gray level axis. In the second step, the distance from the line (calculated in the first step) to the histogram for all the values of b [bmin-bmax] is calculated. Finally, in the third step, the level where the distance between the histogram and the line is maximal is chosen as the threshold value.
The way to use the triangle binarization algorithm in OpenCV is very similar to Otsu's algorithm. In fact, only one flag should be changed properly. In case of Otsu's binarization, the cv2.THRESH_OTSU flag was set. In the case of the triangle binarization algorithm, the flag is cv2.THRESH_TRIANGLE, as follows:
ret1, th1 = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_TRIANGLE)
In the next screenshot, you can see the output when applying the triangle binarization algorithm to a noise image (the same image that was used in Otsu's binarization example in the previous section). The full code for this example can be seen in the thresholding_triangle_filter_noise.py script:
You can see that applying a Gaussian filter is a good solution to filter the noise. This way, the triangle binarization algorithm can segment the leaf properly.