Skip to main content

lib_jsl_dsp/discrete/image/
distance.rs

1//! Distance transforms: for every foreground pixel, the distance to the nearest background pixel.
2//!
3//! The exact Euclidean transform uses the separable algorithm of Felzenszwalb and Huttenlocher
4//! (2004): the squared distance in two dimensions is a one-dimensional problem along the rows of a
5//! one-dimensional answer along the columns, and each one-dimensional problem is the lower envelope
6//! of parabolas, found in linear time. The chamfer transforms (city-block and chessboard) need only
7//! two raster sweeps.
8//!
9//! See the book entry [Morphology, distance transforms and labelling](https://jwkunz.github.io/lib_jsl/book/image/morphology.html).
10
11use lib_jsl_core::ErrorsJSL;
12use ndarray::Array2;
13
14// ANCHOR: envelope
15/// The one-dimensional squared distance transform of `f` with sample spacing `h`:
16/// `d[q] = min_p ((q − p)² h² + f[p])`, and the minimising `p`. Each `p` contributes the parabola
17/// `(q − p)² h² + f[p]`; the lower envelope of the parabolas is built left to right, discarding any
18/// parabola that the newest one undercuts before the previous one takes over.
19fn envelope(f: &[f64], h: f64) -> (Vec<f64>, Vec<usize>) {
20    let n = f.len();
21    let h2 = h * h;
22    let mut v = vec![0usize; n]; // positions of the parabolas in the envelope
23    let mut z = vec![0.0f64; n + 1]; // boundaries between them
24    let mut k = 0usize;
25    let finite: Vec<usize> = (0..n).filter(|&p| f[p].is_finite()).collect();
26    if finite.is_empty() {
27        return (vec![f64::INFINITY; n], vec![usize::MAX; n]);
28    }
29    v[0] = finite[0];
30    z[0] = f64::NEG_INFINITY;
31    z[1] = f64::INFINITY;
32    for &q in &finite[1..] {
33        loop {
34            let p = v[k];
35            // Where the parabolas from p and q intersect.
36            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));
37            if s <= z[k] {
38                if k == 0 {
39                    v[0] = q;
40                    z[1] = f64::INFINITY;
41                    break;
42                }
43                k -= 1;
44            } else {
45                k += 1;
46                v[k] = q;
47                z[k] = s;
48                z[k + 1] = f64::INFINITY;
49                break;
50            }
51        }
52    }
53    let mut d = vec![0.0; n];
54    let mut idx = vec![0usize; n];
55    let mut k = 0;
56    for q in 0..n {
57        while z[k + 1] < q as f64 {
58            k += 1;
59        }
60        let p = v[k];
61        d[q] = h2 * ((q as f64 - p as f64).powi(2)) + f[p];
62        idx[q] = p;
63    }
64    (d, idx)
65}
66// ANCHOR_END: envelope
67
68/// The exact Euclidean distance transform with its feature transform.
69#[derive(Clone, Debug, PartialEq)]
70pub struct DistanceTransform {
71    /// The distance from each pixel to the nearest background pixel (0 on the background).
72    pub distances: Array2<f64>,
73    /// The `(row, column)` of that nearest background pixel.
74    pub nearest: Array2<(usize, usize)>,
75}
76
77// ANCHOR: edt
78/// The exact Euclidean distance transform of a binary image (SciPy's `distance_transform_edt`):
79/// for each foreground (`true`) pixel, the distance to the nearest background (`false`) pixel,
80/// with pixel spacing `sampling = (row spacing, column spacing)` (default `(1, 1)`). Background
81/// pixels get 0. The image must contain at least one background pixel.
82pub fn distance_transform_edt(mask: &Array2<bool>, sampling: Option<(f64, f64)>) -> Result<DistanceTransform, ErrorsJSL> {
83    let (rows, cols) = mask.dim();
84    let (hr, hc) = sampling.unwrap_or((1.0, 1.0));
85    if !(hr > 0.0 && hc > 0.0) {
86        return Err(ErrorsJSL::InvalidInputRange("sampling must be positive"));
87    }
88    if mask.iter().all(|&b| b) {
89        return Err(ErrorsJSL::InvalidInputRange("the image has no background pixel to measure from"));
90    }
91    // Pass 1, down each column: squared distance to the nearest background pixel in that column.
92    let mut g = Array2::<f64>::zeros((rows, cols));
93    let mut grow = Array2::<usize>::zeros((rows, cols));
94    for c in 0..cols {
95        let f: Vec<f64> = (0..rows).map(|r| if mask[(r, c)] { f64::INFINITY } else { 0.0 }).collect();
96        let (d, idx) = envelope(&f, hr);
97        for r in 0..rows {
98            g[(r, c)] = d[r];
99            grow[(r, c)] = idx[r];
100        }
101    }
102    // Pass 2, along each row: combine the column answers.
103    let mut distances = Array2::<f64>::zeros((rows, cols));
104    let mut nearest = Array2::from_elem((rows, cols), (0usize, 0usize));
105    for r in 0..rows {
106        let f: Vec<f64> = (0..cols).map(|c| g[(r, c)]).collect();
107        let (d, idx) = envelope(&f, hc);
108        for c in 0..cols {
109            distances[(r, c)] = d[c].sqrt();
110            nearest[(r, c)] = (grow[(r, idx[c])], idx[c]);
111        }
112    }
113    Ok(DistanceTransform { distances, nearest })
114}
115// ANCHOR_END: edt
116
117/// The metric of a chamfer distance transform.
118#[derive(Clone, Copy, Debug, PartialEq, Eq)]
119pub enum ChamferMetric {
120    /// City-block (L1) distance: steps to the four edge neighbours.
121    Taxicab,
122    /// Chessboard (L∞) distance: steps to all eight neighbours.
123    Chessboard,
124}
125
126// ANCHOR: cdt
127/// The chamfer distance transform (SciPy's `distance_transform_cdt`), in integer steps: a forward
128/// raster sweep takes each pixel's distance from its already visited neighbours (up and left), and
129/// a backward sweep from the others. Background pixels get 0. Images without background give
130/// `None` for every pixel.
131pub fn distance_transform_cdt(mask: &Array2<bool>, metric: ChamferMetric) -> Array2<Option<u32>> {
132    let (rows, cols) = mask.dim();
133    let big = u32::MAX / 2;
134    let mut d = Array2::from_shape_fn((rows, cols), |(r, c)| if mask[(r, c)] { big } else { 0 });
135    let forward: &[(isize, isize)] = match metric {
136        ChamferMetric::Taxicab => &[(-1, 0), (0, -1)],
137        ChamferMetric::Chessboard => &[(-1, -1), (-1, 0), (-1, 1), (0, -1)],
138    };
139    let relax = |d: &mut Array2<u32>, r: usize, c: usize, steps: &[(isize, isize)], sign: isize| {
140        for &(dr, dc) in steps {
141            let (nr, nc) = (r as isize + sign * dr, c as isize + sign * dc);
142            if nr >= 0 && nc >= 0 && (nr as usize) < rows && (nc as usize) < cols {
143                let cand = d[(nr as usize, nc as usize)].saturating_add(1);
144                if cand < d[(r, c)] {
145                    d[(r, c)] = cand;
146                }
147            }
148        }
149    };
150    for r in 0..rows {
151        for c in 0..cols {
152            relax(&mut d, r, c, forward, 1);
153        }
154    }
155    for r in (0..rows).rev() {
156        for c in (0..cols).rev() {
157            relax(&mut d, r, c, forward, -1);
158        }
159    }
160    d.mapv(|v| if v >= big { None } else { Some(v) })
161}
162// ANCHOR_END: cdt
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    #[test]
169    fn distances_from_a_single_background_pixel() {
170        let mut mask = Array2::from_elem((7, 9), true);
171        mask[(3, 4)] = false;
172        let t = distance_transform_edt(&mask, None).unwrap();
173        for ((r, c), &d) in t.distances.indexed_iter() {
174            let want = ((r as f64 - 3.0).powi(2) + (c as f64 - 4.0).powi(2)).sqrt();
175            assert!((d - want).abs() < 1e-12, "({r},{c}): {d} vs {want}");
176            assert_eq!(t.nearest[(r, c)], (3, 4));
177        }
178        let cdt = distance_transform_cdt(&mask, ChamferMetric::Taxicab);
179        assert_eq!(cdt[(0, 0)], Some(3 + 4));
180        let cdt = distance_transform_cdt(&mask, ChamferMetric::Chessboard);
181        assert_eq!(cdt[(0, 0)], Some(4));
182    }
183
184    #[test]
185    fn anisotropic_sampling_scales_the_axes() {
186        let mut mask = Array2::from_elem((5, 5), true);
187        mask[(0, 0)] = false;
188        let t = distance_transform_edt(&mask, Some((2.0, 0.5))).unwrap();
189        assert!((t.distances[(3, 4)] - ((6.0f64).powi(2) + 2.0f64.powi(2)).sqrt()).abs() < 1e-12);
190    }
191}