Image filtering: convolution, Gaussian blur, Sobel gradients and sharpening
| Problem | Replace each pixel by a weighted combination of its neighbours: to smooth noise, estimate the gradient, or emphasise detail |
| Devised by | Irwin Sobel and Gary Feldman (1968), the Sobel operator; Jan Koenderink (1984) and Andrew Witkin (1983), Gaussian scale space; unsharp masking from photographic darkrooms (1930s) |
| Accuracy | Exact (the library agrees with SciPy’s ndimage to the 12 digits compared; see the chapter overview) |
| Cost | per pixel for a kernel; when the kernel is separable, as the Gaussian and Sobel kernels are |
| Read first | Convolution and correlation |
| API | correlate2d, convolve2d, separable_convolve, Border, gaussian_kernel_1d, gaussian_blur, sobel, sharpening, sharpening_with_threshold |
Overview
An image is a two-dimensional signal. The library stores it as an Array2<f64> indexed (row, column), with rows increasing downwards. The most basic operation
slides a small kernel over the image and replaces each pixel by the kernel-weighted sum of its neighbourhood: a 2D convolution. The kernel decides what the filter does. A
Gaussian kernel smooths, suppressing noise and detail smaller than its width. The Sobel kernels estimate the two components of the intensity gradient, which is large at edges. Unsharp masking
subtracts a blurred copy to isolate the fine detail, then adds it back amplified, which makes edges look crisper. Near the image’s edge the kernel reaches past the
pixels that exist, so every filter needs a border rule.
Where it is used
Filtering is the first step of almost every image pipeline.
- Noise reduction. Gaussian blur smooths sensor noise before measuring anything.
- Edges and gradients. Sobel filters find the boundaries used in lane detection for driver assistance, in quality inspection of manufactured parts and as input to the Canny detector.
- Sharpening. Unsharp masking restores detail in photographs and microscope images.
- Convolutional neural networks. Their first layers learn filters like these.
History
Averaging neighbouring samples to reduce noise is as old as measurement. In digital image processing, Irwin Sobel and Gary Feldman presented their 3 × 3 gradient operator at the Stanford Artificial Intelligence Project in 1968. It became the standard edge filter, although the talk itself was never published. Andrew Witkin (1983) and Jan Koenderink (1984) showed that blurring by Gaussians of increasing width is the natural way to look at an image at several scales, the scale space underlying the blob and feature detectors of later entries. Unsharp masking began in darkrooms, where a slightly blurred negative was sandwiched with the original to boost edge contrast. It moved into digital imaging with the first scanners.
The idea
Convolution and border modes
Most image filters work the same way: each output pixel is a weighted sum of the input pixels in a small neighbourhood around it, and the same table of weights, the kernel, is used at every position. The kernel alone decides what the filter does. A kernel with every weight equal to replaces each pixel by the average of itself and its eight neighbours, a simple blur. A kernel with positive weights on one side and negative on the other responds to changes of intensity, and so finds edges. This is the two-dimensional version of an FIR filter.
In symbols, the library’s correlate2d computes
for a kernel of odd size centred on the output pixel. convolve2d flips the kernel first, , which is the true convolution. The two
differ only for asymmetric kernels. The output has the input’s size. Outside the image, Border supplies the missing pixels: Zero pads with zeros, which darkens the edges; Replicate repeats the edge pixel; Reflect mirrors the
image about its edge (c b a | a b c | c b a). These are SciPy’s constant, nearest and reflect modes.
Separable kernels
A kernel costs multiplications per pixel, which becomes expensive for wide
blurs. Many useful kernels have a structure that avoids this. A kernel that is an outer product,
, is called separable, and it can be applied in two one-dimensional
passes: a convolution along every row with , and then along every column with . The
two-dimensional sum factorises, because the weight of each pixel is a product of a row weight
and a column weight. That costs multiplications per pixel instead of . separable_convolve does this,
and the Gaussian and Sobel kernels are both separable. Blurring by σ = 1.2 and then 1.6 differs from one blur of σ = 2 by at most 1.0e-5 away from the borders. On a 256 × 256 image with σ = 3 (a 25-tap kernel), the separable blur took 2.7 ms and the full 25 × 25 kernel 59.4 ms, a factor of 22, with results equal to 2e-14.
Gaussian blur
The 2D Gaussian is the product of two 1D Gaussians. gaussian_kernel_1d samples it out to pixels and normalises the samples to
sum to one, so a constant image is unchanged. (SciPy truncates at instead. The two agree when the radii coincide, and differ by about when they do not, as for in the reference table.) The Gaussian is the only kernel that is both separable and rotationally symmetric, and Gaussians compose:
a blur of followed by equals one blur of , because variances add under convolution. Blurring suppresses detail finer than about pixels.
Gradients: the Sobel operator
The intensity gradient points across edges, and its magnitude measures their strength. The Sobel operator estimates it with
a central difference along one axis and a smoothing across it, which is less sensitive to noise than a plain difference. Applied by correlation, responds positively to intensity increasing to the right and to
intensity increasing downwards. The raw response is 8 times the gradient; sobel(image, true) divides by 8, so that a ramp gives exactly . It also returns the magnitude and the direction .
Figure 17.1. Filtering the test scene.
Differentiating amplifies noise, so gradients are normally taken after a Gaussian blur, as in the figure: the magnitude then outlines the disc and the square cleanly.
Unsharp masking
The difference between an image and its blur, , contains only the detail finer than . Adding a multiple of it back,
steepens edges and adds an overshoot on either side, which the eye reads as crispness. sharpening_with_threshold applies the boost only where exceeds a threshold, so flat, noisy regions are left alone:
Figure 17.2. Unsharp masking profile.
Algorithm
Correlation of an image with a kernel of size . For each output pixel :
- for each kernel entry , find the input pixel ; if it lies outside the image, replace it according to the border rule (zero, the nearest edge pixel, or the mirror image);
- add the kernel entry times that pixel to the sum.
Convolution is the same with the kernel rotated by 180° first. The cost is the number of pixels times the number of kernel entries.
Separable filtering with a row kernel and a column kernel :
- filter every row of the image with , into a temporary image;
- filter every column of the temporary image with .
Gaussian blur of width : sample the one-dimensional Gaussian at the integers from to ; divide by the sum of the samples; filter separably with that kernel along both axes.
Sobel gradient: correlate with and with , replicating the border; divide both by 8 if normalisation is requested; return the two components, the magnitude and the direction .
Unsharp mask: blur the image; compute the detail, image minus blur; at each pixel where
the magnitude of the detail exceeds the threshold, add amount times the detail to the image.
Implementation
let (hr, hc) = ((col_kernel.len() / 2) as isize, (row_kernel.len() / 2) as isize);
// Horizontal pass: convolution flips the kernel, so tap j pairs with offset (hc - j).
let horizontal = Array2::from_shape_fn((rows, cols), |(r, c)| {
row_kernel
.iter()
.enumerate()
.filter_map(|(j, k)| border_index(c as isize + hc - j as isize, cols, border).map(|cc| image[(r, cc)] * k))
.sum::<f64>()
});
Ok(Array2::from_shape_fn((rows, cols), |(r, c)| {
col_kernel
.iter()
.enumerate()
.filter_map(|(i, k)| border_index(r as isize + hr - i as isize, rows, border).map(|rr| horizontal[(rr, c)] * k))
.sum::<f64>()
}))
let kx = array![[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]];
let ky = array![[-1.0, -2.0, -1.0], [0.0, 0.0, 0.0], [1.0, 2.0, 1.0]];
let mut gx = correlate2d(image, &kx, Border::Replicate)?;
let mut gy = correlate2d(image, &ky, Border::Replicate)?;
if normalize {
gx.mapv_inplace(|v| v / 8.0);
gy.mapv_inplace(|v| v / 8.0);
}
let magnitude = Array2::from_shape_fn(gx.dim(), |i| gx[i].hypot(gy[i]));
let direction = Array2::from_shape_fn(gx.dim(), |i| gy[i].atan2(gx[i]));
let blurred = gaussian_blur(image, sigma)?;
Ok(Array2::from_shape_fn(image.dim(), |i| {
let detail = image[i] - blurred[i];
if detail.abs() >= threshold { image[i] + amount * detail } else { image[i] }
}))
- Kernels must have odd dimensions, so that they have a centre.
- The direct sum suits small kernels. For large ones,
fft_convolve_2dconvolves by FFT (with zero borders). gaussian_blurreplicates borders;gaussian_blur_with_bordertakes any mode.
In practice
//! Image filtering: 2D convolution with border modes, Gaussian blur, Sobel gradients and unsharp masking.
use lib_jsl_dsp::discrete::image::convolution::{Border, convolve2d};
use lib_jsl_dsp::discrete::image::filters::gaussian_blur::gaussian_blur;
use lib_jsl_dsp::discrete::image::filters::sharpening::sharpening;
use lib_jsl_dsp::discrete::image::filters::sobel::sobel;
use ndarray::Array2;
fn main() {
// A vertical step edge: dark on the left, bright on the right.
let step = Array2::from_shape_fn((9, 9), |(_, c)| if c < 4 { 0.2 } else { 0.8 });
let box3 = Array2::from_elem((3, 3), 1.0 / 9.0);
for border in [Border::Zero, Border::Replicate, Border::Reflect] {
let out = convolve2d(&step, &box3, border).unwrap();
println!("3x3 mean, {border:?}: corner {:.3}, centre row {:.3?}", out[(0, 0)], out.row(4).to_vec());
}
let blurred = gaussian_blur(&step, 1.0).unwrap();
println!("Gaussian σ = 1 across the edge: {:.3?}", blurred.row(4).to_vec());
let g = sobel(&step, true).unwrap();
println!("Sobel gx across the edge: {:.2?} (gy {:.2})", g.gx.row(4).to_vec(), g.gy[(4, 4)]);
let sharp = sharpening(&blurred, 1.0, 1.0).unwrap();
println!("unsharp mask of the blur: {:.3?}", sharp.row(4).to_vec());
let ramp = Array2::from_shape_fn((5, 5), |(r, c)| 2.0 * c as f64 + 3.0 * r as f64);
let g = sobel(&ramp, true).unwrap();
println!("Sobel of 2x + 3y at the centre: gx {} gy {}, direction {:.4} rad", g.gx[(2, 2)], g.gy[(2, 2)], g.direction[(2, 2)]);
}
3x3 mean, Zero: corner 0.089, centre row [0.133, 0.200, 0.200, 0.400, 0.600, 0.800, 0.800, 0.800, 0.533]
3x3 mean, Replicate: corner 0.200, centre row [0.200, 0.200, 0.200, 0.400, 0.600, 0.800, 0.800, 0.800, 0.800]
3x3 mean, Reflect: corner 0.200, centre row [0.200, 0.200, 0.200, 0.400, 0.600, 0.800, 0.800, 0.800, 0.800]
Gaussian σ = 1 across the edge: [0.200, 0.203, 0.235, 0.380, 0.620, 0.765, 0.797, 0.800, 0.800]
Sobel gx across the edge: [0.00, 0.00, 0.00, 0.30, 0.30, 0.00, 0.00, 0.00, 0.00] (gy 0.00)
unsharp mask of the blur: [0.197, 0.184, 0.187, 0.345, 0.655, 0.813, 0.816, 0.803, 0.800]
Sobel of 2x + 3y at the centre: gx 2 gy 3, direction 0.9828 rad
Zero padding darkens the borders; the other two modes keep a constant region constant. The step of 0.6 between columns 3 and 4 gives a normalised Sobel response of 0.3 at both, since the central difference spans two pixels.
Strengths
- Simple, exact and predictable; separable kernels make large Gaussian blurs cheap.
- Gaussian blurs compose and commute with differentiation, which is the basis of scale-space methods.
Weaknesses
- Linear smoothing blurs edges as much as noise (the Wiener filter adapts instead).
- Every border rule invents data; results within a kernel radius of the edge depend on it.
Exercises
- Show that convolution with an outer-product kernel equals row filtering with followed by column filtering with .
- Prove that the convolution of Gaussians of variances and is a Gaussian of variance .
- Show that the normalised Sobel operator is exact for linear ramps, and find its error for .
- Find the frequency response of the 3 × 3 Sobel and compare it with the ideal differentiator .
- Find the impulse response and frequency response of unsharp masking, and show that it is a high-frequency boost.
Hints and answers
- : summing over first (rows, with ) and then over (columns, with ) gives the same result.
- In the Fourier domain a Gaussian of variance has transform , and the product of two such is .
- The normalised Sobel with for the central difference is exact for ; for the central difference over spacing 2 gives , which is exact, and the smoothing in does not change it, so the error vanishes for as well; the first error appears for .
- The response is ; at low frequency this is , the ideal differentiator, and it falls below it as approaches .
- Unsharp masking has frequency response , which is at DC and rises towards at high frequencies: a high-frequency boost.
Further reading
- R. C. Gonzalez and R. E. Woods, Digital Image Processing, 4th ed., Pearson, 2018, chapter 3.
- I. Sobel, “An isotropic 3 × 3 image gradient operator”, 1968 talk, written up in 2014 (Stanford AI Project); see also R. Duda and P. Hart, Pattern Classification and Scene Analysis, Wiley, 1973, p. 271.
- J. J. Koenderink, “The structure of images”, Biological Cybernetics 50 (1984) 363–370.
- T. Lindeberg, Scale-Space Theory in Computer Vision, Kluwer, 1994.