Certainly! Below is a Python implementation of the Adaptive Median Filter for 2D grayscale images. This filter is particularly effective for removing "salt-and-pepper" noise while preserving image details.
Overview of the Adaptive Median Filter
The Adaptive Median Filter works by changing the size of the median filter window based on the local properties of the image. The algorithm has two main stages:
- Level A: Determines if the median value is an impulse noise by checking if it's different from the minimum and maximum values in the window.
- Level B: Determines if the current pixel is noise by comparing it to the minimum and maximum values. If it's noise, replace it with the median value.
Python Implementation
import numpy as np
def adaptive_median_filter(image, Smax):
"""
Apply the Adaptive Median Filter to a 2D grayscale image.
Parameters:
image (numpy.ndarray): Input 2D grayscale image.
Smax (int): Maximum window size (must be odd and >= 3).
Returns:
numpy.ndarray: The filtered image.
"""
if Smax % 2 == 0 or Smax < 3:
raise ValueError("Smax must be an odd integer >= 3.")
m, n = image.shape
filtered_image = np.zeros_like(image)
pad_size = Smax // 2
padded_image = np.pad(image, pad_size, mode='edge')
for i in range(m):
for j in range(n):
S = 3 # Initial window size
while True:
half_size = S // 2
# Define window boundaries
i_min = i + pad_size - half_size
i_max = i + pad_size + half_size + 1
j_min = j + pad_size - half_size
j_max = j + pad_size + half_size + 1
# Extract the window
window = padded_image[i_min:i_max, j_min:j_max].flatten()
Zmin = window.min()
Zmax = window.max()
Zmed = np.median(window)
A1 = Zmed - Zmin
A2 = Zmed - Zmax
if A1 > 0 and A2 < 0:
# Level B
B1 = image[i, j] - Zmin
B2 = image[i, j] - Zmax
if B1 > 0 and B2 < 0:
filtered_image[i, j] = image[i, j]
else:
filtered_image[i, j] = Zmed
break # Move to next pixel
else:
S += 2 # Increase window size
if S > Smax:
filtered_image[i, j] = Zmed
break # Move to next pixel
return filtered_image
Usage Example
Here's how you can use the adaptive_median_filter function on a grayscale image:
import numpy as np
import matplotlib.pyplot as plt
# Load a sample grayscale image (replace 'image.png' with your image file)
image = plt.imread('image.png')
if image.ndim == 3:
# Convert to grayscale if the image is RGB
image = np.mean(image, axis=2)
# Add salt-and-pepper noise to the image
def add_salt_and_pepper_noise(img, amount, salt_vs_pepper):
noisy_img = np.copy(img)
num_salt = np.ceil(amount * img.size * salt_vs_pepper)
num_pepper = np.ceil(amount * img.size * (1.0 - salt_vs_pepper))
# Salt noise
coords = [np.random.randint(0, i - 1, int(num_salt)) for i in img.shape]
noisy_img[coords] = img.max()
# Pepper noise
coords = [np.random.randint(0, i - 1, int(num_pepper)) for i in img.shape]
noisy_img[coords] = img.min()
return noisy_img
noisy_image = add_salt_and_pepper_noise(image, amount=0.05, salt_vs_pepper=0.5)
# Apply the Adaptive Median Filter
Smax = 7 # Maximum window size
filtered_image = adaptive_median_filter(noisy_image, Smax)
# Display the results
plt.figure(figsize=(15, 5))
plt.subplot(1, 3, 1)
plt.imshow(image, cmap='gray', vmin=0, vmax=255)
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 3, 2)
plt.imshow(noisy_image, cmap='gray', vmin=0, vmax=255)
plt.title('Noisy Image')
plt.axis('off')
plt.subplot(1, 3, 3)
plt.imshow(filtered_image, cmap='gray', vmin=0, vmax=255)
plt.title('Filtered Image')
plt.axis('off')
plt.tight_layout()
plt.show()
Explanation of the Usage Example
- Loading the Image: We load the image and convert it to grayscale if necessary.
- Adding Noise: We add synthetic salt-and-pepper noise to the image for demonstration purposes.
- Filtering: We apply the
adaptive_median_filter with a maximum window size Smax.
- Displaying Results: We visualize the original, noisy, and filtered images side by side.
Notes
- Ensure that the input image is a 2D numpy array representing a grayscale image.
- The
Smax parameter controls the maximum size of the filter window. Larger values can handle larger noise artifacts but may increase computational time.
- The padding mode is set to
'edge' to handle borders effectively without introducing artificial data.
Performance Considerations
The adaptive median filter can be computationally intensive, especially for large images or large values of Smax. For performance optimization:
- Consider using libraries like Numba for JIT compilation.
- Parallelize the loops using libraries like multiprocessing or joblib if needed.
- For very large images, consider processing the image in smaller blocks.
References
- Digital Image Processing by Rafael C. Gonzalez and Richard E. Woods.
- Adaptive Median Filter Algorithm details: [Link to resource or documentation if needed].
Feel free to adjust Smax and other parameters based on your specific use case!