Doublesided filter is used to smooth images and reduce noise while preserving edges . This article — using a mean medianmodeinpythonwithoutlibraries/">median filter. However, these convolutions often result in the loss of important border information as they blur everything, whether it is noise or border. To counter this problem, a nonlinear bidirectional filter was introduced.
Gaussian Blur
Gaussian blur can be formulated as follows:
Here, is the result in the p pixel, and the RHS is essentially the sum of all the q pixels weighted by Gaussian functions. pixel intensity q .
Twosided filter: additional deadline
A twoway filter can be formulated as follows:
Here normalization factor and range weight are new terms added to the previous equation. indicates the spatial extent of the kernel, that is, the size of the neighborhood, and indicates the minimum edge amplitude. This ensures that only pixels with intensity values similar to those of the center pixel are counted for blur, while maintaining abrupt intensity changes. The smaller the value the sharper the edges. As tends to infinity, the equation tends to Gaussian blur.
OpenCV has a function twoway filtering with the following arguments:
 d: the diameter of each pixel neighborhood.
 sigmaColor: value in color space. The higher the value, the more colors will blend together.
 sigmaColor: value in coordinate space. The higher the value, the more pixels will blend together, given that their colors are within the sigmaColor range.
Code:
Input: noisy image.
Code: Implement TwoWay Filtering

Bilateral filter output
Comparison with mean and mean medianmodeinpythonwithoutlibraries/">median filters
Below is the output of the mean filter ( cv2.blur (img, (5, 5))
).
Below is the output of the mean medianmodeinpythonwithoutlibraries/">median filter ( cv2.mean medianmodeinpythonwithoutlibraries/">medianBlur (img, 5)
).
Below is the result of the Gaussian filter ( cv2. GaussianBlur (img, (5, 5), 0)
).
It is easy to see that all these noise canceling filters are contaminating the edges, while Bilateral filtering keeps them.