Skip to main content

lib_jsl_dsp/discrete/image/segmentation/
canny_edge_detection.rs

1//! Canny edge detection.
2//!
3//! The Canny detector turns an image into thin, connected, one-pixel-wide edges in four stages:
4//!
5//! 1. **Smooth** with a Gaussian (scale `sigma`) to suppress noise that would create false edges.
6//! 2. **Differentiate** with the Sobel operator to get gradient magnitude and direction.
7//! 3. **Thin** by *non-maximum suppression*: keep a pixel only if its magnitude is at least as large
8//!    as both neighbours along the gradient direction, i.e. it is on the ridge of the edge.
9//! 4. **Link** by *hysteresis thresholding*: pixels above the `high` threshold are certain edges;
10//!    pixels between `low` and `high` are kept only if they connect (8-neighbourhood) to a certain
11//!    edge. This keeps faint parts of real edges while discarding isolated noise.
12//!
13//! Thresholds are on the gradient magnitude in intensity units per pixel. The outermost pixel
14//! border is never marked.
15//!
16//! See the book entry [Segmentation](https://jwkunz.github.io/lib_jsl/book/image/segmentation.html#canny-edges).
17
18use crate::discrete::image::filters::{gaussian_blur::gaussian_blur, sobel::sobel};
19use lib_jsl_core::ErrorsJSL;
20use ndarray::Array2;
21use std::collections::VecDeque;
22
23/// Detects edges in `image`: smoothing scale `sigma` (pixels), and hysteresis thresholds `low <=
24/// high` on the gradient magnitude. Returns a boolean edge map.
25pub fn canny_edge_detection(image: &Array2<f64>, sigma: f64, low: f64, high: f64) -> Result<Array2<bool>, ErrorsJSL> {
26    if !(low >= 0.0) || !(high >= low) || !high.is_finite() {
27        return Err(ErrorsJSL::InvalidInputRange("Thresholds must satisfy 0 <= low <= high"));
28    }
29    let blurred = gaussian_blur(image, sigma)?;
30    let grad = sobel(&blurred, true)?;
31    let (rows, cols) = image.dim();
32    let mag = &grad.magnitude;
33
34    // Non-maximum suppression along the (quantised) gradient direction.
35    let mut thin = Array2::<f64>::zeros((rows, cols));
36    for r in 1..rows.saturating_sub(1) {
37        for c in 1..cols.saturating_sub(1) {
38            let m = mag[(r, c)];
39            if m <= 0.0 {
40                continue;
41            }
42            // Angle folded into [0, 180) degrees.
43            let mut deg = grad.direction[(r, c)].to_degrees();
44            if deg < 0.0 {
45                deg += 180.0;
46            }
47            if deg >= 180.0 {
48                deg -= 180.0;
49            }
50            let (dr, dc): (isize, isize) = if !(22.5..157.5).contains(&deg) {
51                (0, 1) // gradient along x: compare left and right
52            } else if deg < 67.5 {
53                (1, 1)
54            } else if deg < 112.5 {
55                (1, 0) // gradient along y: compare up and down
56            } else {
57                (1, -1)
58            };
59            let before = mag[((r as isize - dr) as usize, (c as isize - dc) as usize)];
60            let after = mag[((r as isize + dr) as usize, (c as isize + dc) as usize)];
61            // Strict on one side so a plateau of equal values yields a single ridge pixel.
62            if m > before && m >= after {
63                thin[(r, c)] = m;
64            }
65        }
66    }
67
68    // ANCHOR: hysteresis
69    // Hysteresis: grow from strong pixels through weak ones.
70    let mut edges = Array2::from_elem((rows, cols), false);
71    let mut queue = VecDeque::new();
72    for ((r, c), &m) in thin.indexed_iter() {
73        if m >= high && m > 0.0 {
74            edges[(r, c)] = true;
75            queue.push_back((r, c));
76        }
77    }
78    while let Some((r, c)) = queue.pop_front() {
79        for dr in -1isize..=1 {
80            for dc in -1isize..=1 {
81                let (nr, nc) = (r as isize + dr, c as isize + dc);
82                if nr < 0 || nc < 0 || nr >= rows as isize || nc >= cols as isize {
83                    continue;
84                }
85                let (nr, nc) = (nr as usize, nc as usize);
86                if !edges[(nr, nc)] && thin[(nr, nc)] >= low && thin[(nr, nc)] > 0.0 {
87                    edges[(nr, nc)] = true;
88                    queue.push_back((nr, nc));
89                }
90            }
91        }
92    }
93    Ok(edges)
94    // ANCHOR_END: hysteresis
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100
101    fn lcg(seed: &mut u64) -> f64 {
102        *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
103        ((*seed >> 33) as f64 / (1u64 << 31) as f64) - 0.5
104    }
105
106    fn square(n: usize, lo: usize, hi: usize) -> Array2<f64> {
107        Array2::from_shape_fn((n, n), |(r, c)| if (lo..hi).contains(&r) && (lo..hi).contains(&c) { 1.0 } else { 0.0 })
108    }
109
110    #[test]
111    fn edges_of_a_square_are_thin_and_on_its_boundary() {
112        let img = square(60, 20, 40);
113        let e = canny_edge_detection(&img, 1.0, 0.05, 0.15).unwrap();
114        // Along a horizontal cut through the middle there are exactly two edge pixels, at the sides.
115        let row: Vec<usize> = (0..60).filter(|&c| e[(30, c)]).collect();
116        assert_eq!(row.len(), 2, "one edge pixel per side, got {row:?}");
117        assert!(row[0].abs_diff(20) <= 1 && row[1].abs_diff(39) <= 1, "{row:?}");
118        // Same vertically, and nothing inside or far outside.
119        let col: Vec<usize> = (0..60).filter(|&r| e[(r, 30)]).collect();
120        assert_eq!(col.len(), 2, "{col:?}");
121        assert!(!e[(30, 30)] && !e[(5, 5)] && !e[(55, 55)] && !e[(30, 5)]);
122        // The detected set is the right ballpark: roughly the 80-pixel perimeter.
123        let total = e.iter().filter(|v| **v).count();
124        assert!((70..=110).contains(&total), "{total} edge pixels");
125    }
126
127    #[test]
128    fn hysteresis_keeps_faint_segments_attached_to_strong_edges_and_drops_isolated_ones() {
129        // One vertical edge at column 15 whose contrast fades smoothly from 1.0 (rows <= 10) to
130        // 0.3 (rows >= 30): strong at the top, faint at the bottom, continuous in between. (An
131        // abrupt change of contrast would create a second, horizontal edge and a gap at the corner.)
132        // Separately, an isolated faint edge at column 45.
133        let amplitude = |r: usize| (1.0 - 0.7 * (r as f64 - 10.0) / 20.0).clamp(0.3, 1.0);
134        let img = Array2::from_shape_fn((40, 60), |(r, c)| {
135            let fading = if c >= 15 { amplitude(r) } else { 0.0 };
136            let isolated = if c >= 45 && (5..15).contains(&r) { 0.3 } else { 0.0 };
137            fading + isolated
138        });
139        let e = canny_edge_detection(&img, 1.0, 0.04, 0.2).unwrap();
140        let count = |rows: std::ops::Range<usize>, cols: std::ops::Range<usize>| rows.flat_map(|r| cols.clone().map(move |c| (r, c))).filter(|&p| e[p]).count();
141        assert!(count(3..18, 13..18) >= 12, "the strong part is found");
142        assert!(count(26..38, 13..18) >= 10, "the faint part survives through hysteresis: {}", count(26..38, 13..18));
143        assert_eq!(count(5..15, 43..48), 0, "the isolated faint edge is rejected");
144        // Without hysteresis (low == high) the faint part disappears but the strong part remains.
145        let strict = canny_edge_detection(&img, 1.0, 0.2, 0.2).unwrap();
146        assert!((26..38).flat_map(|r| (13..18).map(move |c| (r, c))).all(|p| !strict[p]));
147        assert!((3..15).flat_map(|r| (13..18).map(move |c| (r, c))).filter(|&p| strict[p]).count() >= 10);
148    }
149
150    #[test]
151    fn noise_alone_produces_few_edges_with_sensible_thresholds_and_the_scene_survives_noise() {
152        let mut seed = 5;
153        let mut noise = |s: f64| s * (0..12).map(|_| lcg(&mut seed)).sum::<f64>();
154        let flat_noise = Array2::from_shape_fn((64, 64), |_| 0.5 + noise(0.03));
155        let none = canny_edge_detection(&flat_noise, 1.5, 0.05, 0.12).unwrap();
156        assert!(none.iter().filter(|v| **v).count() < 20);
157        let noisy_square = &square(64, 20, 44) + &Array2::from_shape_fn((64, 64), |_| noise(0.03));
158        let e = canny_edge_detection(&noisy_square, 1.5, 0.05, 0.12).unwrap();
159        assert!(e[(32, 20)] || e[(32, 19)] || e[(32, 21)], "left edge found despite noise");
160        assert!(e[(32, 43)] || e[(32, 44)] || e[(32, 42)], "right edge found despite noise");
161    }
162
163    #[test]
164    fn a_disc_gives_a_closed_ring_at_the_right_radius() {
165        let img = Array2::from_shape_fn((80, 80), |(r, c)| if ((r as f64 - 40.0).powi(2) + (c as f64 - 40.0).powi(2)).sqrt() < 20.0 { 1.0 } else { 0.0 });
166        let e = canny_edge_detection(&img, 1.5, 0.05, 0.15).unwrap();
167        let radii: Vec<f64> = e.indexed_iter().filter(|(_, v)| **v).map(|((r, c), _)| ((r as f64 - 40.0).powi(2) + (c as f64 - 40.0).powi(2)).sqrt()).collect();
168        assert!(radii.len() > 100);
169        assert!(radii.iter().all(|r| (r - 20.0).abs() < 1.5), "all edge pixels on the circle");
170        // Every direction has an edge pixel: the ring is closed.
171        let mut hit = [false; 36];
172        for ((r, c), v) in e.indexed_iter() {
173            if *v {
174                let a = (r as f64 - 40.0).atan2(c as f64 - 40.0).to_degrees().rem_euclid(360.0);
175                hit[(a / 10.0) as usize % 36] = true;
176            }
177        }
178        assert!(hit.iter().all(|h| *h));
179    }
180
181    #[test]
182    fn flat_images_and_invalid_thresholds() {
183        let flat = Array2::from_elem((20, 20), 0.7);
184        assert!(canny_edge_detection(&flat, 1.0, 0.1, 0.2).unwrap().iter().all(|v| !*v));
185        assert!(canny_edge_detection(&flat, 1.0, 0.3, 0.2).is_err());
186        assert!(canny_edge_detection(&flat, 1.0, -0.1, 0.2).is_err());
187        assert!(canny_edge_detection(&flat, 0.0, 0.1, 0.2).is_err());
188        let tiny = Array2::from_elem((2, 2), 1.0);
189        assert!(canny_edge_detection(&tiny, 1.0, 0.1, 0.2).unwrap().iter().all(|v| !*v));
190    }
191}