Skip to content

Instantly share code, notes, and snippets.

@anujonthemove
Forked from heisters/cv_median.cpp
Created July 19, 2016 18:25
Show Gist options
  • Save anujonthemove/f9395693a70e8d0ff51fabb2962d940a to your computer and use it in GitHub Desktop.
Save anujonthemove/f9395693a70e8d0ff51fabb2962d940a to your computer and use it in GitHub Desktop.
Find the median of a single channel using OpenCv
namespace cv {
// calculates the median value of a single channel
// based on https://github.com/arnaudgelas/OpenCVExamples/blob/master/cvMat/Statistics/Median/Median.cpp
double median( cv::Mat channel )
{
double m = (channel.rows*channel.cols) / 2;
int bin = 0;
double med = -1.0;
int histSize = 256;
float range[] = { 0, 256 };
const float* histRange = { range };
bool uniform = true;
bool accumulate = false;
cv::Mat hist;
cv::calcHist( &channel, 1, 0, cv::Mat(), hist, 1, &histSize, &histRange, uniform, accumulate );
for ( int i = 0; i < histSize && med < 0.0; ++i )
{
bin += cvRound( hist.at< float >( i ) );
if ( bin > m && med < 0.0 )
med = i;
}
return med;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment