Skip to content

Instantly share code, notes, and snippets.

@heisters
Created June 18, 2015 22:38
Show Gist options
  • Save heisters/9cd68181397fbd35031b to your computer and use it in GitHub Desktop.
Save heisters/9cd68181397fbd35031b 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;
}
}
@belgraviton
Copy link

Thanks. Works fine.

@TimZaman
Copy link

Thanks for sharing. But only works for 8 bit, although it does allow any other type (with invalid results) to pass.

@royss7
Copy link

royss7 commented Jun 17, 2016

thanks for sharing

@Finfa811
Copy link

Finfa811 commented Aug 3, 2016

Good work

@rayryeng
Copy link

@TimZaman Simply change the 256 to whatever the maximum number is for the datatype + 1. So if it's unsigned 16-bit, this would be 65536 or if it's unsigned 32-bit, it would be 2^32, and so on.

@facug91
Copy link

facug91 commented Jan 26, 2017

@rayryeng be carefull with that, because the function isn't going to work well with all the other types. If you use int, the size of the array would be gigantic, and hence very slow.
@heisters the function is not taking into account when the matrix is even-sized, in which should use the two middle values.
Thank you!

@rayryeng
Copy link

@facug91 - I know. That's why I don't use this code when calculating the median value. I use something else instead. Just wanted to put that comment in for the sake of completeness.

@johnlohit
Copy link

@rayryeng can you tell me what you use instead?

@hoonhoons
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment