the NumPy library.import numpy as np def compute_otsu_criteria(im, th): # create the thresholded image thresholded_im = np.zeros(im.shape) thresholded_im[im >= th] = 1 # compute weights nb_pixels = im.size nb_pixels1 = np.count_nonzero(thresholded_im) weight1 = nb_pixels1 / nb_pixels weight0 = 1 - weight1 # if one the classes is empty, eg all pixels are below or above the threshold, that threshold will not be considered # in the search for the best threshold if weight1 == 0 or weight0 == 0: return np.inf # find all pixels belonging to each class val_pixels1 = im[thresholded_im == 1] val_pixels0 = im[thresholded_im == 0] # compute variance of these classes var0 = np.var(val_pixels0) if len(val_pixels0) > 0 else 0 var1 = np.var(val_pixels1) if len(val_pixels1) > 0 else 0 return weight0 * var0 + weight1 * var1 im = # load your image as a numpy array. # For testing purposes, one can use for example im = np.random.randint(0,255, size = (50,50)) # testing all thresholds from 0 to the maximum of the image threshold_range = range(np.max(im)+1) criterias = [compute_otsu_criteria(im, th) for th in threshold_range] # best threshold is the one minimizing the Otsu criteria best_threshold = threshold_range[np.argmin(criterias)] Python libraries dedicated to image processing such as OpenCV and Scikit-image propose built-in implementations of the algorithm. Limitations and variations Otsu's method performs well when the histogram has a bimodal distribution with a deep and sharp valley between the two peaks. Like all other global thresholding methods, Otsu's method performs badly in case of heavy noise, small objects size, inhomogeneous lighting and larger intra-class than inter-class variance. In those cases, local adaptations of the Otsu method have been developed. Moreover, the mathematical grounding of Otsu's method models the histogram of the image as a mixture of two Normal distributions with equal variance and equal size. Otsu's thresholding may however yield satisfying results even when these assumptions are not met, in the same way statistical tests (to which Otsu's method is heavily connected) can perform correctly even when the working assumptions are not fully satisfied. However, several variations of Otsu's methods have been proposed to account for more severe deviations from these assumptions, such as the Kittler-Illingworth method. A variation for noisy images A popular local adaptation is the two-dimensional Otsu's method, which performs better for the object segmentation task in noisy images. Here, the intensity value of a given pixel is compared with the average intensity of its