How to do bilateral filtering in OpenCV

share link

by Dejaswarooba dot icon Updated: Oct 25, 2023

technology logo
technology logo

Solution Kit Solution Kit  

Bilateral filtering helps in image processing tasks to achieve image smoothing. It will preserve edges and details. It is quite distinct from traditional image blurring methods like Gaussian Blurring.


Standard blurring techniques create a uniform smoothing effect. We can do this by applying a low-pass filter kernel to the entire image. Bilateral filtering takes into account both spatial and color information. It is when applying the smoothing filter.    


We can employ the `bilateralFilter` function from the OpenCV library for bilateral filtering. This function operates on an input image and a destination (output) image. Bilateral filtering computes a weighted average for each pixel.

It considers two key factors:   

1. Color Similarity (sigmaColor - Filter sigma):   

It looks at how similar the colors are between the present pixel and its neighboring pixels.   


2. Spatial Proximity (sigmaSpace - Filter sigma):    

It considers the closeness of neighboring pixels. i.e., how close they are in their spatial distance from the current pixel.   


Bilateral filtering combines these two factors. This ensures that we apply the smoothing effect. It helps preserve edges and details in the image. Median blurring computes the median value of pixel intensities within a kernel area. Unlike that, bilateral filtering is an advanced filter. It takes into account pixel differences and values in the current pixel's vicinity. It is useful in scenarios where there is a large intensity variation in the image. It is also useful when we need to retain similar intensities.   


The bilateral smoothing filter uses a normalization factor. It considers the pixel values within a kernel. This works in contrast to a simple average filter like a box filter or a normalized box filter. This function helps with noise removal in real-time applications. It helps ensure unwanted noise doesn't interfere with the task at hand. It employs for edge-preserving smoothing and enhancing features. It helps keep important details intact.  

 

The cv2.bilateralFilter function is a tool for performing bilateral filtering on images. It is particularly effective in reducing noise while retaining important image structures. Here's an overview of the cv2.bilateralFilter function:   

Syntax:   

cv2.bilateralFilter(src, d, sigmaColor, sigmaSpace, dst=None, borderType=None)   

Parameters:   

  • src: This is the source image that you want to filter.   
  • d: The diameter of each pixel neighborhood. It defines the range over which the filter operates. A larger d value includes pixels that are farther apart in the filtering process.   
  • sigmaColor: This parameter controls the influence of color similarity on the filtering. A larger sigmaColor value means that we consider pixels with similar color values.   
  • sigmaSpace: This parameter controls the influence of spatial proximity on the filtering. A larger sigmaSpace value means pixels closer to the center contribute to filtering.   
  • dst (optional): This is the output image where we store the filtered result. If not specified, the function creates a new image for the result.   
  • borderType (optional): It specifies how to handle border pixels during filtering. Common values include cv2.BORDER_DEFAULT, cv2.BORDER_CONSTANT, cv2.BORDER_REFLECT, and others.   


Preview of the output that you will get on running this code from your IDE

Code

This code demonstrates bilateral filtering using OpenCV and Matplotlib. It loads an image, applies bilateral filtering with specified parameters to both uint8 and float32 versions of the image, and then displays the original image, the uint8 filtered image, the float32 filtered image, and the float32 filtered image corrected for display in a 2x2 grid using Matplotlib.

import cv2
import matplotlib.pyplot as plt
import numpy as np
from skimage import img_as_float32, img_as_ubyte

# Use .astype(x) instead of img_as_x
img = cv2.imread('path/to/your/image.jpg')[..., ::-1]
filter_uint8 = cv2.bilateralFilter(img, 200, 200, 200)
filter_float32 = cv2.bilateralFilter(img.astype(np.float32), 200, 200, 200)

plt.figure(1, figsize=(14, 8))
plt.subplot(2, 2, 1), plt.imshow(img), plt.title('Original image')
plt.subplot(2, 2, 2), plt.imshow(filter_uint8), plt.title('uint8 filtered')
plt.subplot(2, 2, 3), plt.imshow(filter_float32), plt.title('float32 filtered')
plt.subplot(2, 2, 4), plt.imshow(filter_float32 / 255), plt.title('float32 filtered, corrected')
plt.tight_layout()

import cv2
import matplotlib.pyplot as plt
from skimage import img_as_float32, img_as_ubyte

# Scale sigmaColor w.r.t. to float value range of [0.0 ... 1.0]
img = img_as_float32(cv2.imread('path/to/your/image.jpg')[..., ::-1])
filter_uint8 = cv2.bilateralFilter(img_as_ubyte(img), 200, 200, 200)
filter_float32 = cv2.bilateralFilter(img, 200, 200, 200)
filter_float32_corr = cv2.bilateralFilter(img, 200, 200/255, 200)

plt.figure(0, figsize=(14, 8))
plt.subplot(2, 2, 1), plt.imshow(img), plt.title('Original image')
plt.subplot(2, 2, 2), plt.imshow(filter_uint8), plt.title('uint8 filtered')
plt.subplot(2, 2, 3), plt.imshow(filter_float32), plt.title('float32 filtered')
plt.subplot(2, 2, 4), plt.imshow(filter_float32_corr), plt.title('float32 filtered, corrected')
plt.tight_layout(), plt.show()

----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.16299-SP0
Python:        3.9.1
Matplotlib:    3.4.0
NumPy:         1.20.2
OpenCV:        4.5.1
scikit-image:  0.18.1
----------------------------------------

Follow the steps carefully to get the output easily.

  • Download and install VS Code on your desktop.
  • Open VS Code and create a new file in the editor.
  • Copy the code snippet that you want to run, using the "Copy" button or by selecting the text and using the copy command (Ctrl+C on Windows/Linux or Cmd+C on Mac).,
  • Paste the code into your file in VS Code, and save the file with a meaningful name and the appropriate file extension for Python use (.py).file extension.
pip install opencv-python 
  • Use this line in the command prompt to install OpenCV.
  • Also install matplotlib and numpy using
pip install matplotlib
pip install numpy

in the command prompt.

  • Remove the line
from skimage import img_as_float32, img_as_ubyte
  • Remove the second part of the code as shown in the attached image
  • Add the following lines at the end -
plt.show()


  • Make sure you give the correct path of the image. Refer to the output image.
  • To run the code, open the file in VS Code and click the "Run" button in the top menu, or use the keyboard shortcut Ctrl+Alt+N (on Windows and Linux) or Cmd+Alt+N (on Mac).


I hope you found this useful. I have added the dependencies and their version information below.


I found this code snippet by searching for "bilateralfilter opencv" in kandi. You can try any such use case!

Dependencies


matplotlibby matplotlib

Python doticonstar image 17559 doticonVersion:v3.7.1doticon
no licences License: No License (null)

matplotlib: plotting with Python

Support
    Quality
      Security
        License
          Reuse

            matplotlibby matplotlib

            Python doticon star image 17559 doticonVersion:v3.7.1doticonno licences License: No License

            matplotlib: plotting with Python
            Support
              Quality
                Security
                  License
                    Reuse

                      opencv-pythonby opencv

                      Shell doticonstar image 3491 doticonVersion:72doticon
                      License: Permissive (MIT)

                      Automated CI toolchain to produce precompiled opencv-python, opencv-python-headless, opencv-contrib-python and opencv-contrib-python-headless packages.

                      Support
                        Quality
                          Security
                            License
                              Reuse

                                opencv-pythonby opencv

                                Shell doticon star image 3491 doticonVersion:72doticon License: Permissive (MIT)

                                Automated CI toolchain to produce precompiled opencv-python, opencv-python-headless, opencv-contrib-python and opencv-contrib-python-headless packages.
                                Support
                                  Quality
                                    Security
                                      License
                                        Reuse

                                          numpyby numpy

                                          Python doticonstar image 23755 doticonVersion:v1.25.0rc1doticon
                                          License: Permissive (BSD-3-Clause)

                                          The fundamental package for scientific computing with Python.

                                          Support
                                            Quality
                                              Security
                                                License
                                                  Reuse

                                                    numpyby numpy

                                                    Python doticon star image 23755 doticonVersion:v1.25.0rc1doticon License: Permissive (BSD-3-Clause)

                                                    The fundamental package for scientific computing with Python.
                                                    Support
                                                      Quality
                                                        Security
                                                          License
                                                            Reuse

                                                              If you do not have Opencv that is required to run this code, you can install it by clicking on the above link and copying the pip Install command from the page in kandi.


                                                              You can search for any dependent library on kandi like Opencv.

                                                              Environment tested

                                                              I tested this solution in the following versions. Be mindful of changes when working with other versions.


                                                              1. The solution is created and tested using Vscode 1.77.2 version
                                                              2. This code was tested using Python version 3.8.0
                                                              3. This code was tested using opencv-python version 72
                                                              4. This code was tested using matplotlib version 3.7.1
                                                              5. This code was tested using numpy version 1.25.0



                                                              By using this technique, you can smoothen an image while preserving edges and details by taking into account both spatial and color information. You can also compute weighted averages of neighboring pixels based on their similarity in both color and spatial distance. This process also facilitates an easy-to-use, hassle-free method to create a hands-on working version of code.

                                                              FAQ 

                                                              1. How can I use the Bilateral Filter OpenCV to show the blurred image?   

                                                              Apply the `cv2.bilateralFilter` function to your input image. Adjust the parameters like `d', `sigmaColor`, and `sigmaSpace` to control the blurring effect. Display the filtered result using OpenCV's `imshow` function.   

                                                                

                                                              2. What are some typical image processing tasks that we can do with Bilateral Filter OpenCV?   

                                                              Bilateral filtering in OpenCV helps in image denoising. Because it effectively reduces noise while preserving edges and fine details. It's also useful for tasks like image stylization, tone mapping, and texture enhancement.   

                                                                

                                                              3. What are the various low pass filters available in OpenCV, and how do they work?   

                                                              OpenCV provides various low-pass filters. It includes the Gaussian filter, the mean filter, and the median filter. These filters work by averaging pixel values about each pixel. Gaussian filtering is effective for smoothing while preserving edges. This is due to its weighted averaging.   

                                                                

                                                              4. Is bilateral filtering better suited for certain tasks of image smoothing?   

                                                              The goal is to reduce noise while maintaining edge and texture details. It's particularly useful in scenarios where preserving image structures is critical. This includes computer vision tasks and stylized image processing.   


                                                              5. Could you explain Bilateral Smoothing and its effect on images?   

                                                              Bilateral smoothing works by considering both spatial proximity and color similarity. It allows it to smooth areas with similar colors. This retains sharp transitions between different regions. This makes it effective for tasks like noise reduction edge preservation in images.  

                                                              Support

                                                              1. For any support on kandi solution kits, please use the chat
                                                              2. For further learning resources, visit the Open Weaver Community learning page.

                                                              See similar Kits and Libraries