← Back to Documentation

Algorithm Reference: Median Filtering

Type: Non-Linear Digital Filter
Library: OpenCV (cv2.medianBlur)
Application: Salt-and-Pepper Noise Removal

The Median Filter is a non-linear digital filtering technique, often used to remove noise from an image or signal. Unlike linear filters (like Gaussian or Box Blur) which calculate the average, the Median filter replaces a pixel with the median value of its neighbourhood. This preserves edges while eliminating outliers.

1. Mathematical Formulation

For a given pixel at location (x, y), we consider a neighbourhood w centered around it. The new intensity value I'(x, y) is calculated by sorting all pixel intensities in the window and picking the middle one.

I'(x, y) = median({ I(i, j) | (i, j) ∈ w })

Because the median is a robust statistic, unrepresentative pixel values (like extreme black or white dots caused by sensor noise) are effectively ignored, rather than being averaged into the result.

2. Python Backend Logic (Snippet)

We implement this using OpenCV's optimized backend. The kernel size (k) determines the size of the neighbourhood.

Constraint: The kernel size must always be an odd integer (e.g., 3, 5, 7) to ensure there is a single central pixel to replace.


def apply_median_blur(image, kernel_size):
    # Validate that kernel_size is odd
    if kernel_size % 2 == 0:
        raise ValueError("Kernel size must be odd")

    # Apply Median Blur
    # Effectively removes salt-and-pepper noise
    denoised_image = cv2.medianBlur(
        image,
        ksize=kernel_size
    )

    return denoised_image

3. Algorithmic Complexity

A naive implementation of a median filter requires sorting the values in the k × k window for every pixel. This would result in a complexity of:

However, OpenCV uses an optimized Histogram-based approach (for 8-bit images) or Huang's Algorithm, which brings the complexity down to O(r) or even O(1) relative to the window size, allowing for real-time processing on the server.

Try the Denoising Tool:

Launch Live Tool