The Wayback Machine - https://web.archive.org/web/20240707202425/https://www.geeksforgeeks.org/python-opencv-smoothing-and-blurring/
Open In App

Python OpenCV – Smoothing and Blurring

Last Updated : 03 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn about smoothing and blurring with python-OpenCV.

When we are dealing with images at some points the images will be crisper and sharper which we need to smoothen or blur to get a clean image, or sometimes the image will be with a really bad edge which also we need to smooth it down to make the image usable. In OpenCV, we got more than one method to smooth or blur an image, let’s discuss them one by one.

Method 1: With 2D Convolution  

In this method of smoothing, we have complete flexibility over the filtering process because we will be using our custom-made kernel [a simple 2d matrix of NumPy array which helps us to process the image by convolving with the image pixel by pixel]. A kernel basically will give a specific weight for each pixel in an image and sum up the weighted neighbor pixels to form a pixel, with this method we will be able to compress the pixels in an image and thus we can reduce the clarity of an image, By this method, we can able to smoothen or blur an image easily.  

Note: By using these kernels [2d matrices] we can perform many functions like sharpening and edge detecting an image. But remember each process has a different kernel i.e., different values of matrices. The kernel we are going to use in this article is a 5 by 5 averaging kernel which is basically a matrix of ones which in whole divided by 25, Which will look like,

To smoothen an image with a custom-made kernel we are going to use a function called filter2D() which basically helps us to convolve a custom-made kernel with an image to achieve different image filters like sharpening and blurring and more.

Syntax: filter2D(sourceImage, ddepth, kernel)

Code:

Python3




# Importing the modules
import cv2
import numpy as np
  
# Reading the image
image = cv2.imread('image.png')
  
# Creating the kernel with numpy
kernel2 = np.ones((5, 5), np.float32)/25
  
# Applying the filter
img = cv2.filter2D(src=image, ddepth=-1, kernel=kernel2)
  
# showing the image
cv2.imshow('Original', image)
cv2.imshow('Kernel Blur', img)
  
cv2.waitKey()
cv2.destroyAllWindows()


Output:

Method 2:  With pre-built functions

OpenCV comes with many prebuilt blurring and smoothing functions let us see them in brief,

1. Averaging:

Syntax: cv2.blur(image, shapeOfTheKernel)

  • Image– The image you need to smoothen
  • shapeOfTheKernel– The shape of the matrix-like 3 by 3 / 5 by 5

The averaging method is very similar to the 2d convolution method as it is following the same rules to smoothen or blur an image and uses the same type of kernel which will basically set the center pixel’s value to the average of the kernel weighted surrounding pixels. And by this, we can greatly reduce the noise of the image by reducing the clarity of an image by replacing the group of pixels with similar values which is basically similar color. We can greatly reduce the noise of the image and smoothen the image. The kernel we are using for this method is the desired shape of a matrix with all the values as “1”  and the whole matrix is divided by the number of values in the respective shape of the matrix [which is basically averaging the kernel weighted values in the pixel range]. The kernel we used in this example is,

Code:

Python3




# Importing the modules
import cv2
import numpy as np
  
# Reading the image
image = cv2.imread('image.png')
  
# Applying the filter
averageBlur = cv2.blur(image, (5, 5))
  
# Showing the image
cv2.imshow('Original', image)
cv2.imshow('Average blur', averageBlur)
  
cv2.waitKey()
cv2.destroyAllWindows()


Output:

2. Gaussian Blur:

Syntax: cv2. GaussianBlur(image, shapeOfTheKernel, sigmaX )

  • Image– the image you need to blur
  • shapeOfTheKernel– The shape of the matrix-like 3 by 3 / 5 by 5
  • sigmaX– The Gaussian kernel standard deviation which is the default set to 0

In a gaussian blur, instead of using a box filter consisting of similar values inside the kernel which is a simple mean we are going to use a weighted mean. In this type of kernel, the values near the center pixel will have a higher weight. With this type of blurs, we will probably get a less blurred image but a natural blurred image which will look more natural because it handles the edge values very well. Instead of averaging the weighted sum of the pixels here, we will divide it with a specific value which is 16 in the case of a 3 by 3 shaped kernel which will look like this.

Note: We can achieve the same result when we use this exact same kernel in the filter2D() function but in this case, we don’t need to create the kernel because this function automatically will do it for us.

Code:

Python3




# Importing the module
import cv2
import numpy as np
  
# Reading the image
image = cv2.imread('image.png')
  
# Applying the filter
gaussian = cv2.GaussianBlur(image, (3, 3), 0)
  
# Showing the image
cv2.imshow('Original', image)
cv2.imshow('Gaussian blur', gaussian)
  
cv2.waitKey()
cv2.destroyAllWindows()


Output:

3. Median blur:

Syntax: cv. medianBlur(image, kernel size)

  • Image– The image we need to apply the smoothening
  • KernelSize– the size of the kernel as it always takes a square matrix the value must be a positive integer more than 2.

Note: There are no specific kernel values for this method.

In this method of smoothing, we will simply take the median of all the pixels inside the kernel window and replace the center value with this value. The one positive of this method over the gaussian and box blur is in these two cases the replaced center value may contain a pixel value that is not even present in the image which will make the image’s color different and weird to look, but in case of a median blur though it takes the median of the values that are already present in the image it will look a lot more natural.

Code:

Python3




# Importing the modules
import cv2
import numpy as np
  
# Reading the image
image = cv2.imread('image.png')
  
# Applying the filter
medianBlur = cv2.medianBlur(image, 9)
  
# Showing the image
cv2.imshow('Original', image)
cv2.imshow('Median blur', medianBlur)
  
cv2.waitKey()
cv2.destroyAllWindows()


Output:

4. Bilateral blur:

Syntax: cv2.bilateralFilter(image, diameter, sigmaColor, sigmaSpace)

  • Image– The image we need to apply the smoothening
  • Diameter– similar to the size of the kernel
  • SigmaColor– The number of colors to be considered in the given range of pixels [the higher value represents the increase in the number of colors in the given area of pixels]—Should not keep very high
  • SigmaSpace – the space between the biased pixel and the neighbor pixel higher value means the pixels far out from the pixel will manipulate in the pixel value

The smoothening methods we saw earlier are fast but we might end up losing the edges of the image which is not so good. But by using this method, this function concerns more about the edges and smoothens the image by preserving the images. This is achieved by performing two gaussian distributions. This might be very slow while comparing to the other methods we discussed so far.  

Code:

Python3




# Importing the modules
import cv2
import numpy as np
  
# Reading the image
image = cv2.imread('image.png')
  
# Applying the filter
bilateral = cv2.bilateralFilter(image, 9, 75, 75)
  
# Showing the image
cv2.imshow('Original', image)
cv2.imshow('Bilateral blur', bilateral)
  
cv2.waitKey()
cv2.destroyAllWindows()


Output:



Previous Article
Next Article

Similar Reads

Python | Image blurring using OpenCV
Image Blurring refers to making the image less clear or distinct. It is done with the help of various low pass filter kernels. Advantages of blurring: It helps in Noise removal. As noise is considered as high pass signal so by the application of low pass filter kernel we restrict noise. It helps in smoothing the image. Low intensity edges are remov
2 min read
Transition from OpenCV 2 to OpenCV 3.x
OpenCV is one of the most popular and most used Computer vision libraries. It contains tools to carry out image and video processing. When OpenCV 3..4.1 is an improved version of OpenCV 2.4 as it introduced new algorithms and features. Although some of the existing modules were rewritten and moved to sub-modules. In this articles, I will focus on t
2 min read
Top Books for Learning OpenCV: Computer Vision with OpenCV Library
OpenCV or Open Source Computer Vision Library, is an open-source computer vision and machine learning software library. It's extensively used for real-time computer vision tasks such as object detection, face recognition, image processing, etc. Whether you're a beginner or an experienced developer looking to deepen your understanding of OpenCV, her
5 min read
Automatic Document Scanner using OpenCV (OpenCV Document Scanner)
An automatic document scanner using OpenCV is a computer vision application that automatically detects and extracts documents from images. This type of scanner can be useful in various scenarios, such as digitizing paper documents, processing scanned documents, or automating document recognition tasks. In this article, we will see how we can build
6 min read
Setting up ROS with Python 3 and Python OpenCV
Setting up a Robot Operating System (ROS) with Python 3 and OpenCV can be a powerful combination for robotics development, enabling you to leverage ROS's robotics middleware with the flexibility and ease of Python programming language along with the computer vision capabilities provided by OpenCV. Here's a step-by-step guide to help you set up ROS
3 min read
Blur and anonymize faces with OpenCV and Python
In this article, we are going to see how to Blur and anonymize faces with OpenCV and Python. For this, we will be using Cascade Classifier to detect the faces. Make sure to download the same, from this link: haarcascade_frontalface_default.xml ApproachFirstly, we use a built face detection algorithm, to detect the face from a real-time video or fro
4 min read
Addition and Blending of images using OpenCV in Python
When we talk about images, we know its all about the matrix either binary image(0, 1), gray scale image(0-255) or RGB image(255 255 255). So additions of the image is adding the numbers of two matrices. In OpenCV, we have a command cv2.add() to add the images. Below is code for Addition of two images using OpenCV : # Python program for adding # ima
2 min read
Draw a rectangular shape and extract objects using Python's OpenCV
OpenCV is an open-source computer vision and machine learning software library. Various image processing operations such as manipulating images and applying tons of filters can be done with the help of it. It is broadly used in Object detection, Face Detection, and other Image processing tasks. Let's see how to draw rectangular shape on image and e
4 min read
Find the Solidity and Equivalent Diameter of an Image Object Using OpenCV Python
In this article, we will see how we can find the solidity and the equivalent diameter of an object present in an image with help of Python OpenCV. Function to Find Solidity The solidity of an image is the measurement of the overall concavity of a particle. We can define the solidity of an object as the ratio of the contour area to its convex hull a
4 min read
Python | OpenCV program to read and save an Image
OpenCV (Open Source Computer Vision) is a library of programming functions mainly aimed at real-time computer vision. This is cross-platform library, it provides functions that are used in multiple languages. Coming to image processing, OpenCV enables us to perform multiple operations on image, but in order to do that we need to read an image file
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg