Ask Your Question
0

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

asked 2017-10-17 04:57:47 -0600

Asad gravatar image

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 flag offensive close merge delete

Comments

LBerger gravatar imageLBerger ( 2017-10-17 05:27:06 -0600 )edit

^^ 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..)

berak gravatar imageberak ( 2017-10-17 06:44:32 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
2

answered 2017-10-17 07:05:05 -0600

VxW gravatar image

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...

edit flag offensive delete link more

Question Tools

1 follower

Stats

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

Seen: 17,262 times

Last updated: Oct 17 '17