
- SciPy - Home
- SciPy - Introduction
- SciPy - Environment Setup
- SciPy - Basic Functionality
- SciPy - Relationship with NumPy
- SciPy Clusters
- SciPy - Clusters
- SciPy - Hierarchical Clustering
- SciPy - K-means Clustering
- SciPy - Distance Metrics
- SciPy Constants
- SciPy - Constants
- SciPy - Mathematical Constants
- SciPy - Physical Constants
- SciPy - Unit Conversion
- SciPy - Astronomical Constants
- SciPy - Fourier Transforms
- SciPy - FFTpack
- SciPy - Discrete Fourier Transform (DFT)
- SciPy - Fast Fourier Transform (FFT)
- SciPy Integration Equations
- SciPy - Integrate Module
- SciPy - Single Integration
- SciPy - Double Integration
- SciPy - Triple Integration
- SciPy - Multiple Integration
- SciPy Differential Equations
- SciPy - Differential Equations
- SciPy - Integration of Stochastic Differential Equations
- SciPy - Integration of Ordinary Differential Equations
- SciPy - Discontinuous Functions
- SciPy - Oscillatory Functions
- SciPy - Partial Differential Equations
- SciPy Interpolation
- SciPy - Interpolate
- SciPy - Linear 1-D Interpolation
- SciPy - Polynomial 1-D Interpolation
- SciPy - Spline 1-D Interpolation
- SciPy - Grid Data Multi-Dimensional Interpolation
- SciPy - RBF Multi-Dimensional Interpolation
- SciPy - Polynomial & Spline Interpolation
- SciPy Curve Fitting
- SciPy - Curve Fitting
- SciPy - Linear Curve Fitting
- SciPy - Non-Linear Curve Fitting
- SciPy - Input & Output
- SciPy - Input & Output
- SciPy - Reading & Writing Files
- SciPy - Working with Different File Formats
- SciPy - Efficient Data Storage with HDF5
- SciPy - Data Serialization
- SciPy Linear Algebra
- SciPy - Linalg
- SciPy - Matrix Creation & Basic Operations
- SciPy - Matrix LU Decomposition
- SciPy - Matrix QU Decomposition
- SciPy - Singular Value Decomposition
- SciPy - Cholesky Decomposition
- SciPy - Solving Linear Systems
- SciPy - Eigenvalues & Eigenvectors
- SciPy Image Processing
- SciPy - Ndimage
- SciPy - Reading & Writing Images
- SciPy - Image Transformation
- SciPy - Filtering & Edge Detection
- SciPy - Top Hat Filters
- SciPy - Morphological Filters
- SciPy - Low Pass Filters
- SciPy - High Pass Filters
- SciPy - Bilateral Filter
- SciPy - Median Filter
- SciPy - Non - Linear Filters in Image Processing
- SciPy - High Boost Filter
- SciPy - Laplacian Filter
- SciPy - Morphological Operations
- SciPy - Image Segmentation
- SciPy - Thresholding in Image Segmentation
- SciPy - Region-Based Segmentation
- SciPy - Connected Component Labeling
- SciPy Optimize
- SciPy - Optimize
- SciPy - Special Matrices & Functions
- SciPy - Unconstrained Optimization
- SciPy - Constrained Optimization
- SciPy - Matrix Norms
- SciPy - Sparse Matrix
- SciPy - Frobenius Norm
- SciPy - Spectral Norm
- SciPy Condition Numbers
- SciPy - Condition Numbers
- SciPy - Linear Least Squares
- SciPy - Non-Linear Least Squares
- SciPy - Finding Roots of Scalar Functions
- SciPy - Finding Roots of Multivariate Functions
- SciPy - Signal Processing
- SciPy - Signal Filtering & Smoothing
- SciPy - Short-Time Fourier Transform
- SciPy - Wavelet Transform
- SciPy - Continuous Wavelet Transform
- SciPy - Discrete Wavelet Transform
- SciPy - Wavelet Packet Transform
- SciPy - Multi-Resolution Analysis
- SciPy - Stationary Wavelet Transform
- SciPy - Statistical Functions
- SciPy - Stats
- SciPy - Descriptive Statistics
- SciPy - Continuous Probability Distributions
- SciPy - Discrete Probability Distributions
- SciPy - Statistical Tests & Inference
- SciPy - Generating Random Samples
- SciPy - Kaplan-Meier Estimator Survival Analysis
- SciPy - Cox Proportional Hazards Model Survival Analysis
- SciPy Spatial Data
- SciPy - Spatial
- SciPy - Special Functions
- SciPy - Special Package
- SciPy Advanced Topics
- SciPy - CSGraph
- SciPy - ODR
- SciPy Useful Resources
- SciPy - Reference
- SciPy - Quick Guide
- SciPy - Cheatsheet
- SciPy - Useful Resources
- SciPy - Discussion
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 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−

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 −
