Of course! Here's a comprehensive guide to using the median blur in Python, primarily with the OpenCV library, which is the standard for image processing.
What is a Median Blur?
A median blur is a non-linear digital filtering technique. Its primary purpose is noise reduction.
Instead of averaging the pixel values in a neighborhood (like a Gaussian blur), the median blur replaces the center pixel's value with the median value of all the pixels in the surrounding kernel (or sliding window).
Key Advantages:
- Excellent for "Salt-and-Pepper" Noise: This is its superpower. Salt-and-pepper noise is random occurrences of black and white pixels. Because the median is calculated from a group of pixels, extreme outlier values (like pure white or pure black) are effectively ignored, making the blur very effective at removing this type of noise.
- Preserves Edges: Unlike a simple average, the median filter tends to preserve sharp edges in an image while smoothing out noise. This is a huge advantage over linear filters like Gaussian blur for certain tasks.
How to Perform Median Blur in Python (with OpenCV)
The most common and efficient way to perform a median blur in Python is by using the cv2.medianBlur() function from the OpenCV library.
Step 1: Install OpenCV
If you don't have it installed, open your terminal or command prompt and run:
pip install opencv-python pip install numpy # Often required alongside OpenCV
Step 2: The cv2.medianBlur() Function
The function is very simple to use:
dst = cv2.medianBlur(src, ksize)
Parameters:
src: The source image (the input image). It should be in an 8-bit or floating-point, single-channel format. For color images, the blur is applied to each channel independently.ksize: The size of the kernel (the sliding window). This must be a positive odd integer (e.g., 3, 5, 7, 9...). A kernel size of3means a 3x3 window,5means a 5x5 window, etc. A larger kernel will result in more blurring but will also be slower and may remove more detail.
Return Value:
dst: The destination (blurred) image.
Complete Python Example
This example demonstrates how to load an image, add some salt-and-pepper noise to it, and then apply a median blur to remove the noise.
import cv2
import numpy as np
import matplotlib.pyplot as plt
# --- 1. Load an Image ---
# Make sure you have an image file named 'lena.jpg' in the same directory,
# or provide the correct path to your image.
try:
original_image = cv2.imread('lena.jpg', cv2.IMREAD_COLOR)
if original_image is None:
raise FileNotFoundError("Image not found. Please check the path.")
except FileNotFoundError:
# Create a sample image if 'lena.jpg' is not found
print("Lena.jpg not found. Creating a sample image with noise.")
original_image = np.zeros((512, 512, 3), dtype=np.uint8)
original_image[:] = (128, 128, 128) # Gray background
cv2.circle(original_image, (256, 256), 100, (255, 0, 0), -1) # Blue circle
cv2.rectangle(original_image, (100, 100), (200, 200), (0, 255, 0), -1) # Green square
cv2.putText(original_image, "OpenCV", (150, 350), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 3)
# --- 2. Add Salt-and-Pepper Noise ---
# This function is a great way to test the median blur.
# It randomly replaces some pixels with 0 (pepper) and 255 (salt).
def add_salt_pepper_noise(image, prob):
"""
Adds salt and pepper noise to an image.
prob: Probability of a pixel being noise.
"""
output = np.copy(image)
# Salt mode
salt_coords = np.random.rand(*image.shape[:2]) <= prob / 2
output[salt_coords] = 255
# Pepper mode
pepper_coords = np.random.rand(*image.shape[:2]) <= prob / 2
output[pepper_coords] = 0
return output
noisy_image = add_salt_pepper_noise(original_image, prob=0.05)
# --- 3. Apply Median Blur ---
# We'll try a few different kernel sizes to see the effect.
# Kernel size MUST be an odd number (3, 5, 7, ...).
blurred_image_3x3 = cv2.medianBlur(noisy_image, 3)
blurred_image_5x5 = cv2.medianBlur(noisy_image, 5)
blurred_image_7x7 = cv2.medianBlur(noisy_image, 7)
# --- 4. Display the Results ---
# Using matplotlib for easy side-by-side comparison
images = [original_image, noisy_image, blurred_image_3x3, blurred_image_5x5, blurred_image_7x7]s = ['Original Image', 'Noisy Image (5%)', 'Median Blur (3x3)', 'Median Blur (5x5)', 'Median Blur (7x7)']
plt.figure(figsize=(15, 10))
for i in range(len(images)):
# Convert BGR (OpenCV) to RGB (Matplotlib) for correct color display
img_rgb = cv2.cvtColor(images[i], cv2.COLOR_BGR2RGB)
plt.subplot(2, 3, i + 1), plt.imshow(img_rgb)
plt.title(titles[i]), plt.xticks([]), plt.yticks([])
plt.tight_layout()
plt.show()
Expected Output:
As you can see from the plot:
- The Noisy Image has random black and white pixels scattered everywhere.
- The Median Blur (3x3) does an excellent job of removing almost all the noise while keeping the image details relatively sharp.
- The Median Blur (5x5) removes all the noise but starts to slightly blur the edges of the shapes.
- The Median Blur (7x7) completely removes the noise but results in significant loss of detail and edge sharpness.
This demonstrates the trade-off: a larger kernel is more effective at removing noise but also more destructive to the image's fine details.
Comparison with Other Blurs
To understand the power of the median blur, let's compare it with a Gaussian blur on the same noisy image.
# Using the 'noisy_image' from the previous example
# Apply Gaussian Blur for comparison
# The kernel size for Gaussian blur can be even (e.g., 5, 5)
# sigmaX is the standard deviation in X direction. 0 means it's calculated from kernel size.
blurred_gaussian = cv2.GaussianBlur(noisy_image, (5, 5), 0)
# Display the comparison
plt.figure(figsize=(12, 6))
plt.subplot(1, 3, 1)
plt.imshow(cv2.cvtColor(noisy_image, cv2.COLOR_BGR2RGB))'Noisy Image')
plt.axis('off')
plt.subplot(1, 3, 2)
plt.imshow(cv2.cvtColor(blurred_gaussian, cv2.COLOR_BGR2RGB))'Gaussian Blur (5x5)')
plt.axis('off')
plt.subplot(1, 3, 3)
plt.imshow(cv2.cvtColor(blurred_image_5x5, cv2.COLOR_BGR2RGB))'Median Blur (5x5)')
plt.axis('off')
plt.tight_layout()
plt.show()
Expected Output:
Key Observation: The Gaussian blur smooths the image but the salt-and-pepper noise is still faintly visible. It has averaged the noise, but since the noise consists of extreme values, they still have an impact. The Median blur has completely eliminated the noise, leaving a much cleaner image. This is why median blur is the go-to filter for salt-and-pepper noise.
Summary
| Feature | Median Blur (cv2.medianBlur) |
Gaussian Blur (cv2.GaussianBlur) |
|---|---|---|
| Type | Non-linear | Linear |
| Best For | Salt-and-Pepper noise, impulse noise. | General-purpose smoothing, reducing Gaussian noise. |
| Edge Preservation | Excellent. Preserves sharp edges well. | Good, but can slightly blur edges. |
| Kernel Size | Must be an odd integer (3, 5, 7...). | Can be odd or even (e.g., 5, 5). |
| When to Use | When your image has "speckles" of black and white pixels. | For general softening, reducing minor graininess, or as a preprocessing step. |
