Skip to main content

lib_jsl_dsp/discrete/image/
morphology.rs

1//! Mathematical morphology: erosion, dilation, opening, closing and hole filling for binary and
2//! greyscale images, following `scipy.ndimage`.
3//!
4//! Morphology probes an image with a small shape, the **structuring element**. Erosion keeps a
5//! pixel only if the element, centred there, fits inside the foreground; dilation turns a pixel on
6//! if the element touches the foreground. Combinations of the two remove small objects (opening),
7//! fill small gaps (closing), and extract outlines and peaks (gradients and top-hats). For
8//! greyscale images, "fits inside" becomes a minimum and "touches" a maximum over the element.
9//!
10//! See the book entry [Morphology, distance transforms and labelling](https://jwkunz.github.io/lib_jsl/book/image/morphology.html).
11
12use std::collections::VecDeque;
13
14use lib_jsl_core::ErrorsJSL;
15use ndarray::Array2;
16
17use super::boundary::{Mode, sample};
18
19/// The 3 × 3 cross: the four edge neighbours and the centre (4-connectivity; SciPy's default).
20pub fn cross() -> Array2<bool> {
21    Array2::from_shape_fn((3, 3), |(i, j)| i == 1 || j == 1)
22}
23
24/// The full 3 × 3 square (8-connectivity).
25pub fn square(size: usize) -> Array2<bool> {
26    Array2::from_elem((size, size), true)
27}
28
29/// A disc of the given radius, `(2r + 1) × (2r + 1)`.
30pub fn disk(radius: usize) -> Array2<bool> {
31    let r = radius as isize;
32    Array2::from_shape_fn((2 * radius + 1, 2 * radius + 1), |(i, j)| {
33        let (di, dj) = (i as isize - r, j as isize - r);
34        di * di + dj * dj <= r * r
35    })
36}
37
38/// The offsets `(di, dj)` of the true elements of a structuring element, relative to its centre.
39fn offsets(structure: &Array2<bool>) -> Result<Vec<(isize, isize)>, ErrorsJSL> {
40    let (h, w) = structure.dim();
41    if h == 0 || w == 0 || h % 2 == 0 || w % 2 == 0 {
42        return Err(ErrorsJSL::InvalidInputRange("structuring elements must have odd, non-zero dimensions"));
43    }
44    let (ch, cw) = ((h / 2) as isize, (w / 2) as isize);
45    Ok(structure.indexed_iter().filter(|(_, b)| **b).map(|((i, j), _)| (i as isize - ch, j as isize - cw)).collect())
46}
47
48fn binary_pass(image: &Array2<bool>, offsets: &[(isize, isize)], erode: bool, border: bool) -> Array2<bool> {
49    let (rows, cols) = image.dim();
50    let at = |r: isize, c: isize| {
51        if r < 0 || c < 0 || r >= rows as isize || c >= cols as isize { border } else { image[(r as usize, c as usize)] }
52    };
53    Array2::from_shape_fn((rows, cols), |(r, c)| {
54        let (r, c) = (r as isize, c as isize);
55        if erode {
56            offsets.iter().all(|&(di, dj)| at(r + di, c + dj))
57        } else {
58            // Dilation uses the reflected element, as in SciPy.
59            offsets.iter().any(|&(di, dj)| at(r - di, c - dj))
60        }
61    })
62}
63
64fn repeat(image: &Array2<bool>, structure: &Array2<bool>, iterations: usize, erode: bool) -> Result<Array2<bool>, ErrorsJSL> {
65    let offsets = offsets(structure)?;
66    let mut out = binary_pass(image, &offsets, erode, false);
67    let mut k = 1;
68    // `iterations == 0` repeats until nothing changes.
69    while iterations == 0 || k < iterations {
70        let next = binary_pass(&out, &offsets, erode, false);
71        if next == out {
72            break;
73        }
74        out = next;
75        k += 1;
76    }
77    Ok(out)
78}
79
80// ANCHOR: binary
81/// Binary erosion: a pixel stays on only if every element of `structure`, centred on it, lies on
82/// the foreground. Pixels beyond the image count as background, so objects touching the edge are
83/// eroded from it (SciPy's `binary_erosion` with `border_value=0`). `iterations` repeats the
84/// operation; `0` repeats until the image stops changing.
85pub fn binary_erosion(image: &Array2<bool>, structure: &Array2<bool>, iterations: usize) -> Result<Array2<bool>, ErrorsJSL> {
86    repeat(image, structure, iterations, true)
87}
88
89/// Binary dilation: a pixel turns on if the reflected `structure`, centred on it, touches the
90/// foreground (SciPy's `binary_dilation`).
91pub fn binary_dilation(image: &Array2<bool>, structure: &Array2<bool>, iterations: usize) -> Result<Array2<bool>, ErrorsJSL> {
92    repeat(image, structure, iterations, false)
93}
94// ANCHOR_END: binary
95
96/// Opening: erosion then dilation. Removes objects (and protrusions) smaller than the element,
97/// and leaves larger ones nearly unchanged.
98pub fn binary_opening(image: &Array2<bool>, structure: &Array2<bool>, iterations: usize) -> Result<Array2<bool>, ErrorsJSL> {
99    binary_dilation(&binary_erosion(image, structure, iterations)?, structure, iterations)
100}
101
102/// Closing: dilation then erosion. Fills gaps and holes smaller than the element.
103pub fn binary_closing(image: &Array2<bool>, structure: &Array2<bool>, iterations: usize) -> Result<Array2<bool>, ErrorsJSL> {
104    binary_erosion(&binary_dilation(image, structure, iterations)?, structure, iterations)
105}
106
107// ANCHOR: fill_holes
108/// Fills the holes of a binary image: background regions that cannot be reached from outside the
109/// image by steps allowed by `structure` (the cross gives 4-connected steps, the square
110/// 8-connected). A breadth-first search from the background pixels next to the border marks the
111/// outside; everything else becomes foreground (SciPy's `binary_fill_holes`).
112pub fn binary_fill_holes(image: &Array2<bool>, structure: &Array2<bool>) -> Result<Array2<bool>, ErrorsJSL> {
113    let steps: Vec<(isize, isize)> = offsets(structure)?.into_iter().filter(|&d| d != (0, 0)).collect();
114    let (rows, cols) = image.dim();
115    let inside = |r: isize, c: isize| r >= 0 && c >= 0 && r < rows as isize && c < cols as isize;
116    let mut outside = Array2::from_elem((rows, cols), false);
117    let mut queue = VecDeque::new();
118    for r in 0..rows {
119        for c in 0..cols {
120            if image[(r, c)] {
121                continue;
122            }
123            // A background pixel is reached from beyond the edge if one of its steps leaves the image.
124            if steps.iter().any(|&(di, dj)| !inside(r as isize - di, c as isize - dj)) {
125                outside[(r, c)] = true;
126                queue.push_back((r, c));
127            }
128        }
129    }
130    while let Some((r, c)) = queue.pop_front() {
131        for &(di, dj) in &steps {
132            let (nr, nc) = (r as isize + di, c as isize + dj);
133            if inside(nr, nc) {
134                let (nr, nc) = (nr as usize, nc as usize);
135                if !image[(nr, nc)] && !outside[(nr, nc)] {
136                    outside[(nr, nc)] = true;
137                    queue.push_back((nr, nc));
138                }
139            }
140        }
141    }
142    Ok(outside.mapv(|o| !o))
143}
144// ANCHOR_END: fill_holes
145
146fn grey_pass(image: &Array2<f64>, footprint: &Array2<bool>, mode: Mode, erode: bool) -> Result<Array2<f64>, ErrorsJSL> {
147    let offsets = offsets(footprint)?;
148    if image.is_empty() {
149        return Err(ErrorsJSL::InvalidInputRange("image must be non-empty"));
150    }
151    Ok(Array2::from_shape_fn(image.dim(), |(r, c)| {
152        let (r, c) = (r as isize, c as isize);
153        if erode {
154            offsets.iter().map(|&(di, dj)| sample(image, r + di, c + dj, mode)).fold(f64::INFINITY, f64::min)
155        } else {
156            offsets.iter().map(|&(di, dj)| sample(image, r - di, c - dj, mode)).fold(f64::NEG_INFINITY, f64::max)
157        }
158    }))
159}
160
161// ANCHOR: grey
162/// Greyscale erosion: the minimum over the footprint centred on each pixel (SciPy's
163/// `grey_erosion` with a flat footprint; the default mode there is `Reflect`).
164pub fn grey_erosion(image: &Array2<f64>, footprint: &Array2<bool>, mode: Mode) -> Result<Array2<f64>, ErrorsJSL> {
165    grey_pass(image, footprint, mode, true)
166}
167
168/// Greyscale dilation: the maximum over the reflected footprint (SciPy's `grey_dilation`).
169pub fn grey_dilation(image: &Array2<f64>, footprint: &Array2<bool>, mode: Mode) -> Result<Array2<f64>, ErrorsJSL> {
170    grey_pass(image, footprint, mode, false)
171}
172// ANCHOR_END: grey
173
174/// Greyscale opening (erosion then dilation): removes bright features smaller than the footprint.
175pub fn grey_opening(image: &Array2<f64>, footprint: &Array2<bool>, mode: Mode) -> Result<Array2<f64>, ErrorsJSL> {
176    grey_dilation(&grey_erosion(image, footprint, mode)?, footprint, mode)
177}
178
179/// Greyscale closing (dilation then erosion): removes dark features smaller than the footprint.
180pub fn grey_closing(image: &Array2<f64>, footprint: &Array2<bool>, mode: Mode) -> Result<Array2<f64>, ErrorsJSL> {
181    grey_erosion(&grey_dilation(image, footprint, mode)?, footprint, mode)
182}
183
184/// The white top-hat, `image − opening`: the bright features smaller than the footprint, with the
185/// background removed.
186pub fn white_tophat(image: &Array2<f64>, footprint: &Array2<bool>, mode: Mode) -> Result<Array2<f64>, ErrorsJSL> {
187    Ok(image - &grey_opening(image, footprint, mode)?)
188}
189
190/// The black top-hat, `closing − image`: the dark features smaller than the footprint.
191pub fn black_tophat(image: &Array2<f64>, footprint: &Array2<bool>, mode: Mode) -> Result<Array2<f64>, ErrorsJSL> {
192    Ok(&grey_closing(image, footprint, mode)? - image)
193}
194
195/// The morphological gradient, `dilation − erosion`: large on edges, zero in flat regions.
196pub fn morphological_gradient(image: &Array2<f64>, footprint: &Array2<bool>, mode: Mode) -> Result<Array2<f64>, ErrorsJSL> {
197    Ok(&grey_dilation(image, footprint, mode)? - &grey_erosion(image, footprint, mode)?)
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203
204    fn from_rows(rows: &[&str]) -> Array2<bool> {
205        Array2::from_shape_fn((rows.len(), rows[0].len()), |(i, j)| rows[i].as_bytes()[j] == b'#')
206    }
207
208    #[test]
209    fn opening_removes_a_speck_and_closing_fills_a_hole() {
210        let img = from_rows(&["........", ".####...", ".####..#", ".####...", ".##.#...", "........"]);
211        let open = binary_opening(&img, &cross(), 1).unwrap();
212        assert!(!open[(2, 7)], "the isolated pixel is removed");
213        let holed = from_rows(&["......", ".####.", ".#.##.", ".####.", "......"]);
214        let close = binary_closing(&holed, &cross(), 1).unwrap();
215        assert!(close[(2, 2)], "the one-pixel hole is filled");
216    }
217
218    #[test]
219    fn holes_are_filled_but_open_bays_are_not() {
220        let img = from_rows(&["#####.", "#...#.", "#.#.#.", "#...#.", "##.##.", "......"]);
221        let filled = binary_fill_holes(&img, &cross()).unwrap();
222        // The interior is connected to the outside through the gap at (4, 2): not a hole.
223        assert!(!filled[(1, 1)]);
224        let closed = from_rows(&["#####", "#...#", "#...#", "#####"]);
225        assert!(binary_fill_holes(&closed, &cross()).unwrap().iter().all(|&b| b));
226    }
227
228    #[test]
229    fn grey_erosion_and_dilation_are_minimum_and_maximum() {
230        let img = Array2::from_shape_fn((5, 5), |(i, j)| (i * 5 + j) as f64);
231        let e = grey_erosion(&img, &square(3), Mode::Reflect).unwrap();
232        let d = grey_dilation(&img, &square(3), Mode::Reflect).unwrap();
233        assert_eq!(e[(2, 2)], 6.0);
234        assert_eq!(d[(2, 2)], 18.0);
235        assert_eq!(e[(0, 0)], 0.0);
236        assert_eq!(d[(4, 4)], 24.0);
237    }
238}