arghhjayy
arghhjayy

Reputation: 137

How does Opencv MedianBlur actually work?

I've been working with a grayscale image that has a lot of Salt and Pepper noise and came to know that MedianBlur is very useful. So I used the Python version of Opencv(cv2.medianBlur()). It worked but didn't work in the way I wanted. So I was looking for the actual algorithm it worked on and got the following explanation:

If you have a kernel size(k) of 5, then for every 5(row count)x5(column count) square window, the central pixel of this window will get replaced by the Median value of all the elements in it. So, for instance, consider this window:

      [[11,  4, 17,  1,  5],
       [ 6, 14,  0, 12, 16],
       [24, 19, 13, 18, 23],
       [ 7, 11, 11, 10,  5],
       [10, 13, 23,  3,  0]] 

Here, the central element, 13 will get replaced by the Median of all these elements, i.e. 11. Is this correct? If yes, what happens to the first 2 rows, since there can't be elements in the first two rows which are the central element for ANY window? As per my observation(comparing the original and processed image), the first two rows change too.

Upvotes: 2

Views: 4586

Answers (3)

WinHtut
WinHtut

Reputation: 131

Here, the function cv2.medianBlur() computes the median of all the pixels under the kernel window and the central pixel is replaced with this median value. This is highly effective in removing salt-and-pepper noise. One interesting thing to note is that, in the Gaussian and box filters, the filtered value for the central element can be a value which may not exist in the original image. However this is not the case in median filtering, since the central element is always replaced by some pixel value in the image. This reduces the noise effectively. The kernel size must be a positive odd integer.

Upvotes: 0

ilke444
ilke444

Reputation: 2741

According to the medianBlur() documentation, it uses BORDER_REPLICATE internally to process border pixels.

BORDER_REPLICATE 
Python: cv.BORDER_REPLICATE

aaaaaa|abcdefgh|hhhhhhh 

So it repeats the bordering pixels until all pixels are the mid pixel of a window.

EDIT: To apply a kernel with a size of 5x5, the first pixel should be at the third row and column of the image. It means replicate the the border by two pixels. So your image becomes this internally:

  [[11, 11, 11,  4, 17,  1,  5,  5,  5],
   [11, 11, 11,  4, 17,  1,  5,  5,  5],
   [11, 11, 11,  4, 17,  1,  5,  5,  5],
   [ 6,  6,  6, 14,  0, 12, 16, 16, 16],
   [24, 24, 24, 19, 13, 18, 23, 23, 23],
   [ 7,  7,  7, 11, 11, 10,  5,  5,  5],
   [10, 10, 10, 13, 23,  3,  0,  0,  0],
   [10, 10, 10, 13, 23,  3,  0,  0,  0],
   [10, 10, 10, 13, 23,  3,  0,  0,  0]]

Upvotes: 1

Alex Alex
Alex Alex

Reputation: 2018

From documentation:

The median filter uses #BORDER_REPLICATE internally to cope with border pixels, see #BorderTypes

Upvotes: 0

Related Questions