Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Rank filters, derivative filters and geometric transforms

ProblemRemove impulse noise without blurring edges; differentiate a noisy image at a chosen scale; resample an image after a rotation, shift, scaling or general affine map
Devised byThe median filter: John Tukey (1971, “running medians”); Gaussian derivative filters and scale space: Iijima (1962), Andrew Witkin (1983), Jan Koenderink (1984); B-spline interpolation by recursive filtering: Michael Unser, Akram Aldroubi and Murray Eden (1991–1993)
AccuracyRank filters are identical to scipy.ndimage; Gaussian filters and spline interpolation agree to (quintic splines in Nearest mode to )
CostRank filter: per pixel (selection) for a -pixel window; Gaussian derivatives: per pixel (separable); spline interpolation of order : an prefilter, then per output pixel
Read firstImage filtering: convolution, Gaussian blur, Sobel gradients and sharpening, Splines
APImedian_filter, rank_filter, percentile_filter, minimum_filter, maximum_filter, gaussian_filter, gaussian_laplace, gaussian_gradient_magnitude, laplace, spline_filter, map_coordinates, affine_transform, shift, zoom, rotate

Overview

This entry collects three families of scipy.ndimage operations that work on any greyscale image.

Rank filters replace each pixel by an order statistic of its neighbourhood: the median, a percentile, the minimum or the maximum. A linear filter averages an outlier into its surroundings; the median simply ignores it, so a median removes “salt-and-pepper” noise almost completely while keeping edges sharp.

Derivative filters estimate the derivatives of an image at a chosen scale. Differentiating raw pixels amplifies noise; differentiating after Gaussian smoothing does not, and since differentiation commutes with convolution, the two steps are one convolution with a derivative of the Gaussian. The gradient magnitude finds edges at scale , and the Laplacian of a Gaussian finds blobs.

Geometric transforms move pixels: shift, rotate, zoom, or apply any affine map. Each output pixel comes from a point between input pixels, so the image must be interpolated. Order 0 takes the nearest pixel, order 1 is bilinear, and the default, order 3, is the cubic B-spline. For orders above 1 the spline must pass through the pixels, which needs a prefilter first.

Where it is used

Median-type filters and geometric transforms handle two very common image defects.

  • Impulse noise. Median filters remove salt-and-pepper noise from transmission errors or dead sensor pixels without blurring edges.
  • Derivatives at a scale. Gaussian derivative filters measure edges and ridges at the scale of the structure of interest (blood vessels, cracks).
  • Rotation, scaling and warping. Resampling with interpolation is used to correct lens distortion, rectify aerial photographs and align frames.

History

John Tukey introduced running medians in 1971 for smoothing time series that contain outliers, and the two-dimensional median filter soon became the standard cure for impulse noise in images. Its theory (which signals pass through unchanged, the “root signals”) was developed through the 1980s.

Smoothing with Gaussians of increasing width, and taking derivatives of the smoothed image, was proposed by Taizo Iijima in Japan in 1962 and rediscovered in the West as scale space by Andrew Witkin (1983) and Jan Koenderink (1984). The Gaussian is the only smoothing kernel that creates no new extrema as the scale grows, which is why its derivatives are the standard measurements at a scale. David Marr and Ellen Hildreth (1980) used the zero crossings of the Laplacian of a Gaussian as edges.

Interpolation by B-splines was well understood in approximation theory, but evaluating it exactly through the samples seemed to require solving a large linear system. Michael Unser, Akram Aldroubi and Murray Eden (1991, 1993) showed that the system’s inverse is a pair of recursive filters per pole, applied along each axis in operations. Their method is what scipy.ndimage and this library implement.

The idea

Rank filters

For a window (the footprint) of pixels around each pixel, sort the values; the rank filter of rank returns the -th smallest. The median is , the minimum and the maximum ; the minimum and maximum are the greyscale erosion and dilation of the morphology entry. Selection (not a full sort) finds the -th value in time.

The median keeps a step edge exactly: in a window straddling the edge, more than half the pixels lie on one side, so the median is a value from that side. And it ignores impulses: an isolated outlier is one of values, at the end of the sorted list, so it cannot be the median. A Gaussian blur does neither: it spreads each outlier into a blob and softens each edge.

Figure 17.16. Median against Gaussian smoothing.

Table 17.6. Peak signal-to-noise ratio (dB) after Gaussian and median smoothing, for impulse and Gaussian noise.

noisenoisyGaussian σ = 0.8Gaussian σ = 1.5median 3 × 3median 5 × 5
impulse noise (10%)15.523.024.131.228.4
Gaussian noise (σ = 0.08)21.928.226.228.327.6

On impulse noise the median gains 16 dB, far more than any Gaussian. On Gaussian noise the median and a small Gaussian do about equally well: there are no outliers to ignore, and averaging is the right thing to do.

Gaussian derivatives

The Gaussian of standard deviation is sampled at integers out to and normalised to sum 1. Its derivatives multiply it by polynomials: for the first (with the sign arranged so that correlation estimates ), and for the second. Because the two-dimensional Gaussian is a product of two one-dimensional ones, every derivative filter is two one-dimensional passes: , for example, is the second-derivative kernel down the columns and the smoothing kernel along the rows.

The truncated, sampled kernels are not exact. On the linear ramp , the first-derivative filter with returns , not 3, because the discrete second moment of the sampled Gaussian is not exactly . SciPy’s kernels, which these reproduce exactly, make the same error.

Figure 17.17. Gaussian derivatives.

At the gradient magnitude shows the edges but also the noise; at the noise is gone and only the large-scale edges remain, broadened to the scale. The Laplacian of a Gaussian is negative inside bright regions and positive inside dark ones, with its strongest response at blobs of radius about .

Interpolation by B-splines

A geometric transform asks for image values at non-integer points. The B-spline of degree , , is the -fold convolution of a unit box with itself: a bell of width made of polynomial pieces of degree , with continuous derivatives. Interpolation writes the image as a combination of shifted B-splines,

and evaluates at any point from the nearest coefficients. For (a box) and (a triangle) the coefficients are the pixel values themselves. For they are not: , for example, has values at the integers, so , and making pass through the pixels means solving this tridiagonal system for .

Unser’s observation is that the system is a convolution, with , so . Factoring with the pole , the inverse is a causal first-order recursion followed by an anti-causal one , with a gain. Higher orders have two poles, each handled the same way. The recursions start from the infinite sums that the boundary symmetry implies, which can be written in closed form for mirror, half-sample-reflect and periodic extensions. The prefilter runs along every row and then every column, and costs a few operations per pixel.

Figure 17.18. Interpolation orders.

Order 0 makes stairs and moves edges by up to half a pixel. Order 1 is continuous but has corners at the samples. Orders 3 and 5 are smooth and exact for polynomials of their degree, but they overshoot near a step, ringing like a band-limited signal, because a smooth curve through a sudden jump must overshoot to stay smooth.

Geometric transforms

All transforms map output coordinates to input coordinates, not the other way: output pixel takes the interpolated value at . Working backwards guarantees that every output pixel gets exactly one value. A shift by has and . A zoom by factor maps output index to , so that the first and last pixels of the output sample the first and last pixels of the input exactly. A rotation by about the centre uses the rotation matrix of and the offset that maps the output centre to the input centre; with reshape the output grows to hold the whole rotated frame. Points that fall outside the input are supplied by the boundary mode; in Constant mode, points outside the input’s extent take the constant.

Figure 17.19. Rotation and magnification.

Every interpolation loses a little, and repeated transforms accumulate the loss. Rotating six times by and back again:

Table 17.7. RMS error after rotating six times by 15° and back, by spline order.

spline ordersmooth image: RMS errorsharp-edged image: RMS error
00.01830.0503
10.01070.0527
20.00030.0244
30.00010.0225
50.00000.0180

On a smooth image the cubic spline is almost lossless, a hundred times better than bilinear interpolation; on an image with sharp edges every order loses detail, because the edges contain frequencies that no sampled image can represent, and higher orders help less.

Algorithm

Rank filter of rank with footprint (origin at its element ): for each pixel, gather the image values at the footprint’s offsets (extended beyond the edges by the boundary mode), select the -th smallest (a negative counts from the largest). The median takes , the percentile takes (and for ).

Gaussian filter with standard deviations and derivative orders : build the one-dimensional kernels of radius ; correlate every column with the row kernel, then every row with the column kernel. The Laplacian of a Gaussian is the sum of the and filters; the gradient magnitude is from the and filters.

Spline interpolation of order at points :

  1. Prefilter: for each line (columns, then rows), multiply by the gain and, for each pole , run the causal recursion from its boundary-implied initial value and then the anti-causal one. In Nearest mode, pad 12 copies of the edge first (as SciPy does).
  2. For each point, find the first coefficient index (for odd , ; for even , ) and the weights along each axis.
  3. Sum the products of weights and coefficients over the neighbourhood, mapping coefficient indices outside the image by the boundary symmetry; in Constant mode, points outside return the constant.

Affine transform: apply step 3 at for every output pixel , reusing one prefilter.

Implementation

The rank filter:

/// The rank filter (SciPy's `rank_filter`): each pixel becomes the `rank`-th smallest value
/// (counting from 0) of the pixels under the footprint centred on it; a negative rank counts from
/// the largest. The footprint's origin is its element `(h / 2, w / 2)`, so even sizes are allowed
/// and extend one further before the pixel than after it, as in SciPy.
pub fn rank_filter(image: &Array2<f64>, rank: isize, footprint: &Array2<bool>, mode: Mode) -> Result<Array2<f64>, ErrorsJSL> {
    let (h, w) = footprint.dim();
    let offsets: Vec<(isize, isize)> = footprint
        .indexed_iter()
        .filter(|(_, b)| **b)
        .map(|((i, j), _)| (i as isize - (h / 2) as isize, j as isize - (w / 2) as isize))
        .collect();
    let n = offsets.len() as isize;
    if n == 0 || image.is_empty() {
        return Err(ErrorsJSL::InvalidInputRange("the image and the footprint must be non-empty"));
    }
    let k = if rank < 0 { n + rank } else { rank };
    if !(0..n).contains(&k) {
        return Err(ErrorsJSL::InvalidInputRange("rank out of range for the footprint"));
    }
    let mut window = vec![0.0; n as usize];
    let mut out = Array2::zeros(image.dim());
    for ((r, c), o) in out.indexed_iter_mut() {
        for (v, &(di, dj)) in window.iter_mut().zip(&offsets) {
            *v = sample(image, r as isize + di, c as isize + dj, mode);
        }
        let (_, kth, _) = window.select_nth_unstable_by(k as usize, |a, b| a.total_cmp(b));
        *o = *kth;
    }
    Ok(out)
}

The Gaussian kernels:

/// SciPy's one-dimensional Gaussian kernel of standard deviation `sigma`, radius
/// `⌊truncate σ + ½⌋`, for derivative order 0, 1 or 2, already reversed for correlation: weights
/// `φ(x)` normalised to sum 1, multiplied by `x/σ²` (first derivative) or `x²/σ⁴ − 1/σ²` (second).
pub fn gaussian_kernel(sigma: f64, order: usize, truncate: f64) -> Result<Vec<f64>, ErrorsJSL> {
    if !(sigma > 0.0) || !(truncate > 0.0) {
        return Err(ErrorsJSL::InvalidInputRange("sigma and truncate must be positive"));
    }
    if order > 2 {
        return Err(ErrorsJSL::InvalidInputRange("derivative order must be 0, 1 or 2"));
    }
    let radius = (truncate * sigma + 0.5) as isize;
    let s2 = sigma * sigma;
    let phi: Vec<f64> = (-radius..=radius).map(|x| (-0.5 * (x * x) as f64 / s2).exp()).collect();
    let total: f64 = phi.iter().sum();
    Ok((-radius..=radius)
        .zip(phi)
        .map(|(x, p)| {
            let x = x as f64;
            let q = match order {
                0 => 1.0,
                1 => x / s2,
                _ => x * x / (s2 * s2) - 1.0 / s2,
            };
            q * p / total
        })
        .collect())
}

The B-spline prefilter:

/// Converts one line of samples into B-spline coefficients in place: an overall gain, then for
/// each pole `z` a causal recursion `c[i] += z c[i − 1]` and an anti-causal one
/// `c[i] = z (c[i + 1] − c[i])`, each started from the infinite sum that the boundary symmetry
/// implies (SciPy's `spline_filter1d`).
fn prefilter_line(c: &mut [f64], order: usize, ext: Ext) {
    let n = c.len();
    if order < 2 || n < 2 {
        return;
    }
    let zs = poles(order);
    let gain: f64 = zs.iter().map(|&z| (1.0 - z) * (1.0 - 1.0 / z)).product();
    c.iter_mut().for_each(|v| *v *= gain);
    for &z in &zs {
        // Causal initial value.
        match ext {
            Ext::Mirror => {
                let zn1 = z.powi(n as i32 - 1);
                let mut zi = z;
                let mut c0 = c[0] + zn1 * c[n - 1];
                for i in 1..n - 1 {
                    c0 += zi * (c[i] + zn1 * c[n - 1 - i]);
                    zi *= z;
                }
                c[0] = c0 / (1.0 - zn1 * zn1);
            }
            Ext::Reflect => {
                let zn = z.powi(n as i32);
                let first = c[0];
                let mut zi = z;
                let mut c0 = c[0] + zn * c[n - 1];
                for i in 1..n {
                    c0 += zi * (c[i] + zn * c[n - 1 - i]);
                    zi *= z;
                }
                c[0] = c0 * z / (1.0 - zn * zn) + first;
            }
            Ext::Wrap => {
                let mut zi = z;
                let mut c0 = c[0];
                for i in 1..n {
                    c0 += zi * c[n - i];
                    zi *= z;
                }
                c[0] = c0 / (1.0 - zi);
            }
        }
        for i in 1..n {
            c[i] += z * c[i - 1];
        }
        // Anti-causal initial value.
        match ext {
            Ext::Mirror => c[n - 1] = (z * c[n - 2] + c[n - 1]) * z / (z * z - 1.0),
            Ext::Reflect => c[n - 1] *= z / (z - 1.0),
            Ext::Wrap => {
                let mut zi = z;
                let mut cn = c[n - 1];
                for &v in &c[..n - 1] {
                    cn += zi * v;
                    zi *= z;
                }
                c[n - 1] = cn * z / (zi - 1.0);
            }
        }
        for i in (0..n - 1).rev() {
            c[i] = z * (c[i + 1] - c[i]);
        }
    }
}

Interpolation at arbitrary points:

/// Interpolates `image` at arbitrary points `(row, column)` (SciPy's `map_coordinates`), with
/// spline order 0 to 5. Coefficients from [`spline_filter`] are combined with B-spline weights over
/// the `(k + 1) × (k + 1)` neighbourhood of each point. In `Constant` mode, points outside the
/// image (beyond `−0.5 … n − 0.5`… precisely, outside `[0, n − 1]`) take the constant, as in SciPy.
pub fn map_coordinates(image: &Array2<f64>, points: &[(f64, f64)], order: usize, mode: Mode) -> Result<Vec<f64>, ErrorsJSL> {
    if image.is_empty() {
        return Err(ErrorsJSL::InvalidInputRange("image must be non-empty"));
    }
    let (coeffs, pad) = spline_filter(image, order, mode)?;
    let (rows, cols) = image.dim();
    let (cr, cc) = coeffs.dim();
    Ok(points
        .iter()
        .map(|&(r, c)| {
            if let Mode::Constant(k) = mode {
                // SciPy treats coordinates within a small tolerance of the edge as inside.
                let tol = 1e-12;
                if r < -tol || c < -tol || r > rows as f64 - 1.0 + tol || c > cols as f64 - 1.0 + tol {
                    return k;
                }
            }
            let (r, c) = (r + pad as f64, c + pad as f64);
            let (sr, wr) = weights(r, order);
            let (sc, wc) = weights(c, order);
            let mut v = 0.0;
            for (i, a) in wr.iter().enumerate() {
                if *a == 0.0 {
                    continue;
                }
                let ri = coeff_index(sr + i as isize, cr, mode);
                for (j, b) in wc.iter().enumerate() {
                    v += a * b * coeffs[(ri, coeff_index(sc + j as isize, cc, mode))];
                }
            }
            v
        })
        .collect())
}
  • Boundary modes follow SciPy: Reflect (default for filters), Mirror, Nearest, Constant(value) and Wrap. For spline interpolation, Wrap behaves as SciPy’s grid-wrap, the exactly periodic extension.
  • Footprints may have even sides; the origin is then one element past the middle, as in SciPy, so the window extends one pixel further before the pixel than after it.
  • Spline orders 0 to 5 are supported. shift, zoom and rotate are thin wrappers around affine_transform.

In practice

Every function is compared with scipy.ndimage on a test image, for every boundary mode and spline order (see the chapter’s reference table). Rank filters are identical; Gaussian filters and interpolation agree to , except quintic splines in Nearest mode, which agree to (both pad the image by 12 pixels before prefiltering, and the poles of order 5 are not quite damped over that distance).

Strengths

  • The median removes impulse noise and keeps edges; percentiles and extremes give robust local statistics.
  • Gaussian derivative filters give stable derivatives at an explicit scale, the basis of edge, corner and blob detectors.
  • Cubic spline interpolation is nearly lossless for smooth images and costs little more than bilinear interpolation, thanks to the recursive prefilter.

Weaknesses

  • Rank filters cost per pixel; large windows need faster sliding-histogram methods, not implemented here.
  • The median rounds corners and removes thin lines narrower than half the window.
  • High-order splines ring at sharp edges; for label images or masks use order 0.
  • Repeated geometric transforms accumulate interpolation error; compose the maps and resample once.

Exercises

  1. Show that a median leaves a straight step edge (in any direction through pixel centres) unchanged, but rounds the corner of a square. Which pixels change?
  2. Show that the second-derivative kernel applied to gives in the continuous case, and compute what the sampled kernel with gives.
  3. Derive the cubic B-spline values , from , and find the pole of .
  4. Show that shifting by a whole number of pixels with any spline order (and Wrap mode) reproduces the image exactly, while shifting by half a pixel and back does not. Which order loses least?
  5. Implement rotation by composing three shears (Paeth’s method), each a one-dimensional shift of every row or column, and compare its error with rotate at order 3.
Hints and answers
  1. Along a straight edge every window has at least five pixels on the side of its centre (or exactly on the edge line), so the median is a value from that side. At a convex corner of a bright square the corner pixel’s window has only four bright pixels out of nine, so the median is dark: the corner pixel is removed and the corner rounded.
  2. The continuous second derivative of the Gaussian smoothing of is the smoothing of , which is 2. The sampled kernel gives (with normalised to sum 1), about for : half the value of the in the text, which was for .
  3. is the piecewise cubic for and for . The roots of are ; the stable pole is .
  4. At integer positions every spline evaluates to the coefficient-reconstructed sample exactly, since by construction. A half-pixel shift evaluates between samples, and shifting back evaluates the interpolant of the interpolant; higher orders lose less on smooth images.
  5. A rotation by equals shears with factors , , ; each shear is a one-dimensional interpolation per line, so it accumulates three interpolations but each is one-dimensional. Compare RMS errors on a smooth image.

Further reading

  • J. W. Tukey, Exploratory Data Analysis, Addison-Wesley, 1977 (running medians).
  • J. J. Koenderink, “The structure of images”, Biological Cybernetics 50 (1984) 363–370.
  • M. Unser, “Splines: a perfect fit for signal and image processing”, IEEE Signal Processing Magazine 16 (1999) 22–38.
  • M. Unser, A. Aldroubi and M. Eden, “B-spline signal processing: Part I—Theory” and “Part II—Efficient design and applications”, IEEE Transactions on Signal Processing 41 (1993) 821–848.