SciPy - Median Filter



Median Filter in SciPy

The Median Filter in SciPy is a non-linear image processing technique used to remove noise especially salt-and-pepper noise while preserving edges. It works by replacing each pixel in an image with the median of the values in its surrounding neighborhood which can be a square or rectangular region.

This filter is effective in smoothing images without blurring sharp edges as it is less sensitive to outliers compared to linear filters. The neighborhood size is adjustable such as 3x3, 5x5 and it is commonly used in preprocessing stages of image analysis for denoising.

The scipy.ndimage module of scipy library have a function namely, median_filter() to apply the median filter on the given images to remove salt-and-pepper noise by preserving the details of the edges.

Syntax

Following is the syntax of the scipy.ndimage.median_filter() function to apply the median filter −

scipy.ndimage.median_filter(input, size, footprint=None, output=None, mode='reflect', cval=0.0, origin=0)

Following are the parameters of the scipy.ndimage.median_filter

  • input: The input image or array to which the filter will be applied.
  • size: The size of the neighborhood i.e., a tuple or scalar. If scalar then a square neighborhood is used ie., 3 means a 3x3 neighborhood.
  • footprint(optional): A binary array that defines the neighborhood shape.
  • output(optional): The array to store the result.
  • mode: The mode used to handle borders such as 'reflect', 'constant', 'nearest', etc.
  • cval(optional): The constant value used when mode='constant'
  • origin: The offset for the neighborhood with default value as 0.

How Median Filter Works?

Following are the steps to be followed while implementing the Median Filter in removing the salt-and-pepper noise from the image −

  • Neighborhood Selection: For each pixel there will be a neighborhood of surrounding pixels is considered. For example a 3x3 or 5x5 grid.
  • Median Calculation: The median value of the pixels in that neighborhood is calculated.
  • Pixel Replacement: The central pixel is replaced with the median value.
  • Preserving Edges: The median filter is particularly effective at removing noise without blurring sharp edges in an image.

Advantages of Median filter

Here are the advantages of using the Median filter in Image processing −

  • Effective for Salt-and-Pepper Noise: Removes noise without blurring the edges as much as linear filters.
  • Non-linear: It does not rely on weighted sums by making it resistant to outliers.

Limitations of Median Filter

The Median filter not only have the benefits while using it but also have some limitations, which can be mentioned as follows −

  • Computational Cost: The median filter can be computationally more expensive than linear filters for larger neighborhoods.
  • Edge Effects: This filter may not perform as well at the edges of the image where the neighborhood size is constrained by the image boundary.

Basic Median Filter Example

Following is an example shows how to apply a simple Median Filter on a 2D image or array to remove noise with the help of scipy.ndimage.median_filter() function −

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

# Sample 2D image (5x5 grid)
image = np.array([[1, 2, 3, 4, 5],
                  [6, 7, 8, 9, 10],
                  [11, 12, 13, 14, 15],
                  [16, 17, 18, 19, 20],
                  [21, 22, 23, 24, 25]])

# Apply median filter with a 3x3 neighborhood
filtered_image = ndimage.median_filter(image, size=3)

# Plot original and filtered images
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
axes[0].imshow(image, cmap='gray')
axes[0].set_title('Original Image')
axes[0].axis('off')

axes[1].imshow(filtered_image, cmap='gray')
axes[1].set_title('Median Filtered Image')
axes[1].axis('off')

plt.show()

Following is the output of the basic median filter −

Median filter example

Median Filter with a Larger Neighborhood

This example uses a larger neighborhood for the median filter such as 5x5 to show the effect of smoothing on a larger area −

import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage
from skimage import data

# Load sample image
image = data.camera()

# Apply median filter with a 5x5 neighborhood
filtered_image = ndimage.median_filter(image, size=5)

# Plot original and filtered images
fig, axes = plt.subplots(1, 2, figsize=(12, 6))
axes[0].imshow(image, cmap='gray')
axes[0].set_title('Original Image')
axes[0].axis('off')

axes[1].imshow(filtered_image, cmap='gray')
axes[1].set_title('Median Filtered (5x5) Image')
axes[1].axis('off')

plt.show()

Following is the output of the median filter applied on the Larger neighborhood−

Median filter with neighboorhood

Applying Median Filter to 3D Image

Applying a median filter to a 3D image is similar to applying it to a 2D image but in 3D, the filter works across a volume of data where each voxel (3D pixel) is replaced by the median of its neighbors within a defined neighborhood.

This can be useful for denoising 3D data such as medical imaging, volumetric data from simulations or 3D scanning data. Here is the example where a 3D image is processed with a median filter −

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

# Create a synthetic 3D image (10x10x10 array)
image_3d = np.random.random((10, 10, 10))

# Apply median filter with a 3x3x3 neighborhood
filtered_image_3d = ndimage.median_filter(image_3d, size=3)

# Plot original and filtered slices (3D visualization)
fig, axes = plt.subplots(1, 2, figsize=(12, 6))
axes[0].imshow(image_3d[5, :, :], cmap='gray')  # Show middle slice
axes[0].set_title('Original 3D Slice')
axes[0].axis('off')

axes[1].imshow(filtered_image_3d[5, :, :], cmap='gray')  # Show middle slice of filtered image
axes[1].set_title('Median Filtered 3D Slice')
axes[1].axis('off')

plt.show()

Following is the output of the median filter applied 3D Image −

Median filter on 3d image
Advertisements