Image Contrast Enhancement Threshold Selection
What you are looking for called Otsu Method / Otsu Thresholding.
It solves an optimization problem to set the optimal threshold between two modal distribution.