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

Contrast and restoration: histogram equalisation and Wiener filtering

ProblemSpread an image’s gray levels over the full range; remove noise without blurring edges; undo a known blur
Devised byNorbert Wiener (1942, published 1949), the minimum-mean-square-error filter; Ernest Hall (1974) and others, histogram equalisation; Jong-Sen Lee (1980), the locally adaptive Wiener filter
AccuracyEqualisation maps levels exactly through the cumulative histogram; the adaptive Wiener filter agrees with SciPy’s signal.wiener to 12 digits away from the borders
Cost for equalisation and for the adaptive Wiener filter (box sums); for Wiener deconvolution by FFT, for pixels
Read firstImage filtering: convolution, Gaussian blur, Sobel gradients and sharpening
APIhistogram, equalization_lut, histogram_equalization, wiener_filter, wiener_deconvolution

Overview

A photograph taken in poor light uses only a narrow band of the available gray levels, so it looks flat. Histogram equalisation remaps the levels through the image’s own cumulative distribution, spreading them evenly over the full range. A noisy image needs smoothing, but a fixed blur softens edges as much as noise. The adaptive Wiener filter smooths strongly only where the neighbourhood looks like pure noise, and leaves edges and texture alone. A blurred image, if the blur is known, can be partly un-blurred. Dividing by the blur’s transfer function amplifies noise without limit, so Wiener deconvolution divides only where the signal dominates the noise.

Where it is used

Restoration tries to recover what the camera or sensor lost.

  • Contrast enhancement. Histogram equalisation brings out detail in X-rays, satellite images and dark photographs.
  • Deblurring. Wiener filtering restores images blurred by camera motion, defocus or a telescope’s point spread function, as in astronomy and microscopy.
  • Denoising. Reducing noise in low-light or medical images without destroying edges.

History

Norbert Wiener derived the optimal linear filter for separating a signal from noise during the Second World War, for anti-aircraft fire control. The report circulated in 1942, classified, and was published in 1949. Its two-dimensional, frequency-domain form, analysed for images by Carl Helstrom (1967), became the standard method for restoring images whose blur could be measured. Histogram equalisation appeared in the early 1970s in work on image enhancement (Ernest Hall and colleagues, 1971–74). Contrast-limited adaptive variants (CLAHE) followed in the 1980s for medical imaging. Jong-Sen Lee (1980) introduced the locally adaptive filter, which estimates the signal statistics in a small window around each pixel. MATLAB’s wiener2 and SciPy’s signal.wiener implement it.

The idea

Histogram equalisation

If a continuous random variable has cumulative distribution , then is uniform on . Mapping each gray level through the image’s cumulative histogram therefore flattens its histogram. For 8-bit images, with the number of pixels at or below level , the first nonzero value, and pixels,

which sends the darkest level present to 0 and the brightest to 255. The map is monotonic, so it preserves the order of brightness. With discrete levels the result is only approximately uniform: each input level maps to one output level, so the histogram’s bars are moved apart, not split.

Figure 17.3. Histogram equalisation.

Figure 17.4. Cumulative histograms.

The equalised cumulative histogram follows the diagonal in steps. Equalisation stretches the noise as much as the signal: the dense band of background levels is spread widest.

The adaptive Wiener filter

Model each pixel as , with signal of local mean and variance , and white noise of variance . The linear estimate of with the smallest mean-square error is

wiener_filter estimates and the total variance over a window around each pixel, by box filtering and . The result is . In a flat region and the pixel is replaced by the local mean; at an edge and it is left almost unchanged. If the noise variance is not given, it is estimated as the mean of all the local variances.

Figure 17.5. Denoising.

method (noise σ = 0.08)PSNR (dB)
noisy21.8
Gaussian blur, σ = 0.727.9
Gaussian blur, σ = 128.4
Gaussian blur, σ = 1.527.6
adaptive Wiener, 3 × 3, noise variance given28.8
adaptive Wiener, 5 × 5, noise variance given30.4
adaptive Wiener, 7 × 7, noise variance given30.4
adaptive Wiener, 5 × 5, noise variance estimated31.7

The adaptive filter beats the best fixed blur by 2–3 dB, keeping the edges sharp. Estimating the noise variance did better than supplying the true value here. The mean local variance includes the edges, so it overestimates and smooths the flat regions harder, which suits this mostly flat image.

Wiener deconvolution

A blurred, noisy image is , or in the frequency domain. Dividing by , the inverse filter, restores where there is no noise, but is tiny at high frequencies and explodes. The MMSE linear filter is

with the ratio of noise power to signal power, here taken as a constant. Where , it is the inverse filter; where , the gain falls to zero instead of growing. wiener_deconvolution pads the image to power-of-two dimensions by repeating its edge pixels, centres the PSF at the origin, and applies the filter by FFT.

Figure 17.6. Deconvolution.

Wiener deconvolution (Gaussian blur σ = 2, noise σ = 0.002)PSNR (dB)
blurred and noisy (no restoration)29.2
K = 0 (inverse filter)-143.2
K = 1e-611.1
K = 1e-520.8
K = 1e-429.0
K = 1e-332.1
K = 1e-231.6

The inverse filter turns noise of standard deviation 0.002 into numbers of order . Small restores too aggressively and large too timidly; the best value gains 3 dB over the blurred image here. Real blurs are not exactly known, nor circular as in this test, so in practice is tuned by eye.

Algorithm

Histogram equalisation of an 8-bit image.

  1. Count the pixels at each of the 256 levels.
  2. Form the cumulative counts .
  3. Build a lookup table of 256 entries from the formula above.
  4. Replace each pixel by the table entry for its level.

The cost is one pass to count and one to map.

Adaptive Wiener filter with a window.

  1. Box-filter the image and the squared image (reflecting at the borders) to obtain, at each pixel, the local mean and the local mean square, and from them the local variance .
  2. If the noise variance was not supplied, estimate it as the average of the local variances over the whole image.
  3. At each pixel, output if , and otherwise.

Wiener deconvolution with a known point spread function (PSF) and a constant .

  1. Pad the image to power-of-two dimensions by repeating its edge pixels.
  2. Place the PSF in an array of the same size, shifted cyclically so that its centre is at index ; otherwise the result would be displaced.
  3. Take the two-dimensional FFT of both, giving and .
  4. Multiply by at every frequency.
  5. Take the inverse FFT, and crop to the original size.

Implementation

    let cdf_min = cdf.iter().copied().find(|&c| c > 0).unwrap_or(0);
    let mut lut = [0u8; 256];
    if total == cdf_min {
        // Only one gray level is present: nothing to equalize.
        for (i, l) in lut.iter_mut().enumerate() {
            *l = i as u8;
        }
        return lut;
    }
    for i in 0..256 {
        let scaled = (cdf[i].saturating_sub(cdf_min)) as f64 / (total - cdf_min) as f64;
        lut[i] = (255.0 * scaled).round().clamp(0.0, 255.0) as u8;
    }
    let box_kernel = vec![1.0 / window as f64; window];
    let mean = separable_convolve(image, &box_kernel, &box_kernel, Border::Reflect)?;
    let squares = image.mapv(|v| v * v);
    let mean_sq = separable_convolve(&squares, &box_kernel, &box_kernel, Border::Reflect)?;
    let variance = Array2::from_shape_fn(image.dim(), |i| (mean_sq[i] - mean[i] * mean[i]).max(0.0));
    let noise = noise_variance.unwrap_or_else(|| variance.sum() / variance.len() as f64);
    Ok(Array2::from_shape_fn(image.dim(), |i| {
        if variance[i] >= noise && variance[i] > 0.0 {
            mean[i] + (variance[i] - noise) / variance[i] * (image[i] - mean[i])
        } else {
            mean[i]
        }
    }))
    let g = fft2d(&padded, false)?;
    let hf = fft2d(&h, false)?;
    let restored_f = Array2::from_shape_fn((n_rows, n_cols), |i| {
        let denom = hf[i].norm_sqr() + noise_to_signal;
        if denom < 1e-24 { Complex::new(0.0, 0.0) } else { hf[i].conj() / denom * g[i] }
    });
    let restored = fft2d(&restored_f, true)?;
  • Equalisation works on Array2<u8>; the filters work on Array2<f64>.
  • wiener_filter reflects at the borders, where SciPy pads with zeros; the two agree away from the edges.
  • wiener_deconvolution does not normalise the PSF: a PSF summing to one preserves the image’s mean.

In practice

//! Histogram equalisation, adaptive Wiener denoising and Wiener deconvolution.

use lib_jsl_dsp::discrete::image::convolution::gaussian_kernel_1d;
use lib_jsl_dsp::discrete::image::filters::gaussian_blur::gaussian_blur;
use lib_jsl_dsp::discrete::image::filters::histogram_equalization::{equalization_lut, histogram, histogram_equalization};
use lib_jsl_dsp::discrete::image::filters::wiener_filter::{wiener_deconvolution, wiener_filter};
use ndarray::Array2;

fn mse(a: &Array2<f64>, b: &Array2<f64>) -> f64 {
    a.iter().zip(b.iter()).map(|(x, y)| (x - y).powi(2)).sum::<f64>() / a.len() as f64
}

fn main() {
    // Four gray levels crowded into 100..=130.
    let dull = Array2::from_shape_fn((8, 8), |(r, c)| [100u8, 110, 120, 130][(r + c) % 4]);
    let lut = equalization_lut(&histogram(&dull));
    println!("equalised levels: 100 -> {}, 110 -> {}, 120 -> {}, 130 -> {}", lut[100], lut[110], lut[120], lut[130]);
    println!("equalised image row 0: {:?}", histogram_equalization(&dull).unwrap().row(0).to_vec());
    // A smooth image with deterministic "noise".
    let clean = Array2::from_shape_fn((64, 64), |(r, c)| if (16..48).contains(&r) && (16..48).contains(&c) { 0.8 } else { 0.2 });
    let noise = Array2::from_shape_fn((64, 64), |(r, c)| 0.05 * (((r * 31 + c * 17) % 13) as f64 / 6.0 - 1.0));
    let noisy = &clean + &noise;
    let variance = noise.iter().map(|v| v * v).sum::<f64>() / noise.len() as f64;
    println!("MSE: noisy {:.2e}, Wiener 5x5 {:.2e}", mse(&noisy, &clean), mse(&wiener_filter(&noisy, 5, Some(variance)).unwrap(), &clean));
    // Deconvolve a known Gaussian blur.
    let k = gaussian_kernel_1d(1.5, 4.0).unwrap();
    let psf = Array2::from_shape_fn((k.len(), k.len()), |(i, j)| k[i] * k[j]);
    let blurred = gaussian_blur(&clean, 1.5).unwrap();
    for nsr in [1e-1, 1e-2, 1e-3] {
        println!("deconvolution with K = {nsr:.0e}: MSE {:.2e} (blurred {:.2e})", mse(&wiener_deconvolution(&blurred, &psf, nsr).unwrap(), &clean), mse(&blurred, &clean));
    }
}
equalised levels: 100 -> 0, 110 -> 85, 120 -> 170, 130 -> 255
equalised image row 0: [0, 85, 170, 255, 0, 85, 170, 255]
MSE: noisy 9.72e-4, Wiener 5x5 1.26e-4
deconvolution with K = 1e-1: MSE 4.47e-3 (blurred 3.62e-3)
deconvolution with K = 1e-2: MSE 1.88e-3 (blurred 3.62e-3)
deconvolution with K = 1e-3: MSE 1.35e-3 (blurred 3.62e-3)

Four equally common levels become four evenly spaced ones. The example’s deconvolution starts from a blur that was not circular, so the restoration is limited by the border mismatch as well as by .

Strengths

  • Equalisation needs no parameters and preserves the order of brightness.
  • The adaptive Wiener filter preserves edges and needs only the window size; deconvolution has one parameter.

Weaknesses

  • Equalisation is global: it can over-enhance noise and wash out small regions (adaptive, contrast-limited versions address this).
  • The Wiener filters assume additive white noise and, for deconvolution, a known, shift-invariant blur.

Exercises

  1. Show that if has a continuous cumulative distribution , then is uniform on .
  2. Derive the scalar MMSE estimate .
  3. Derive the Wiener deconvolution filter by minimising at each frequency.
  4. Show that the Fourier transform of a Gaussian blur of width is a Gaussian of width , and explain why the inverse filter fails for it.
  5. Implement contrast-limited equalisation: clip the histogram at a multiple of its mean before forming the cumulative sum.
Hints and answers
  1. for continuous strictly increasing .
  2. For with and , the conditional mean is .
  3. Minimising with at each frequency gives .
  4. , a Gaussian of width in (i.e. in cycles). The inverse filter divides by it, amplifying high-frequency noise by without bound.
  5. Clip each histogram bin at (a multiple of) the mean count, redistribute the clipped excess evenly across all bins, then form the cumulative sum; this limits the slope of the mapping and so limits noise amplification.

Further reading

  • R. C. Gonzalez and R. E. Woods, Digital Image Processing, 4th ed., Pearson, 2018, chapters 3 and 5.
  • N. Wiener, Extrapolation, Interpolation, and Smoothing of Stationary Time Series, MIT Press, 1949.
  • J.-S. Lee, “Digital image enhancement and noise filtering by use of local statistics”, IEEE Transactions on Pattern Analysis and Machine Intelligence 2 (1980) 165–168.
  • C. W. Helstrom, “Image restoration by the method of least squares”, Journal of the Optical Society of America 57 (1967) 297–303.
  • J. S. Lim, Two-Dimensional Signal and Image Processing, Prentice Hall, 1990, chapter 9.