How to apply custom filters to images (2D convolution) using OpenCV Python?

In this tutorial, we will learn how to apply custom filters to images using OpenCV Python. We'll explore two different low-pass filters: filter2D and boxFilter. These filters perform 2D convolution operations to smooth images and remove noise.

Applying 2D filters to images is also known as the "2D Convolution operation". These filters are commonly referred to as averaging filters. The main disadvantage of these filters is that they also smooth the edges in the image. If you don't want to smooth the edges, you can apply a "bilateral filter" that preserves edges.

Syntax

Following are the syntaxes of filter2D and boxFilter ?

cv2.filter2D(img, ddepth, kernel)
cv2.boxFilter(img, ddepth, ksize)

Parameters

  • img ? The input image on which the filter operation will be applied.

  • ddepth ? The desired depth of the output image. If ddepth = -1, it returns the output image with the same depth as the input image.

  • kernel ? Convolution kernel. In filter2D, we pass the kernel as a numpy array.

  • ksize ? The kernel size. In boxFilter, we pass the kernel size as a tuple.

Using filter2D() with Custom Kernel

The filter2D() function allows you to apply a custom convolution kernel to an image ?

import cv2
import numpy as np

# Read the input image
img = cv2.imread('vehicle.jpg')

# Convert the image to grayscale
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Define a 5x5 averaging kernel
kernel = np.ones((5,5), np.float32) / 25

# Apply the averaging filter
result = cv2.filter2D(img, -1, kernel)

# Display the filtered image
cv2.imshow("Filter 2D Image", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

Using boxFilter() for Averaging

The boxFilter() function applies a box filter (averaging filter) with a specified kernel size ?

import cv2

# Read the input image
img = cv2.imread('vehicle.jpg')

# Convert the image to grayscale
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Apply boxFilter to the input image
result = cv2.boxFilter(img, -1, (5,5))

# Display the image after filter operation
cv2.imshow("Box Filter Image", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

Creating Different Custom Kernels

You can create various types of custom kernels for different filtering effects ?

import numpy as np

# Averaging kernel (blur effect)
avg_kernel = np.ones((5,5), np.float32) / 25
print("Averaging Kernel:")
print(avg_kernel)

# Sharpening kernel
sharpen_kernel = np.array([[-1,-1,-1],
                          [-1, 9,-1],
                          [-1,-1,-1]], np.float32)
print("\nSharpening Kernel:")
print(sharpen_kernel)

# Edge detection kernel (Laplacian)
edge_kernel = np.array([[0,-1, 0],
                       [-1, 4,-1],
                       [ 0,-1, 0]], np.float32)
print("\nEdge Detection Kernel:")
print(edge_kernel)
Averaging Kernel:
[[0.04 0.04 0.04 0.04 0.04]
 [0.04 0.04 0.04 0.04 0.04]
 [0.04 0.04 0.04 0.04 0.04]
 [0.04 0.04 0.04 0.04 0.04]
 [0.04 0.04 0.04 0.04 0.04]]

Sharpening Kernel:
[[-1. -1. -1.]
 [-1.  9. -1.]
 [-1. -1. -1.]]

Edge Detection Kernel:
[[ 0. -1.  0.]
 [-1.  4. -1.]
 [ 0. -1.  0.]]

Comparison

Method Kernel Definition Best For
filter2D() Custom numpy array Custom filters, advanced operations
boxFilter() Just kernel size Simple averaging, faster computation

Conclusion

Use filter2D() when you need custom convolution kernels for specific filtering effects. Use boxFilter() for simple averaging operations as it's computationally more efficient for basic smoothing tasks.

Updated on: 2026-03-26T22:00:32+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements