Finding minimum in the middle of a histogram I'm building an image processing pipeline and one step in the process requires thresholding the image based on saturation.

Example code using OpenCV-Python:

H, S, V = cv2.split(img)
mask = cv2.threshold(S, low, 255, cv2.THRESH_BINARY)


I know how to set the low value manually, if I look at the histogram:



(the red arrow indicates the value I would pick)

My question is: how can I programatically find that value?

Some non-rigorous descriptions of the problem:


find the lower boundary of the right-most "hump"
find the minimum value that's not at the edges
To me, this looks like you want something like 


start from right. Add up bins' values, as long as 


the added bin is larger than the last or
the value added by that bin divided by the current sum is still above a fixed threshold



Adjust the threshold to fit your needs.

Often, things like smoothing the histogram (effectively: applying a low pass filter to it) help. Or you do something like finding a function fit, something like a polynomial of fixed degree (let's say 5) that minimizes some error function (for example, sum square absolute error in all bins), and then analytically find local extrema.