Filtering in OpenCV

Introduction

In Today's OpenCV post, we will be performing Filtering Operations on Images.
Whenever some filtering need to be done on an Image, we first need to convert it from Spatial Domain to Frequency domain. The most common method for this process is Fourier Transform, but we will be using detail enhance filter by OpenCV for this.

Prerequistes

First we complete all the necessary imports

import cv2
from google.colab.patches import cv2_imshow
import numpy as np

No we can move towards reading the image-

img = cv2.imread('wild west.png')
cv2_imshow(img)

Applying Domain Filters

Now we apply the Enhance Detail filter by OpenCV. Here we specify the source image, sigma spatial value and sigma range.

dst = cv2.detailEnhance(img, sigma_s=10, sigma_r=0.15)
cv2_imshow(np.hstack((img, dst)))

This results in:
Image description

Smoothing

The next filter we need to apply is Smoothing filters.
We will be using Gaussian Filter for this.

blurimg = cv2.GaussianBlur(img,(5,5),cv2.BORDER_DEFAULT)
cv2_imshow(np.hstack((img, blurimg)))

The results-
Image description

Sharpening

No we will be applying the sharpening filter by using the Bilateral Filter. in the bilateralFilter() function, we specify the source image, d = 60 and sigma space = 60.

sharp = cv2.bilateralFilter(img, 60, 60, 60)
cv2_imshow(sharp)

High Pass and Low Pass Filters

Finally, we move onto applying Low Pass and High Pass filters on the image.
Low Pass Filter
We will be using a Kernel to apply the low pass filter. Our Low pass filter is a 5x5 array with all ones averaged.
We apply convolution between the Kernel and the Image using cv2.filter2D() function.

kernel = np.array([[1, 1, 1, 1, 1], 
                   [1, 1, 1, 1, 1], 
                   [1, 1, 1, 1, 1], 
                   [1, 1, 1, 1, 1], 
                   [1, 1, 1, 1, 1]])
kernel = kernel/sum(kernel)

#filter the source image
lpf = cv2.filter2D(img,-1,kernel)
cv2_imshow(np.hstack((img, lpf)))

This gives the output as:
Image description

High Pass Filter
For the High Pass filter, we will be subtracting the Gaussian Blur image from the actual image and adding 127 to it.

hpf = img - cv2.GaussianBlur(img, (0,0), 3) + 127
cv2_imshow(np.hstack((img, hpf)))

The result of applying a high pass filter is as follows-
Image description

Conclusion

So if you have reached this far, thank you for reading this.

With this we found out the results of the various filters that can be applied on images and these can be used for further image processing operations.

23