Selected Reading

SciPy - ndimage.median_filter() Function



The scipy.ndimage.median_filter() is a function in the SciPy library which is used to apply a median filter to an image or array. It replaces each pixel in the input with the median value of the pixels within a specified neighborhood which is typically defined by a square or rectangular region.

The size of this neighborhood is controlled by the size parameter. This filter is particularly effective at removing salt-and-pepper noise while preserving edges in an image. It supports various boundary handling modes like 'reflect', 'constant' and 'nearest' and can work with multi-dimensional arrays

Syntax

Following is the syntax of the function scipy.ndimage.median_filter() to perform LU Decomposition −

scipy.ndimage.median_filter(a, permute_l=False, overwrite_a=False, check_finite=True, p_indices=False)

Parameters

Below are the parameters of the scipy.ndimage.median_filter() function −

  • input (array_like): The input image or array on which the median filter will be applied. This is usually a 2D image or a multi-dimensional array.
  • size (int or tuple of ints, optional): This parameter specifies the size of the neighborhood used to compute the median. It can be a single integer i.e., for a square neighborhood or a tuple such as (3, 3) for a 3x3 neighborhood. The default value is 3.
  • footprint (array_like, optional): A boolean array that defines the shape of the neighborhood. This can be used instead of size. The default value is None.
  • output (array, optional): The array where the result will be stored. If None (default) then a new array is created to store the output.
  • mode (str, optional): This parameter defines how the input array is extended beyond its boundaries. The available modes are as follows −
    • reflect: This is the default value where the array is reflected at the boundaries.
    • constant: Pads with a constant value (specified by cval).
    • nearest: Pads with the nearest boundary value.
    • mirror: Similar to reflect but without copying the boundary values.
    • wrap: Wraps the array from the opposite side.
  • cval (scalar, optional): The constant value used for padding when mode='constant'. The default value is 0.0.
  • origin (int or tuple of ints, optional): This specifies the position of the filter kernel relative to the input array. The default value is 0 which means the kernel is centered on the pixel.

Return Value

The scipy.ndimage.median_filter() function returns a new array with the same shape as the input where each element has been replaced by the median of its neighborhood.

Basic Example

Following is the basic example which uses scipy.ndimage.median_filter() function to remove the salt-and-pepper noise from the given input image −

import numpy as np
from scipy.ndimage import median_filter
import matplotlib.pyplot as plt

# Create an image with salt-and-pepper noise
np.random.seed(0)
image = np.ones((100, 100)) * 128  # Base grayscale image
noise = np.random.choice([0, 255], (100, 100), p=[0.95, 0.05])  # Salt-and-pepper noise
noisy_image = np.clip(image + noise, 0, 255).astype(np.uint8)

# Apply median filter with a 3x3 kernel
filtered_image = median_filter(noisy_image, size=3)

# Display the results
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title("Noisy Image (Salt-and-Pepper)")
plt.imshow(noisy_image, cmap='gray')
plt.axis('off')

plt.subplot(1, 2, 2)
plt.title("Filtered Image")
plt.imshow(filtered_image, cmap='gray')
plt.axis('off')

plt.tight_layout()
plt.show()

Here is the output of the scipy.ndimage.median_filter() function used to remove salt-and-pepper noise −

Basic Median Filter

Smoothing a Grayscale Image

This example applies the median filter to a smooth grayscale gradient image to reduce noise while preserving edges −

import numpy as np
from scipy.ndimage import median_filter
import matplotlib.pyplot as plt

# Create a smooth grayscale gradient image
gradient_image = np.linspace(0, 255, 100*100).reshape(100, 100).astype(np.uint8)
gradient_image_with_noise = gradient_image + np.random.normal(0, 10, gradient_image.shape).astype(np.uint8)

# Apply median filter with a 5x5 kernel
filtered_gradient = median_filter(gradient_image_with_noise, size=5)

# Display the results
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title("Noisy Gradient Image")
plt.imshow(gradient_image_with_noise, cmap='gray')
plt.axis('off')

plt.subplot(1, 2, 2)
plt.title("Filtered Gradient Image")
plt.imshow(filtered_gradient, cmap='gray')
plt.axis('off')

plt.tight_layout()
plt.show()

Here is the output of the scipy.ndimage.median_filter() function used to smooth the grayscale Image −

Median smooth Filter

Filtering a Binary Image

Here is the example which shows how the median filter can remove noise from binary images by using the function scipy.ndimage.median_filter()

import numpy as np
from scipy.ndimage import median_filter
import matplotlib.pyplot as plt

# Create a binary image with noise
binary_image = np.zeros((100, 100), dtype=np.uint8)
binary_image[30:70, 30:70] = 1
noise = np.random.choice([0, 1], size=(100, 100), p=[0.95, 0.05])
noisy_binary_image = np.clip(binary_image + noise, 0, 1)

# Apply median filter with a 3x3 kernel
filtered_binary = median_filter(noisy_binary_image, size=3)

# Display the results
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title("Noisy Binary Image")
plt.imshow(noisy_binary_image, cmap='gray')
plt.axis('off')

plt.subplot(1, 2, 2)
plt.title("Filtered Binary Image")
plt.imshow(filtered_binary, cmap='gray')
plt.axis('off')

plt.tight_layout()
plt.show()

Here is the output of the scipy.ndimage.median_filter() function used to filter the binary Image −

Median Binary Filter
Advertisements