I’ve found some formulas to estimate the median of the histogram but they don’t work.

Where “l” is the lower border of the median group, “F” is the cumulative frequency up to the median group, “f” is the frequency of the median group, “w” is the width of the median group. But i have specific gray levels, not “groups”.

I want to find the histogram medians of a grayscale image different regions, and use it to threshold each image region with a different threshold value.

int median(Mat& hist) {
float n = 0;
for (int i = 0; i < 256; i++) {
n += hist.at<float>(i);
}
float m = n / 2;
n = 0;
int j = 0;
for (j; j < 256; j++) {
if (n < m)
n += hist.at<float>(j);
else break;
}
return j;
}