|
| 1 | +# Median Filter (Sliding Window) |
| 2 | + |
| 3 | +## Overview & Motivation |
| 4 | + |
| 5 | +Impulsive noise — EMI clicks, dropped ADC bits, salt-and-pepper sensor glitches — corrupts embedded |
| 6 | +sensor streams in a way that linear averaging amplifies rather than rejects. A single outlier sample |
| 7 | +at 100× the signal level drags a moving-average output for the entire window duration. The median |
| 8 | +filter eliminates isolated spikes completely, using only comparisons and no arithmetic on the signal |
| 9 | +values themselves, making it an ideal non-linear pre-processor for noisy ADC and sensor streams. |
| 10 | + |
| 11 | +## Mathematical Theory |
| 12 | + |
| 13 | +### Core Definition |
| 14 | + |
| 15 | +Let $x[n]$ be the input sequence and $N$ the window length. Define the sorted window snapshot as |
| 16 | +$x_{(1)} \le x_{(2)} \le \cdots \le x_{(N)}$ (order statistics). The median filter output is: |
| 17 | + |
| 18 | +$$y[n] = x_{(\lceil N/2 \rceil)}$$ |
| 19 | + |
| 20 | +For odd $N$ this is the unique middle order statistic. For even $N$ one common convention takes the |
| 21 | +average of the two central statistics, but this introduces arithmetic on the signal and the |
| 22 | +associated round-off. |
| 23 | + |
| 24 | +### Impulse Rejection Threshold |
| 25 | + |
| 26 | +A spike is suppressed if and only if it does not form a strict majority of the window, i.e., if fewer |
| 27 | +than $\lceil N/2 \rceil$ samples share the outlier level. An isolated impulse occupies exactly one |
| 28 | +slot; it is always rejected for $N \ge 3$. |
| 29 | + |
| 30 | +### Step-Edge Preservation |
| 31 | + |
| 32 | +A step transition from level $a$ to level $b$ causes the median to switch from $a$ to $b$ after |
| 33 | +exactly $\lfloor N/2 \rfloor$ samples of delay — without overshoot, Gibbs ringing, or smearing. This |
| 34 | +is the fundamental advantage over linear filters: the nonlinearity of the sort operation preserves |
| 35 | +edges while rejecting impulses. |
| 36 | + |
| 37 | +### Lag |
| 38 | + |
| 39 | +The causal sliding-window median introduces a latency of $\lfloor (N-1)/2 \rfloor$ samples, which |
| 40 | +is the same group delay as a symmetric FIR of the same length. Unlike a linear FIR, however, the |
| 41 | +delay is signal-dependent near edges. |
| 42 | + |
| 43 | +## Algorithm |
| 44 | + |
| 45 | +### Insertion-Sort Approach |
| 46 | + |
| 47 | +For small, fixed window sizes $N$ (typically 3–9 in embedded use), copying the ring buffer into a |
| 48 | +scratch array and applying insertion sort is cache-friendly and avoids heap allocation. The |
| 49 | +comparison count is at most $N(N-1)/2$ — fully bounded by the compile-time constant $N$. |
| 50 | + |
| 51 | +Insertion sort on the scratch copy: |
| 52 | + |
| 53 | +$$\text{for } i = 1, \ldots, N-1: \text{ shift } \text{scratch}[0 \ldots i-1] \text{ right until sorted position for scratch}[i]$$ |
| 54 | + |
| 55 | +The median is then $\text{scratch}[\lfloor N/2 \rfloor]$. |
| 56 | + |
| 57 | +### Huang Histogram Variant |
| 58 | + |
| 59 | +Huang, Yang, and Tang (1979) describe an $O(1)$-per-sample update based on a running histogram: the |
| 60 | +departing sample decrements its histogram bin and the arriving sample increments its bin, then the |
| 61 | +median bin is walked left or right by one position. This reduces per-sample work from $O(N)$ to |
| 62 | +$O(1)$ but requires a histogram array indexed over the signal alphabet — impractical for |
| 63 | +floating-point streams on embedded targets. |
| 64 | + |
| 65 | +## Complexity Analysis |
| 66 | + |
| 67 | +| Variant | Time per sample | Space | Notes | |
| 68 | +|----------------------|-----------------|---------|--------------------------------------------| |
| 69 | +| Insertion sort (used) | $O(N)$ | $O(N)$ | Optimal for small fixed $N$; no heap | |
| 70 | +| Huang histogram | $O(1)$ | $O(K)$ | $K$ = alphabet size; integer signals only | |
| 71 | + |
| 72 | +For $N \le 9$ the insertion-sort inner loop is unrolled by the compiler and runs in a handful of |
| 73 | +compare-and-swap operations — faster in practice than histogram maintenance. |
| 74 | + |
| 75 | +## Step-by-Step Walkthrough |
| 76 | + |
| 77 | +Input: $x = [0.1, 0.1, 0.9, 0.1, 0.1]$, window size $N = 3$, initial window pre-seeded with $0.0$. |
| 78 | + |
| 79 | +| $n$ | $x[n]$ | Window (ring buffer) | Sorted scratch | $y[n]$ | |
| 80 | +|-----|--------|----------------------|---------------------|--------| |
| 81 | +| 0 | 0.1 | [0.0, 0.0, 0.1] | [0.0, **0.0**, 0.1] | 0.0 | |
| 82 | +| 1 | 0.1 | [0.0, 0.1, 0.1] | [0.0, **0.1**, 0.1] | 0.1 | |
| 83 | +| 2 | 0.9 | [0.1, 0.1, 0.9] | [0.1, **0.1**, 0.9] | 0.1 | |
| 84 | +| 3 | 0.1 | [0.1, 0.9, 0.1] | [0.1, **0.1**, 0.9] | 0.1 | |
| 85 | +| 4 | 0.1 | [0.9, 0.1, 0.1] | [0.1, **0.1**, 0.9] | 0.1 | |
| 86 | + |
| 87 | +The bold value is the median at index $\lfloor 3/2 \rfloor = 1$. The spike at $n = 2$ ($x = 0.9$) |
| 88 | +appears in only one of the three window slots at any given time, so it is never the majority and |
| 89 | +never reaches the output. |
| 90 | + |
| 91 | +## Pitfalls & Edge Cases |
| 92 | + |
| 93 | +- **Even window length**: the two central order statistics may differ, requiring an average; use odd |
| 94 | + $N$ to keep the output comparison-only. |
| 95 | +- **Window width vs. pulse width**: an impulse burst wider than $\lfloor N/2 \rfloor$ samples is |
| 96 | + not rejected; $N$ must be at least $2 \times \text{burst\_width} + 1$. |
| 97 | +- **Startup / warm-up**: pre-seeding the window with an initial value prevents undefined output |
| 98 | + during the first $N-1$ samples. |
| 99 | +- **Signal plateaus**: when the signal is constant at the impulse level for more than half the |
| 100 | + window, that value becomes the majority and passes through — this is expected behaviour and |
| 101 | + documents the $\lfloor N/2 \rfloor$ rejection limit. |
| 102 | +- **Latency vs. rejection trade-off**: increasing $N$ widens the rejection band but also increases |
| 103 | + latency and rounds off narrow legitimate peaks. |
| 104 | + |
| 105 | +## Variants & Generalizations |
| 106 | + |
| 107 | +- **Weighted median**: assigns integer multiplicities to samples; shifts the breakdown point without |
| 108 | + changing the comparison-only property. |
| 109 | +- **Running-histogram median (Huang 1979)**: $O(1)$ update for integer signals over a bounded |
| 110 | + alphabet. |
| 111 | +- **Two-pass 2-D median**: Huang's paper targets image processing; separable row–column passes |
| 112 | + generalize to 2-D arrays. |
| 113 | +- **Recursive median**: feeds filtered output back into the window; achieves stronger smoothing at |
| 114 | + the cost of potential limit-cycle oscillations. |
| 115 | + |
| 116 | +## Applications |
| 117 | + |
| 118 | +- ADC spike rejection before integration or threshold detection. |
| 119 | +- Salt-and-pepper denoising in IMU/MEMS sensor streams. |
| 120 | +- Pre-filter before a PID controller to prevent derivative kick from glitches. |
| 121 | +- Image-row processing on embedded vision pipelines (1-D median per scan line). |
| 122 | + |
| 123 | +## Connections to Other Algorithms |
| 124 | + |
| 125 | +- `MovingAverage` is the linear equivalent; it smears both noise and edges, while the median |
| 126 | + preserves edges at the cost of being nonlinear and harder to analyse in the frequency domain. |
| 127 | +- `ExponentialMovingAverage` provides even lower memory cost but is sensitive to impulsive outliers. |
| 128 | +- `FirFilter` with optimal coefficients can achieve equiripple passband/stopband behaviour but |
| 129 | + cannot reject isolated spikes without distorting step edges. |
| 130 | + |
| 131 | +## References & Further Reading |
| 132 | + |
| 133 | +- T. Huang, G. Yang, G. Tang, "A fast two-dimensional median filtering algorithm," *IEEE |
| 134 | + Transactions on Acoustics, Speech, and Signal Processing*, 27(1), pp. 13–18, 1979. |
| 135 | +- A. V. Oppenheim & R. W. Schafer, *Discrete-Time Signal Processing*, 3rd ed., §11.4 — Median and |
| 136 | + Order-Statistic Filters. |
| 137 | +- L. Yin, R. Yang, M. Gabbouj, Y. Neuvo, "Weighted median filters: a tutorial," *IEEE Transactions |
| 138 | + on Circuits and Systems II*, 43(3), 1996. |
0 commit comments