Blurrings in cv2 – Simple Blur, Box Blur, Gaussian Blur, and Median Blur – 2024

In today’s blog, we will see how to perform the most famous 4 types of Blurrings in cv2 (Simple Blur, Box Blur, Gaussian Blur, and Median Blur).

This is going to be a very interesting blog, so without any further due, Let’s do it…

Checkout the video here – https://youtu.be/TnjhJpPXkCU

Step 1 – Let’s start with importing the required modules to perform blurrings in cv2.

import cv2
import matplotlib.pyplot as plt

Importing cv2 for performing blurrings and matplotlib to visualize the results in the end.

Step 2 – Let’s read and visualize the image…

img = cv2.imread('test.tiff')
cv2.imshow('Image', img)
cv2.waitKey(0)

In this step, we are simply reading and visualizing the image.

Step 3 – Convert the image channels from BGR to RGB.

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

As we know that cv2 converts the channels of the image to BGR when it loads the image, that’s why we need to convert it back to the RGB channels to visualize it properly in the last step.

Types of blurrings in cv2…

1. Blurring using Box Filter

Syntax: cv2.boxFilter(src, dst, ddepth, ksize, anchor, normalize, borderType)

Parameters:

src Mat object representing the source (input image) for this operation.
dst Mat object representing the destination (output image) for this operation.
ddepth A variable of the type integer representing the depth of the output image.
ksize Size object representing the size of the blurring kernel.
anchor A variable of the type integer representing the anchor point.
Normalize A variable of the type boolean specifying weather the kernel should be normalized.
borderType An integer object representing the type of the border used.
# blurrings in cv2
box = cv2.boxFilter(img, -1, (25, 25))
  • We are applying a simple box filter(kernel) of size 25X25 size.
  • The Box Filter operation is similar to the averaging blur operation; it applies a bilateral image to a filter.
  • Here, you can choose whether the box should be normalized or not.

2. Simple Blur

Syntax: cv2.blur(src, ksize[, dst[, anchor[, borderType]]])

Parameters:

srcIt is the image that is to be blurred.
ksizeA tuple representing the blurring kernel size.
dstIt is the output image of the same size and type as src.
anchorIt is a variable of type integer representing anchor point and it’s default value Point is (-1, -1) which means that the anchor is at the kernel center.
borderTypeIt depicts what kind of border to be added. It is defined by flags like cv2.BORDER_CONSTANTcv2.BORDER_REFLECT, etc
# blurrings in cv2
blur = cv2.blur(img, (15, 15))
  • We are performing simple blurring using a 15X15 kernel.
  • cv2.blur() method is used to blur an image using the normalized box filter.
  • The function smooths an image using the kernel which is represented as:
blurrings in cv2

NOTE Here normalized means that the sum of all the elements of the matrix will be equal to 1.

3. Gaussian Blur

Syntax: cv2.GaussianBlur(src, ksize, sigmaX[, dst[, sigmaY[, borderType=BORDER_DEFAULT]]] )

Parameters:

srcinput image
dstoutput image
ksizeGaussian Kernel Size. [height width]. height and width should be odd and can have different values. If ksize is set to [0 0], then ksize is computed from sigma values.
sigmaXKernel standard deviation along X-axis (horizontal direction).
sigmaYKernel standard deviation along Y-axis (vertical direction). If sigmaY=0, then sigmaX value is taken for sigmaY
borderTypeSpecifies image boundaries while kernel is applied on image borders. Possible values are : cv.BORDER_CONSTANT cv.BORDER_REPLICATE cv.BORDER_REFLECT cv.BORDER_WRAP cv.BORDER_REFLECT_101 cv.BORDER_TRANSPARENT cv.BORDER_REFLECT101 cv.BORDER_DEFAULT cv.BORDER_ISOLATEDsrc
# blurrings in cv2
gaussian = cv2.GaussianBlur(img, (17, 17), 0)
  • We are applying a Gaussian filter(kernel) of size 17X17 size.
  • In this method, instead of a box filter, a Gaussian kernel is used. It is done with the function, cv.GaussianBlur().
  • We should specify the width and height of the kernel which should be positive and odd. We also should specify the standard deviation in the X and Y directions, sigmaX and sigmaY respectively. If only sigmaX is specified, sigmaY is taken as the same as sigmaX. If both are given as zeros, they are calculated from the kernel size.
  • Gaussian blurring is highly effective in removing Gaussian noise from an image.

4. Median Blur

Syntax: cv2.medianBlur(src, dst, ksize)

Parameters:

src Mat object representing the source (input image) for this operation.
dst Mat object representing the destination (output image) for this operation.
ksize  A Size object representing the size of the kernel.
median = cv2.medianBlur(img, ksize=5)
  • We are applying a Median Blur filter of kernel size 5X5.
  • Here, the function cv.medianBlur() takes the median of all the pixels under the kernel area, and the central element is replaced with this median value. This is highly effective against salt-and-pepper noise in an image.
  • Interestingly, in the above filters, the central element is a newly calculated value which may be a pixel value in the image or a new value. But in median blurring, the central element is always replaced by some pixel value in the image. It reduces the noise effectively. Its kernel size should be a positive odd integer.

Let’s see the whole code for blurrings in cv2…

import cv2
import matplotlib.pyplot as plt

img = cv2.imread('test.tiff')

cv2.imshow('i', img)
cv2.waitKey(0)

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# blurrings in cv2
box = cv2.boxFilter(img, -1, (25, 25))
blur = cv2.blur(img, (15, 15))
gaussian = cv2.GaussianBlur(img, (17, 17), 0)
median = cv2.medianBlur(img, ksize=5)

images = [box, blur, gaussian, median]
title =  ['box', 'blur', 'gaussian', 'median']

# blurrings in cv2
for i in range(4):
    plt.subplot(2, 2, i+1)
    plt.title(title[i])
    plt.imshow(images[i])
    plt.xticks([])
    plt.yticks([])

plt.show()
cv2.waitKey(0)
cv2.destroyAllWindows()

In the last steps, we are just using the subplot method of matplotlib’s pyplot package to create a subplot of 2X2 as shown below.

Final Results…

blurrings in cv2
All Blurrings…

NOTE – If your main motive of blurring is just to remove noise then just go with Gaussian Blur, it works best in this scenario.

You can read more about these blurrings here.

Do let me know if there’s any query regarding blurrings in cv2 by contacting me by email or LinkedIn.

So this is all for this blog folks, thanks for reading it and I hope you are taking something with you after reading this and till the next time ?…

Read my previous post: BGR PALETTE – A FUN APPLICATION IN PYTHON USING OPENCV

Check out my other machine learning projectsdeep learning projectscomputer vision projectsNLP projectsFlask projects at machinelearningprojects.net.

Leave a Reply

Your email address will not be published. Required fields are marked *