How to perform bilateral filter operation on an image in OpenCV using Python?


A bilateral filter operation is highly effective in smoothing the image and removing noises. The main advantage of the bilateral filtering is that it preserves the edges unlike in average and median filtering. Bilateral filtering operation is slower in comparison to other filters. We can perform bilateral filtering on an image using the cv2.bilateralFilter() method.

Syntax

Following is the syntax of this method.

cv2.bilateralFilter(img, d, sigmaColor, sigmaSpace)

This method accepts the following parameters

  • img − The input image on which the bilateral filter operation to be applied.

  • d − A variable of the type integer representing the diameter of the pixel neighborhood.

  • sigmaColor − an integer value representing the filter sigma in the color space. The greater the value, the colors farther to each other will start to get mixed.

  • sigmaSpace − an integer value representing the filter sigma in the coordinate space. The greater its value, the farther pixels will mix together, given that their colors lie within the sigmaColor range.

Steps

To perform bilateral filter operation, you can follow the steps given below −

Import the required library. In all the following Python examples, the required Python library is OpenCV. Make sure you have already installed it.

import cv2

Read the input image.

img = cv2.imread('birds.jpg')

Apply bilateral filtering on the input image. We pass d, sigmaColor, and sigmaSpace as 9, 15 and 15 respectively to the function.

bilateral = cv2.bilateralFilter(img, 9, 75, 75)

Display the bilaterally filtered image.

cv2.imshow('bilateral.jpg', bilateral)
cv2.waitKey(0)
cv2.destroyAllWindows())

Example

Let's see an example to perform bilateral filter operation on the input image.

import cv2 # Read the image. img = cv2.imread('birds.jpg') # Apply bilateral filter with d = 9, # sigmaColor = sigmaSpace = 75. bilateral = cv2.bilateralFilter(img, 9, 75, 75) # display the output cv2.imshow('bilateral.jpg', bilateral) cv2.waitKey(0) cv2.destroyAllWindows()

We will use the following image as the Input File in this program −

Output

When we execute the above code, it will produce the following output

We applied bilateral filter with d=9, sigmaColor=55 and sigmaSpace=55

And, we get the following output window −

Notice the difference between the input image and the image after bilateral filtering.

Updated on: 28-Sep-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements