Do you want to blur an image using OpenCV? There is a function in OpenCV cv2 filter2D that convolves a kernel with an image. In this tutorial, you will know how to blur an image using filter2d() function using the kernel with steps.
Steps to implement cv2 filter2d
Here you will know all the steps required to implement cv2 filter2D. Just follow the steps for deep understanding.
Step 1: Import required libraries
The first step is to import all the necessary libraries for blurring the image. In this entire tutorial, I am using NumPy and OpenCV python packages only. So let’s import them using the import statement.
import cv2 import numpy as np
Step 2: Read the image
The second step is to read the image where I am going to apply cv2.filter2D(). In OpenCV, you can read the image using the cv2.imread() method. Use the following lines of code to read the image.
img = cv2.imread("bird.jpg")
Here is the image I am using for blurring.
Step 3: Create a Kernel
To blur the image you have to create a kernel for that. The kernel is a square Matrix with all the values or elements of 1 in it. Let’s create a 5X5 square matrix. I am using the NumPy.ones() method for creating a matrix with all the values 1. Add the following lines of code to create a kernel.
kernel = np.ones((5,5),np.float32)/25
Here I have defined the type of the elements of the kernel and it is float.
Step 4: Use the cv2.filter2D() method
Now after reading and creating a kernel for the image. Lets apply cv2.filter2D() . The syntax for the cv2.filter2D() is the below.
filter2D(src, dst, ddepth, kernel)
src: Input image.
dst : destination (output image) for this operation.
ddepth : A variable of the type integer representing the depth of the output image.
kernel: A Matrix object representing the convolution kernel.
Let’s apply the filter2D() method to our image. Add the following lines of code.
blurred_image = cv2.filter2D(img,-1,kernel)
import cv2 import numpy as np img = cv2.imread("bird.jpg") kernel = np.ones((5,5),np.float32)/25 blurred_image = cv2.filter2D(img,-1,kernel) cv2.imshow("Blurred Image",blurred_image) cv2.waitKey(0)
You can do more blurring if you increase the dimension of the kernel.
These are steps for implementing filter2D() using OpenCV in python. Blurring the image is required before processing the image as it removes any outliers and noise from the image. I hope you have liked this tutorial. If you have any queries then you can contact us for more help.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.