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:
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.
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.
Figure 1-1: Original image(left), Median blurred image (right).