Otsu’s method is a very old but still used adaptive segmentation algorithm due to its simplicity.
Segmenting an image by setting a threshold is probably the easiest possible approach, but that threshold needs to be established somehow. Otsu’s method looks at the histogram and tries to minimize the within-class variance. In other words, it tries to find a threshold such that the variance of the resulting both classes in the Gaussian distributions is as small as possible.
In the picture above we can guess that a good threshold might be somewhere in between those two Gaussian-like distributions. If you want to learn more about Otsu’s method, check this video.
The code is provided in the Source code section.