Search code examples
c++opencvfiltermedian

Apply median filter manually with opencv, differences with medianBlur function


When I apply median filter like this:

Mat medianFilter;
medianBlur(histEqu, medianFilter, 3);

I would expect the same results that if I apply median filter like:

Mat manualMedianFiler;
    float factor = 1 / 9.0;
    Mat kernelMedian = (Mat_<float>(3, 3) <<
        factor, factor, factor,
        factor, factor, factor,
        factor, factor, factor);
    filter2D(histEqu, manualMedianFiler, CV_8U, kernelMedian, Point(-1,-1), 0, 4);

The resultant matrix are similar, but they are not equal. Am I doing something wrong? Which is the correct way to apply median filter?


Solution

  • As a complement to @Miki's answer I remind you that a median filter is one that given N samples (in this case taken from the 3x3 square around central pixels) sorts their value and takes the one in the middle. So given (1, 7, 2, 2, 1, 9, 22, 4, 5) after sorting you get (1, 1, 2, 2, 4, 5, 7, 9, 22) and the median is 4, while the mean value is (1 + 7 + 2 + 2 + 1 + 9 + 22 + 4 + 5) / 9 = 53/9 -> 5.8.

    In short: a median filter is not linear.

    Median filter is preferred where one wants to remove spikes.