Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Non-Linear Image Filters in Python: Median and Bilateral Methods

Tech May 19 1

Image smoothing is critical for noise reduction while preserving structural integrity. While linear methods average pixel values, non-linear approaches offer distinct advantages for specific noise types. Two primary techniques are the median filter and the bilateral filter.

Median Filtering

Unlike linear convolutions where pixel values are weighted sums, median filtering assigns the middle value of a sorted neighborhood to the center pixel. This approach effectively eliminates impulse noise, such as salt-and-pepper artifacts, without blurring sharp transitions at edges. Common window shapes include squares and circles, though rectangular and cross shapes may suit specific geometric needs.

In OpenCV, this operation is executed via medianBlur(). The kernel size parameter ksize must be an odd integer greater than one (e.g., 3, 5).

# Import necessary libraries
import cv2
import numpy as np
import matplotlib.pyplot as plt

# Load the source image
image_path = 'input_image.png'
source_image = cv2.imread(image_path)
# Convert BGR to RGB for proper matplotlib display
source_image_rgb = cv2.cvtColor(source_image, cv2.COLOR_BGR2RGB)

# Apply median filtering with a 3x3 kernel
filtered_median = cv2.medianBlur(source_image_rgb, ksize=3)

# Visualization setup
plt.figure(figsize=(8, 4))
plt.subplot(1, 2, 1)
plt.imshow(source_image_rgb)
plt.title("Original Input")
plt.axis('off')

plt.subplot(1, 2, 2)
plt.imshow(filtered_median)
plt.title("Median Filtered Output")
plt.axis('off')

plt.tight_layout()
plt.show()

Executing this process removes high-frequency noise while maintaining contour clarity.

Bilateral Filtering

Introduced by Tomasi and Manduchi, the bilateral filter employs an anisotropic approach. It considers both spatial proximity and intensity similarity. This dual consideration allows the algorithm to smooth uniform regions while respecting edges where intensity changes abruptly. Unlike Gaussian filters that blur edges alongside noise, bilateral filtering preserves high-frequency details.

The weight calculation involves two components: a domain kernel (spatial distance) and a range kernel (color difference). If pixel intensities differ significantly, the weighting diminishes, preventing cross-edge averaging. In flat regions, behavior resembles Gaussian smoothing; near edges, it suppresses noise from similar-colored neighbors only.

# Re-import required modules (contextual)
import cv2
import numpy as np
import matplotlib.pyplot as plt

# Load source data again
raw_data = cv2.imread('input_image.png')
rgb_input = cv2.cvtColor(raw_data, cv2.COLOR_BGR2RGB)

# Parameters: diameter (d), sigmaColor, sigmaSpace
# d controls neighbor size; sigma values control smoothing intensity
diameter = 15
sigma_color = 150
sigma_space = 150

# Apply bilateral filter
filtered_bilateral = cv2.bilateralFilter(src=rgb_input, d=diameter, 
                                         sigmaColor=sigma_color, 
                                         sigmaSpace=sigma_space)

# Display results
plt.figure(figsize=(8, 4))
plt.subplot(1, 2, 1)
plt.imshow(rgb_input)
plt.title("Source Image")
plt.axis('off')

plt.subplot(1, 2, 2)
plt.imshow(filtered_bilateral)
plt.title(f"Bilateral (d={diameter})")
plt.axis('off')

plt.tight_layout()
plt.show()

This configuration balances noise suppression with texture retention, making it suitable for color images despite limitations with high-frequency color noise in certain scenarios.

Tags: Python

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.