1use std::collections::VecDeque;
13
14use lib_jsl_core::ErrorsJSL;
15use ndarray::Array2;
16
17use super::boundary::{Mode, sample};
18
19pub fn cross() -> Array2<bool> {
21 Array2::from_shape_fn((3, 3), |(i, j)| i == 1 || j == 1)
22}
23
24pub fn square(size: usize) -> Array2<bool> {
26 Array2::from_elem((size, size), true)
27}
28
29pub 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
38fn 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 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 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
80pub fn binary_erosion(image: &Array2<bool>, structure: &Array2<bool>, iterations: usize) -> Result<Array2<bool>, ErrorsJSL> {
86 repeat(image, structure, iterations, true)
87}
88
89pub fn binary_dilation(image: &Array2<bool>, structure: &Array2<bool>, iterations: usize) -> Result<Array2<bool>, ErrorsJSL> {
92 repeat(image, structure, iterations, false)
93}
94pub 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
102pub 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
107pub 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 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}
144fn 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
161pub fn grey_erosion(image: &Array2<f64>, footprint: &Array2<bool>, mode: Mode) -> Result<Array2<f64>, ErrorsJSL> {
165 grey_pass(image, footprint, mode, true)
166}
167
168pub fn grey_dilation(image: &Array2<f64>, footprint: &Array2<bool>, mode: Mode) -> Result<Array2<f64>, ErrorsJSL> {
170 grey_pass(image, footprint, mode, false)
171}
172pub 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
179pub 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
184pub 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
190pub 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
195pub 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 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}