In this OpenCV tutorial, we will learn how to apply Gaussian filter for image smoothing or blurring using OpenCV Python with cv2.GaussianBlur() function.

Image Smoothing using OpenCV Gaussian Blur

As in any other signals, images also can contain different types of noise, especially because of the source (camera sensor). Image Smoothing techniques help in reducing the noise. In OpenCV, image smoothing (also called blurring) could be done in many ways.

Gaussian filters have the properties of having no overshoot to a step function input while minimizing the rise and fall time. In terms of image processing, any sharp edges in images are smoothed while minimizing too much blurring.

Syntax of cv2 GaussianBlur() function

OpenCV provides cv2.gaussianblur() function to apply Gaussian Smoothing on the input source image. Following is the syntax of GaussianBlur() function :

</>
Copy
dst = cv2.GaussianBlur(src, ksize, sigmaX[, dst[, sigmaY[, borderType=BORDER_DEFAULT]]] )
ParameterDescription
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_ISOLATED

Examples

1. Apply Gaussian Blur on Image

In this example, we will read an image, and apply Gaussian blur to the image using cv2.GaussianBlur() function.

Python Program

</>
Copy
import cv2
import numpy
 
# read image
src = cv2.imread('/home/img/python.png', cv2.IMREAD_UNCHANGED)

# apply guassian blur on src image
dst = cv2.GaussianBlur(src,(5,5),cv2.BORDER_DEFAULT)

# display input and output image
cv2.imshow("Gaussian Smoothing",numpy.hstack((src, dst)))
cv2.waitKey(0) # waits until a key is pressed
cv2.destroyAllWindows() # destroys the window showing image

Output

OpenCV Python - Gaussian Image Smoothing

Now let us increase the Kernel size and observe the result.

</>
Copy
dst = cv2.GaussianBlur(src,(10,10),cv2.BORDER_DEFAULT)

Output

OpenCV Python - Gaussian Blur


You may change values of other properties and observe the results.

Conclusion

In this OpenCV Python Tutorial, we have learned how to blur or smooth an image using the Gaussian Filter.