Median Filter
Non-linear filter excellent for removing salt-and-pepper noise while preserving edges.
Definition
Replace each sample with the median of its neighborhood:
$$ y[n] = \text{median}{x[n-k], \ldots, x[n], \ldots, x[n+k]} $$
Implementation
1from scipy import signal, ndimage
2import numpy as np
3
4# 1D median filter
5window_size = 5
6y = signal.medfilt(x, kernel_size=window_size)
7
8# 2D median filter (images)
9filtered_image = ndimage.median_filter(image, size=3)
Advantages
- Preserves edges
- Removes impulse noise effectively
- No ringing artifacts
Disadvantages
- Non-linear (no frequency response)
- Slower than linear filters
- Can remove fine details
Use Cases
- Salt-and-pepper noise removal
- Image preprocessing
- Outlier removal in sensor data
Related Snippets
- Filter Design Principles
Choosing and designing digital filters - FIR Filters
Finite Impulse Response digital filters - IIR Filters
Infinite Impulse Response digital filters - Kalman Filter
Optimal state estimation for linear systems - Madgwick Filter - Orientation Estimation
Gradient descent orientation filter for IMU sensor fusion - Mahony Filter - Orientation Estimation
Complementary filter with PI controller for IMU sensor fusion - Sensor Fusion with Kalman Filters
Combining multiple sensors using Kalman filtering