Median Blurring

Mean blurring performs smoothing operation by replacing the central pixel with the median value from the neighborhood. This filter is especially useful in situation when we have a salt-and-pepper type of noise in the image. OpenCV implements the median blurring in the function medianBlur(). The signature of the medianBlur() is as shown below:

cv2.medianBlur(src, ksize)

The parameters of the above function are described as below:

Parameter Description

src

input image; it can have any number of channels, which are processed independently, but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F.

ksize

Neighborhood size. It means how many pixels around the central pixels will be used to perform blurring of central pixel.It must be odd and greater than 1.

Let us look at an example of how to apply median blur on an image. Code 1-1 shows and example of application of median filter to remove salt and pepper noise.

Code 1-1 Median Blurring
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import cv2
import numpy as np
try:
    path = r'F:\img\sp.jpg'
    img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
    out = cv2.medianBlur(img,5)
    cv2.imshow('Original Image',img)
    cv2.imshow('Median Blur',out)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
except Exception as e:
    print(str(e))

Line 1 and 2: We start by importing OpenCV and numpy libraries.
Line 3: This line defines a try block. The exception block (Line 11-12) is associated with this block. If any exception occurs, it throws it and code in exception block is executed.
Line 4: Define path of the image to read.
Line 5: The image is read. Note that we are reading a grayscale image (see 2nd parameter).
Line 6: Using OpenCV’s medianBlur() function the input image is blurred. This line actually performs the median blurring on the input image. The second parameter provides the size of the kernel used for blurring. It removes the salt and pepper noise from the input image.
Line 7-8: It displays both blurred and original image in a separate window.
Line 9: waitKey(0) function makes the window wait until user presses any keyboard button.
Line 10: Object of all the windows opened will be destroyed and closed.

The output obtained for the code shown above is shown in Figure 1-1.

No image
Figure 1-1: Original image(left), Median blurred image (right).

OpenCV Tutorials