How to automatically select best result from try_all_threshold?

I am applying thresholding on a text-digit based image. Using skimage.filters.try_all_threshold results in 7 of thresholding algorithms getting applied. I am able to get the resut but I am thinking on how I can choose only 1 result to pass the result to next process/dynamically choose 1 best result.

1 answer

  • answered 2018-04-14 21:00 Tonechas

    You need to define a measure of similarity between the original image and the binarized images, and then use the thresholding method that maximixes that measure.

    Demo

    The following code simply aims at putting you on the right track since the function similarity returns a random number rather than a sensible similarity measure. You should implement it or replace it by an appropriate function.

    import numpy as np
    from skimage.data import text
    import skimage.filters
    import matplotlib.pyplot as plt
    
    thresholding_methods = [skimage.filters.threshold_otsu,
                            skimage.filters.threshold_yen,
                            skimage.filters.threshold_isodata,
                            skimage.filters.threshold_li,
                            skimage.filters.threshold_mean,
                            skimage.filters.threshold_minimum,
                            skimage.filters.threshold_mean,
                            skimage.filters.threshold_triangle,
                            ]
    
    def similarity(img, f):
        """Similarity measure between img and f(img)"""
        return np.random.random()
    
    results = np.asarray([similarity(text(), f) for f in thresholding_methods])    
    best_index = np.nonzero(results == results.min())[0][0]    
    best_method = thresholding_methods[best_index]
    threshold = best_method(text())
    binary = text() >= threshold
    
    fig, ax = plt.subplots(1, 1)
    ax.imshow(binary, cmap=plt.cm.gray)
    ax.axis('off')
    ax.set_title(best_method.__name__)
    plt.show(fig)
    

    isodata