Ask Your Question

# How to calculate the median of pixel values in opencv (python)

I want to get an image matrix of a still image and then calculate the median of that matrix for some purpose. Can you help me how to do so?

edit retag close merge delete

## Comments

^^ yes, for blurring.

what exactly do you need this for ? opencv has no direct way for this.

(you could do something with histograms, but we'd need to know more..)

## 1 answer

Sort by » oldest newest most voted

you can try this:

double medianMat(cv::Mat Input, int nVals){
// COMPUTE HISTOGRAM OF SINGLE CHANNEL MATRIX
float range[] = { 0, nVals };
const float* histRange = { range };
bool uniform = true; bool accumulate = false;
cv::Mat hist;
calcHist(&Input, 1, 0, cv::Mat(), hist, 1, &nVals, &histRange, uniform, accumulate);

// COMPUTE CUMULATIVE DISTRIBUTION FUNCTION (CDF)
cv::Mat cdf;
hist.copyTo(cdf);
for (int i = 1; i <= nVals-1; i++){
cdf.at<float>(i) += cdf.at<float>(i - 1);
}
cdf /= Input.total();

// COMPUTE MEDIAN
double medianVal;
for (int i = 0; i <= nVals-1; i++){
if (cdf.at<float>(i) >= 0.5) { medianVal = i;  break; }
}
return medianVal/nVals;
}


this great and fast solution was found at (see last answer): https://stackoverflow.com/questions/3...

more

Official site

GitHub

Wiki

Documentation

## Stats

Asked: 2017-10-17 04:57:47 -0500

Seen: 11,878 times

Last updated: Oct 17 '17