Python | Two-way filtration



Double-sided filter is used to smooth images and reduce noise while preserving edges . This article — using a 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 .

Two-sided filter: additional deadline

A two-way 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 two-way filtering with the following arguments:

  1. d: the diameter of each pixel neighborhood.
  2. sigmaColor: value in color space. The higher the value, the more colors will blend together.
  3. 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 Two-Way Filtering

import cv2

 
# Read the image.

img = cv2.imread ( `taj.jpg` )

  
# Apply a two-sided filter with d = 15,
# sigmaColor = sigmaSpace = 75.

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

 
# Save the output.

cv2.imwrite ( `taj_bilateral.jpg` , bilateral)

Bilateral filter output

Comparison with mean and median filters
Below is the output of the mean filter ( cv2.blur (img, (5, 5)) ).

Below is the output of the median filter ( cv2.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.