Thursday 7 December 2023

Apply Gaussian blur to an image in OpenCV

 

Gaussian blur is used to blur an image.

 

How Gaussian blur works?

Step 1: Create a Gaussian kernel. Kernel is a small 2d matrix with some numerical values. The values in the kernel are calculated using the Gaussian function. The values at the center of the kernel are higher, and they decrease as you move away from the center in a symmetrical manner.

 

Step 2: Perform convolution operation on the image using Kernel matrix. This is performed by selecting the portion that is same as kernel size in the image (start by placing the kernel in the top left corner of the image), at each position of the kernel, the value of the center pixel is replaced with the weighted average of all the pixel values within the kernel.

 

Step 3: Normalize the values, If the blurred image have values that are greater than 255 or less than 0. These values need to be normalized so that they are within the range of 0 to 255

 

How to calculate Gaussian blur in OpenCV?

Using 'cv2.GaussianBlur' method, we can apply Gaussian blur to the image. Gaussian Blur is used to reduce the high frequenc noise in the image and resulting in a smoother, less noisy version of the original image.

 

Signature

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

 

Following table summarizes the parameters of GaussianBlur method.

 

Parameter

Description

src

Source image

ksize

It is a tuple (width, height), represent the size of Gaussian kernel. Kernel determines the extent of the blurring effect.

sigmaX

Specifies the standard deviation of the Gaussian kernel in the X direction.

dst

Specifies the destination image where the result of the Gaussian blur is stored.

sigmaY

Specifies the standard deviation of the Gaussian kernel in the Y direction.

borderType

Specifies how the image boundary is handled during the convolution.

 

Ex: cv.BORDER_DEFAULT, cv2.BORDER_REFLECT, cv2.BORDER_REPLICATE

 

Example

blurred_image = cv.GaussianBlur(image, (5, 5), cv.BORDER_DEFAULT)

 

Find the below working application.

 

gaussian_blur.py 

import cv2 as cv

image = cv.imread('gateway_of_india.png')
cv.imshow('Original image', image)

blurred_image = cv.GaussianBlur(image, (5, 5), cv.BORDER_DEFAULT)
cv.imshow('Blurred image', blurred_image)

cv.waitKey(0)

# Close the OpenCV windows
cv.destroyAllWindows()

Output

Original Image


 

Blurred image


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment