Skip to main content

lib_jsl_dsp/discrete/image/
labelling.rs

1//! Connected-component labelling and per-region measurements, following `scipy.ndimage.label`,
2//! `find_objects`, `sum`, `mean`, `minimum`, `maximum` and `center_of_mass`.
3//!
4//! Labelling gives each connected group of foreground pixels its own number, so that objects can
5//! be counted and measured one by one. Two pixels are connected if a chain of foreground pixels
6//! links them, each step allowed by the structuring element (the cross for edge neighbours only,
7//! the 3 × 3 square to include diagonals). The classical two-pass algorithm assigns provisional
8//! labels in one raster scan, recording which of them touch in a union-find structure, and then
9//! replaces each by its representative.
10//!
11//! See the book entry [Morphology, distance transforms and labelling](https://jwkunz.github.io/lib_jsl/book/image/morphology.html).
12
13use lib_jsl_core::ErrorsJSL;
14use ndarray::Array2;
15
16fn find(parent: &mut [usize], mut x: usize) -> usize {
17    while parent[x] != x {
18        parent[x] = parent[parent[x]];
19        x = parent[x];
20    }
21    x
22}
23
24// ANCHOR: label
25/// Labels the connected components of a binary image (SciPy's `label`). Returns the label image
26/// (0 for background, `1..=n` for the components, numbered in the raster order of their first
27/// pixel) and the number of components `n`. `structure` must be symmetric with odd dimensions;
28/// [`cross`](super::morphology::cross) gives 4-connectivity and
29/// [`square`](super::morphology::square)`(3)` 8-connectivity.
30pub fn label(mask: &Array2<bool>, structure: &Array2<bool>) -> Result<(Array2<usize>, usize), ErrorsJSL> {
31    let (h, w) = structure.dim();
32    if h % 2 == 0 || w % 2 == 0 {
33        return Err(ErrorsJSL::InvalidInputRange("the structure must have odd dimensions"));
34    }
35    let (ch, cw) = ((h / 2) as isize, (w / 2) as isize);
36    // Neighbours already visited in a raster scan: earlier rows, or earlier columns of this row.
37    let earlier: Vec<(isize, isize)> = structure
38        .indexed_iter()
39        .filter(|(_, b)| **b)
40        .map(|((i, j), _)| (i as isize - ch, j as isize - cw))
41        .filter(|&(di, dj)| di < 0 || (di == 0 && dj < 0))
42        .collect();
43    let (rows, cols) = mask.dim();
44    let mut labels = Array2::<usize>::zeros((rows, cols));
45    let mut parent = vec![0usize];
46    for r in 0..rows {
47        for c in 0..cols {
48            if !mask[(r, c)] {
49                continue;
50            }
51            let mut current = 0;
52            for &(di, dj) in &earlier {
53                let (nr, nc) = (r as isize + di, c as isize + dj);
54                if nr < 0 || nc < 0 || nc >= cols as isize {
55                    continue;
56                }
57                let l = labels[(nr as usize, nc as usize)];
58                if l == 0 {
59                    continue;
60                }
61                if current == 0 {
62                    current = l;
63                } else {
64                    let (a, b) = (find(&mut parent, current), find(&mut parent, l));
65                    if a != b {
66                        let (lo, hi) = (a.min(b), a.max(b));
67                        parent[hi] = lo;
68                    }
69                }
70            }
71            if current == 0 {
72                current = parent.len();
73                parent.push(current);
74            }
75            labels[(r, c)] = current;
76        }
77    }
78    // Second pass: representatives, renumbered 1..n in order of first appearance.
79    let mut final_label = vec![0usize; parent.len()];
80    let mut n = 0;
81    for v in labels.iter_mut() {
82        if *v == 0 {
83            continue;
84        }
85        let root = find(&mut parent, *v);
86        if final_label[root] == 0 {
87            n += 1;
88            final_label[root] = n;
89        }
90        *v = final_label[root];
91    }
92    Ok((labels, n))
93}
94// ANCHOR_END: label
95
96/// The measurements of one labelled region.
97#[derive(Clone, Debug, PartialEq)]
98pub struct Region {
99    /// The label, `1..=n`.
100    pub label: usize,
101    /// The number of pixels.
102    pub area: usize,
103    /// The bounding box as half-open ranges: rows `top..bottom`, columns `left..right` (SciPy's
104    /// `find_objects` slices).
105    pub bbox: (usize, usize, usize, usize),
106    /// The mean `(row, column)` of the region's pixels.
107    pub centroid: (f64, f64),
108    /// With an intensity image: the sum, mean, minimum and maximum of its values over the region,
109    /// and the intensity-weighted centre (SciPy's `center_of_mass`).
110    pub sum: Option<f64>,
111    pub mean: Option<f64>,
112    pub minimum: Option<f64>,
113    pub maximum: Option<f64>,
114    pub center_of_mass: Option<(f64, f64)>,
115}
116
117// ANCHOR: regions
118/// Measures every region of a label image in one pass: area, bounding box and centroid, and with
119/// `values` the intensity sum, mean, extremes and weighted centre.
120pub fn regions(labels: &Array2<usize>, n: usize, values: Option<&Array2<f64>>) -> Result<Vec<Region>, ErrorsJSL> {
121    if let Some(v) = values
122        && v.dim() != labels.dim()
123    {
124        return Err(ErrorsJSL::IncompatibleArraySizes((v.len(), labels.len())));
125    }
126    let mut area = vec![0usize; n + 1];
127    let mut bbox = vec![(usize::MAX, 0usize, usize::MAX, 0usize); n + 1];
128    let mut sr = vec![0.0; n + 1];
129    let mut sc = vec![0.0; n + 1];
130    let mut sum = vec![0.0; n + 1];
131    let mut wr = vec![0.0; n + 1];
132    let mut wc = vec![0.0; n + 1];
133    let mut lo = vec![f64::INFINITY; n + 1];
134    let mut hi = vec![f64::NEG_INFINITY; n + 1];
135    for ((r, c), &l) in labels.indexed_iter() {
136        if l == 0 {
137            continue;
138        }
139        if l > n {
140            return Err(ErrorsJSL::InvalidInputRange("a label exceeds the number of regions"));
141        }
142        area[l] += 1;
143        let b = &mut bbox[l];
144        *b = (b.0.min(r), b.1.max(r + 1), b.2.min(c), b.3.max(c + 1));
145        sr[l] += r as f64;
146        sc[l] += c as f64;
147        if let Some(v) = values {
148            let x = v[(r, c)];
149            sum[l] += x;
150            wr[l] += x * r as f64;
151            wc[l] += x * c as f64;
152            lo[l] = lo[l].min(x);
153            hi[l] = hi[l].max(x);
154        }
155    }
156    Ok((1..=n)
157        .filter(|&l| area[l] > 0)
158        .map(|l| {
159            let a = area[l] as f64;
160            let with = values.is_some();
161            Region {
162                label: l,
163                area: area[l],
164                bbox: bbox[l],
165                centroid: (sr[l] / a, sc[l] / a),
166                sum: with.then_some(sum[l]),
167                mean: with.then_some(sum[l] / a),
168                minimum: with.then_some(lo[l]),
169                maximum: with.then_some(hi[l]),
170                center_of_mass: with.then_some((wr[l] / sum[l], wc[l] / sum[l])),
171            }
172        })
173        .collect())
174}
175// ANCHOR_END: regions
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180    use crate::discrete::image::morphology::{cross, square};
181
182    fn from_rows(rows: &[&str]) -> Array2<bool> {
183        Array2::from_shape_fn((rows.len(), rows[0].len()), |(i, j)| rows[i].as_bytes()[j] == b'#')
184    }
185
186    #[test]
187    fn diagonal_neighbours_connect_only_with_the_square() {
188        let img = from_rows(&["#..#", ".#.#", "..##", "#..."]);
189        let (_, n4) = label(&img, &cross()).unwrap();
190        let (_, n8) = label(&img, &square(3)).unwrap();
191        assert_eq!(n4, 4);
192        assert_eq!(n8, 2);
193    }
194
195    #[test]
196    fn a_u_shape_merges_two_provisional_labels() {
197        let img = from_rows(&["#.#", "#.#", "###"]);
198        let (labels, n) = label(&img, &cross()).unwrap();
199        assert_eq!(n, 1);
200        assert!(labels.iter().all(|&l| l <= 1));
201        let r = regions(&labels, n, Some(&labels.mapv(|l| l as f64 * 2.0))).unwrap();
202        assert_eq!(r[0].area, 7);
203        assert_eq!(r[0].bbox, (0, 3, 0, 3));
204        assert_eq!(r[0].sum, Some(14.0));
205    }
206}