Morphology, distance transforms and labelling
| Problem | Clean up binary and greyscale images by shape; measure how far each pixel is from the background; find, count and measure the separate objects in a binary image |
| Devised by | Mathematical morphology: Georges Matheron and Jean Serra (1964 onwards, École des Mines); distance transforms: Azriel Rosenfeld and John Pfaltz (1966); the linear-time exact Euclidean transform: Pedro Felzenszwalb and Daniel Huttenlocher (2004, 2012); two-pass labelling: Rosenfeld and Pfaltz (1966) |
| Accuracy | Exact: every result is identical to scipy.ndimage, apart from rounding (below ) in distances and intensity measurements |
| Cost | Morphology and rank operations: for pixels and a -pixel structuring element; exact Euclidean distance transform and labelling: |
| Read first | Segmentation: Otsu’s threshold, Canny edges and the watershed |
| API | binary_erosion, binary_dilation, binary_opening, binary_closing, binary_fill_holes, grey_erosion, grey_dilation, white_tophat, morphological_gradient, distance_transform_edt, distance_transform_cdt, label, regions, Mode |
Overview
After a threshold or an edge detector has turned an image into foreground and background, the result is rarely clean: there are specks of noise, pinholes inside objects, ragged outlines, and objects that touch. Mathematical morphology repairs such images by probing them with a small shape, the structuring element. Two operations underlie everything else. Erosion keeps a pixel only if the element, centred there, fits entirely inside the foreground; it shrinks objects and deletes those smaller than the element. Dilation turns a pixel on if the element touches the foreground; it grows objects and fills small gaps. Erosion followed by dilation (opening) removes small objects but restores the large ones almost exactly; dilation followed by erosion (closing) fills small holes and gaps. On greyscale images the same ideas become a minimum and a maximum over the element.
Two further tools turn a clean binary image into numbers. The distance transform gives each foreground pixel its distance to the nearest background pixel, a map of how deep inside its object every pixel lies. Labelling gives each connected group of foreground pixels its own number, so that objects can be counted and measured one by one: their area, centroid, bounding box and intensity statistics.
Where it is used
Morphological operations clean up and measure binary and grey images by shape.
- Cleaning segmentation masks. Opening and closing remove specks and fill holes before measurements.
- Counting and measuring objects. Labelling connected components counts cells under a microscope, particles in a micrograph or defects on a part, and reports their areas.
- Distance transforms. How far each pixel is from the boundary guides robot path planning, skeleton extraction and watershed segmentation.
- Document and fingerprint processing. Thinning and cleaning of line patterns.
History
Mathematical morphology was created by Georges Matheron and Jean Serra at the École des Mines de Paris from 1964, to quantify the structure of porous rocks and mineral grains seen in thin sections under the microscope. Matheron’s Random Sets and Integral Geometry (1975) and Serra’s Image Analysis and Mathematical Morphology (1982) set out the theory; the greyscale form and its use in industrial inspection followed through the 1980s.
Azriel Rosenfeld and John Pfaltz (1966) introduced both the two-pass sequential algorithm for labelling connected components and the chamfer distance transforms computed by two raster sweeps. Exact Euclidean distance transforms took longer: early methods propagated vectors and could be wrong in rare configurations, until linear-time exact algorithms appeared around 2000. The one used here, by Pedro Felzenszwalb and Daniel Huttenlocher (published 2004, journal version 2012), reduces the problem to one dimension and solves each line as the lower envelope of parabolas.
The idea
Erosion and dilation
Let be the set of foreground pixels and the structuring element, a set of offsets around the origin, such as the cross (the four edge neighbours and the centre) or the square. Translating to a pixel gives . Then
where is the reflected element (the same as for the symmetric elements used here). Erosion asks “does the element fit?” and dilation “does it touch?”. Pixels beyond the image count as background, so objects touching the image edge are eroded from it.
Two properties give the operations their meaning. Both are increasing: if then , so they never create features that were not there. And they are dual: dilating the foreground is eroding the background, , so every statement about one has a mirror image about the other.
Opening and closing
Erosion followed by dilation, , is the opening. It is the union of all translates of that fit inside : every part of that the element can reach while staying inside survives, and only the parts too narrow for it (specks, thin spurs, small protrusions) disappear. The closing, , is the dual: it fills everything the element cannot fit into from outside, such as pinholes, narrow gaps and small bays. Both are idempotent: opening an opened image changes nothing, which is why they are the standard tools for cleaning.
Figure 17.14. Cleaning a noisy binary image.
The scene has five objects; 1.2% of its pixels have been flipped. Opening with the cross removes every isolated speck but leaves pinholes; closing then fills the pinholes; the remaining holes, too large for the element, are removed by hole filling: a background region is a hole if it cannot be reached from outside the image by steps allowed by the structuring element. A breadth-first search from the background pixels on the border marks everything reachable; the rest is foreground.
Greyscale morphology
On a greyscale image, “the element fits” becomes a minimum and “the element touches” a maximum:
A greyscale opening removes bright features narrower than the element while keeping the background level; the white
top-hat, , keeps exactly those bright features, which makes it a good way to find small spots on an uneven
background. The black top-hat, , finds small dark features, and the morphological gradient,
, is large on edges and zero in flat regions. Beyond the image, greyscale operations use the boundary
modes of scipy.ndimage (Mode), Reflect by default.
Distance transforms
For each foreground pixel , the distance transform gives , the distance to the nearest background pixel. With the city-block or chessboard distance it can be computed by two raster sweeps: going forwards, each pixel takes one more than the smallest value among its already visited neighbours (above and to the left); going backwards, the same with the other neighbours. These are the chamfer transforms.
The Euclidean distance needs more care, because the nearest background pixel is not always reached through a neighbour’s nearest one. The squared distance separates:
The inner minimum is a one-dimensional problem down each column, giving ; the outer one is a one-dimensional problem along each row, . Each candidate contributes a parabola , and the answer is their lower envelope. Because all the parabolas have the same shape, any two cross exactly once, so the envelope is built left to right in linear time, discarding parabolas that a newer one undercuts before they ever become lowest. Recording which parabola wins gives the feature transform, the position of the nearest background pixel, as a by-product.
Figure 17.15. Distance transform and labels.
The distance is largest at the centres of the thick objects, and its maximum in each object is the radius of the largest disc that fits inside it. The ridges of the distance map form the object’s skeleton.
Labelling
Two foreground pixels are connected if a chain of foreground pixels links them, each step allowed by the structuring element: the cross allows only edge neighbours (4-connectivity), the square also diagonals (8-connectivity). The connected components are found in two raster passes. The first gives each pixel the label of an already visited neighbour (above or to the left) or a new provisional label if it has none; when two different labels meet at a pixel, their equivalence is recorded in a union-find structure. The second pass replaces each label by its representative, numbered in the order the objects are first met. With path compression, the union-find operations cost effectively constant time, so the whole is .
Table 17.4. Connected components of the scene before and after cleaning.
| image | components (4-connected) | components (8-connected) |
|---|---|---|
| clean image | 5 | 5 |
| noisy image | 141 | 138 |
| after opening | 5 | 5 |
| after opening and closing | 5 | 5 |
| cores: distance > 6 | 3 | 3 |
Noise turns five objects into well over a hundred components; opening alone already restores the count. The two touching discs are one object to any connectivity rule. Thresholding the distance transform splits them (the “cores” row): their two centres are deep, the neck between them is not. But the thin objects disappear at the same threshold, which is why touching objects are usually separated with the watershed of the distance transform rather than by a single threshold.
Once labelled, each region can be measured in one pass over the image:
Table 17.5. Measurements of the labelled regions of the cleaned scene.
| label | area (pixels) | centroid (row, column) | bounding box | largest inscribed radius |
|---|---|---|---|---|
| 1 | 564 | (25.0, 25.0) | rows 11–39, columns 11–39 | 5.4 |
| 2 | 473 | (28.0, 80.0) | rows 12–44, columns 64–96 | 3.2 |
| 3 | 1193 | (77.5, 28.5) | rows 60–95, columns 12–45 | 9.9 |
| 4 | 289 | (67.5, 85.0) | rows 65–70, columns 60–110 | 3.0 |
| 5 | 630 | (95.0, 84.4) | rows 85–105, columns 65–104 | 10.0 |
Algorithm
Binary erosion and dilation with element offsets : for each pixel, test all offsets (erosion: all on; dilation: any on, with the offsets reflected), treating pixels beyond the image as background; repeat for several iterations, or until the image stops changing.
Hole filling: mark every background pixel that has a step (an element offset) leading out of the image; breadth-first search through background pixels by element steps; invert the marked set.
Greyscale erosion and dilation: the minimum (maximum) of the image, extended by the boundary mode, over the footprint (reflected, for dilation). Opening, closing, top-hats and the gradient are compositions and differences of these.
Exact Euclidean distance transform, with pixel spacing :
- For each column, set on background and on foreground, and compute the one-dimensional squared distance transform , remembering the minimising row.
- For each row, compute the same transform of with spacing , remembering the minimising column.
- The distance is the square root; the feature transform combines the two remembered indices.
The one-dimensional transform maintains the envelope as a stack of parabola positions and boundaries . For each new finite , compute where its parabola meets the top one, ; pop while is left of the top’s boundary; push with boundary . Then read off, for each position, the parabola whose interval contains it.
Labelling: as described above, with union-find (path halving, union by smaller label) over provisional labels, then renumbering in raster order of first appearance.
Implementation
Binary erosion and dilation:
/// Binary erosion: a pixel stays on only if every element of `structure`, centred on it, lies on
/// the foreground. Pixels beyond the image count as background, so objects touching the edge are
/// eroded from it (SciPy's `binary_erosion` with `border_value=0`). `iterations` repeats the
/// operation; `0` repeats until the image stops changing.
pub fn binary_erosion(image: &Array2<bool>, structure: &Array2<bool>, iterations: usize) -> Result<Array2<bool>, ErrorsJSL> {
repeat(image, structure, iterations, true)
}
/// Binary dilation: a pixel turns on if the reflected `structure`, centred on it, touches the
/// foreground (SciPy's `binary_dilation`).
pub fn binary_dilation(image: &Array2<bool>, structure: &Array2<bool>, iterations: usize) -> Result<Array2<bool>, ErrorsJSL> {
repeat(image, structure, iterations, false)
}
The lower envelope of parabolas:
/// The one-dimensional squared distance transform of `f` with sample spacing `h`:
/// `d[q] = min_p ((q − p)² h² + f[p])`, and the minimising `p`. Each `p` contributes the parabola
/// `(q − p)² h² + f[p]`; the lower envelope of the parabolas is built left to right, discarding any
/// parabola that the newest one undercuts before the previous one takes over.
fn envelope(f: &[f64], h: f64) -> (Vec<f64>, Vec<usize>) {
let n = f.len();
let h2 = h * h;
let mut v = vec![0usize; n]; // positions of the parabolas in the envelope
let mut z = vec![0.0f64; n + 1]; // boundaries between them
let mut k = 0usize;
let finite: Vec<usize> = (0..n).filter(|&p| f[p].is_finite()).collect();
if finite.is_empty() {
return (vec![f64::INFINITY; n], vec![usize::MAX; n]);
}
v[0] = finite[0];
z[0] = f64::NEG_INFINITY;
z[1] = f64::INFINITY;
for &q in &finite[1..] {
loop {
let p = v[k];
// Where the parabolas from p and q intersect.
let s = ((f[q] + h2 * (q * q) as f64) - (f[p] + h2 * (p * p) as f64)) / (2.0 * h2 * (q as f64 - p as f64));
if s <= z[k] {
if k == 0 {
v[0] = q;
z[1] = f64::INFINITY;
break;
}
k -= 1;
} else {
k += 1;
v[k] = q;
z[k] = s;
z[k + 1] = f64::INFINITY;
break;
}
}
}
let mut d = vec![0.0; n];
let mut idx = vec![0usize; n];
let mut k = 0;
for q in 0..n {
while z[k + 1] < q as f64 {
k += 1;
}
let p = v[k];
d[q] = h2 * ((q as f64 - p as f64).powi(2)) + f[p];
idx[q] = p;
}
(d, idx)
}
Labelling:
/// Labels the connected components of a binary image (SciPy's `label`). Returns the label image
/// (0 for background, `1..=n` for the components, numbered in the raster order of their first
/// pixel) and the number of components `n`. `structure` must be symmetric with odd dimensions;
/// [`cross`](super::morphology::cross) gives 4-connectivity and
/// [`square`](super::morphology::square)`(3)` 8-connectivity.
pub fn label(mask: &Array2<bool>, structure: &Array2<bool>) -> Result<(Array2<usize>, usize), ErrorsJSL> {
let (h, w) = structure.dim();
if h % 2 == 0 || w % 2 == 0 {
return Err(ErrorsJSL::InvalidInputRange("the structure must have odd dimensions"));
}
let (ch, cw) = ((h / 2) as isize, (w / 2) as isize);
// Neighbours already visited in a raster scan: earlier rows, or earlier columns of this row.
let earlier: Vec<(isize, isize)> = structure
.indexed_iter()
.filter(|(_, b)| **b)
.map(|((i, j), _)| (i as isize - ch, j as isize - cw))
.filter(|&(di, dj)| di < 0 || (di == 0 && dj < 0))
.collect();
let (rows, cols) = mask.dim();
let mut labels = Array2::<usize>::zeros((rows, cols));
let mut parent = vec![0usize];
for r in 0..rows {
for c in 0..cols {
if !mask[(r, c)] {
continue;
}
let mut current = 0;
for &(di, dj) in &earlier {
let (nr, nc) = (r as isize + di, c as isize + dj);
if nr < 0 || nc < 0 || nc >= cols as isize {
continue;
}
let l = labels[(nr as usize, nc as usize)];
if l == 0 {
continue;
}
if current == 0 {
current = l;
} else {
let (a, b) = (find(&mut parent, current), find(&mut parent, l));
if a != b {
let (lo, hi) = (a.min(b), a.max(b));
parent[hi] = lo;
}
}
}
if current == 0 {
current = parent.len();
parent.push(current);
}
labels[(r, c)] = current;
}
}
// Second pass: representatives, renumbered 1..n in order of first appearance.
let mut final_label = vec![0usize; parent.len()];
let mut n = 0;
for v in labels.iter_mut() {
if *v == 0 {
continue;
}
let root = find(&mut parent, *v);
if final_label[root] == 0 {
n += 1;
final_label[root] = n;
}
*v = final_label[root];
}
Ok((labels, n))
}
- Binary images are
Array2<bool>(trueis foreground); greyscale imagesArray2<f64>. Structuring elements areArray2<bool>with odd sides, centred:cross(),square(k),disk(r). iterations = 0repeats erosion or dilation until the image stops changing (SciPy’siterations < 1).- The distance transform returns both the distances and the nearest background pixel; it requires at least one background
pixel. Chamfer distances are integers,
Nonewhere no background exists. regionsreturns the area, bounding box (half-open, as SciPy’sfind_objects) and centroid of each label, and with an intensity image its sum, mean, minimum, maximum and intensity-weighted centre (SciPy’scenter_of_mass).
In practice
The comparison with scipy.ndimage covers every function on a test image, with both structuring elements and every boundary
mode; the results are identical, or agree to rounding error (see the chapter’s reference table).
Strengths
- Simple, exact and fast: binary operations are bit tests, distance transforms and labelling are linear in the number of pixels.
- Shape-based: opening and closing remove features by size and shape, not by intensity, so they keep sharp outlines.
- Labelling and region measurements turn a segmentation into a table of objects.
Weaknesses
- The structuring element must be chosen for the scale of the features; one size rarely suits every object.
- Morphology on a square grid is anisotropic: the cross and the square erode diagonals and edges differently; discs approximate isotropy only for larger radii.
- Touching objects form one component; separating them needs more (a watershed of the distance transform).
- The direct implementation costs per pixel for a -pixel element; large elements are faster by decomposition (a square is two lines), which is not implemented.
Exercises
- Show that opening is idempotent: . (Use .)
- Prove the duality , and deduce that closing the foreground is opening the background.
- A disc of radius is eroded by the square times. What shape and size remains? What does the cross leave?
- Compute the Euclidean distance transform of a single background pixel at the origin by hand for the neighbourhood, and check that the two one-dimensional passes reproduce .
- Label the image whose rows are
#.#,.#.,#.#with 4- and 8-connectivity. How many components does each find? Explain why the background of the 8-connected foreground should be taken as 4-connected (the digital topology paradox).
Hints and answers
- Every that fits in also fits in , and every one that fits in is contained in ; so the union of translates fitting in is the same union.
- iff for all , iff no is in , iff . Applying this to the complement: closing is the complement of the opening of (with the reflected element).
- Erosion by the square removes all pixels within chessboard distance of the background, so the disc shrinks to the set of pixels at chessboard distance more than from the outside: roughly an octagon-like shape of radius , flattened along the diagonals by about . The cross erodes by city-block distance, leaving a diamond-like shape flattened on the axes.
- The column pass gives in the column through the origin and elsewhere; the row pass gives .
- With 4-connectivity: five components (each
#alone). With 8-connectivity: one (all are diagonal neighbours of the centre). The paradox: with 8-connected foreground and 8-connected background, a diagonal line both separates and does not separate the background; using the complementary connectivity for the background restores the Jordan curve theorem.
Further reading
- J. Serra, Image Analysis and Mathematical Morphology, Academic Press, 1982.
- P. Soille, Morphological Image Analysis: Principles and Applications, 2nd ed., Springer, 2003.
- A. Rosenfeld and J. L. Pfaltz, “Sequential operations in digital picture processing”, Journal of the ACM 13 (1966) 471–494.
- P. F. Felzenszwalb and D. P. Huttenlocher, “Distance transforms of sampled functions”, Theory of Computing 8 (2012) 415–428.