Skip to main content

lib_jsl_dsp/discrete/image/feature_extraction/
blob_detection.rs

1//! Blob detection with the scale-normalised Laplacian of Gaussian (LoG).
2//!
3//! A *blob* is a roughly round bright region on a darker background. Smoothing an image with a
4//! Gaussian of scale `σ` and taking the Laplacian responds most strongly, at a blob's centre, when
5//! `σ` matches the blob's size. Multiplying by `σ²` (scale normalisation) makes responses at
6//! different scales comparable, so searching for local maxima over *position and scale* finds each
7//! blob's centre and size at once. For a Gaussian blob of standard deviation `s` the response peaks
8//! at `σ = s`; a disc of radius `R` peaks at `σ = R / √2`.
9//!
10//! Overlapping detections of the same blob at neighbouring positions or scales are pruned,
11//! keeping the strongest.
12//!
13//! Only *bright* blobs are detected. A dark blob on a bright background gives a negative response
14//! at its centre but, as with any LoG, weak positive sidelobes in a ring around it (about 13% of
15//! the response of an equal-contrast bright blob), so use a `threshold` comfortably above that.
16//!
17//! See the book entry [Local features](https://jwkunz.github.io/lib_jsl/book/image/features.html#blobs-and-the-normalised-laplacian).
18
19use crate::discrete::image::convolution::{correlate2d, Border};
20use crate::discrete::image::filters::gaussian_blur::gaussian_blur;
21use lib_jsl_core::ErrorsJSL;
22use ndarray::{array, Array2};
23use std::f64::consts::PI;
24
25/// A detected blob.
26#[derive(Clone, Copy, Debug, PartialEq)]
27pub struct Blob {
28    pub row: usize,
29    pub col: usize,
30    /// The detection scale; the blob's radius is about `sigma · √2`.
31    pub sigma: f64,
32    /// The scale-normalised LoG response (larger = stronger/higher-contrast).
33    pub response: f64,
34}
35
36impl Blob {
37    /// The blob's approximate radius, `σ √2`.
38    pub fn radius(&self) -> f64 {
39        self.sigma * std::f64::consts::SQRT_2
40    }
41}
42
43/// Fraction of the smaller circle's area covered by the intersection of two circles.
44fn overlap_fraction(a: &Blob, b: &Blob) -> f64 {
45    let (ra, rb) = (a.radius(), b.radius());
46    let d = ((a.row as f64 - b.row as f64).powi(2) + (a.col as f64 - b.col as f64).powi(2)).sqrt();
47    let (small, large) = if ra < rb { (ra, rb) } else { (rb, ra) };
48    if d >= ra + rb {
49        return 0.0;
50    }
51    if d <= large - small {
52        return 1.0; // the smaller circle lies inside the larger
53    }
54    let part = |r1: f64, r2: f64| {
55        let x = ((d * d + r1 * r1 - r2 * r2) / (2.0 * d * r1)).clamp(-1.0, 1.0);
56        r1 * r1 * x.acos()
57    };
58    let kite = 0.5 * ((-d + ra + rb) * (d + ra - rb) * (d - ra + rb) * (d + ra + rb)).max(0.0).sqrt();
59    (part(ra, rb) + part(rb, ra) - kite) / (PI * small * small)
60}
61
62/// Detects bright blobs of scale between `min_sigma` and `max_sigma` (`num_sigma` geometrically
63/// spaced scales). A detection must be a local maximum over its 3×3×3 neighbourhood in position and
64/// scale with a normalised response above `threshold`; of two detections overlapping by more than
65/// `overlap` (a fraction of the smaller blob's area, in `[0, 1]`) only the stronger is kept.
66/// The image intensity scale matters for `threshold` (about 0.1 is reasonable for images in `[0, 1]`).
67pub fn blob_detection(image: &Array2<f64>, min_sigma: f64, max_sigma: f64, num_sigma: usize, threshold: f64, overlap: f64) -> Result<Vec<Blob>, ErrorsJSL> {
68    if !(min_sigma > 0.0) || !(max_sigma >= min_sigma) || num_sigma < 3 {
69        return Err(ErrorsJSL::InvalidInputRange("Need 0 < min_sigma <= max_sigma and at least 3 scales"));
70    }
71    if !(threshold >= 0.0) || !(0.0..=1.0).contains(&overlap) {
72        return Err(ErrorsJSL::InvalidInputRange("threshold must be non-negative and overlap within [0, 1]"));
73    }
74    let (rows, cols) = image.dim();
75    if rows < 3 || cols < 3 {
76        return Err(ErrorsJSL::InvalidInputRange("Image must be at least 3x3"));
77    }
78    let ratio = if num_sigma > 1 { (max_sigma / min_sigma).powf(1.0 / (num_sigma - 1) as f64) } else { 1.0 };
79    let sigmas: Vec<f64> = (0..num_sigma).map(|i| min_sigma * ratio.powi(i as i32)).collect();
80    // ANCHOR: log_stack
81    let laplacian = array![[0.0, 1.0, 0.0], [1.0, -4.0, 1.0], [0.0, 1.0, 0.0]];
82    // Scale-normalised, sign-flipped so bright blobs are positive maxima.
83    let stack: Vec<Array2<f64>> = sigmas
84        .iter()
85        .map(|&s| {
86            let lap = correlate2d(&gaussian_blur(image, s)?, &laplacian, Border::Replicate)?;
87            Ok(lap.mapv(|v| -s * s * v))
88        })
89        .collect::<Result<_, ErrorsJSL>>()?;
90    // ANCHOR_END: log_stack
91
92    let mut blobs = Vec::new();
93    for i in 0..num_sigma {
94        for r in 1..rows - 1 {
95            for c in 1..cols - 1 {
96                let v = stack[i][(r, c)];
97                if v < threshold {
98                    continue;
99                }
100                let mut is_max = true;
101                'nbr: for di in -1isize..=1 {
102                    let ii = i as isize + di;
103                    if ii < 0 || ii >= num_sigma as isize {
104                        continue;
105                    }
106                    for dr in -1isize..=1 {
107                        for dc in -1isize..=1 {
108                            if (di, dr, dc) == (0, 0, 0) {
109                                continue;
110                            }
111                            let n = stack[ii as usize][((r as isize + dr) as usize, (c as isize + dc) as usize)];
112                            // Strict on the "earlier" half so a plateau yields one detection.
113                            if n > v || (n == v && (di, dr, dc) < (0, 0, 0)) {
114                                is_max = false;
115                                break 'nbr;
116                            }
117                        }
118                    }
119                }
120                if is_max {
121                    blobs.push(Blob { row: r, col: c, sigma: sigmas[i], response: v });
122                }
123            }
124        }
125    }
126    blobs.sort_by(|a, b| b.response.partial_cmp(&a.response).unwrap());
127    let mut kept: Vec<Blob> = Vec::new();
128    for b in blobs {
129        if kept.iter().all(|k| overlap_fraction(k, &b) <= overlap) {
130            kept.push(b);
131        }
132    }
133    Ok(kept)
134}
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139
140    fn gaussian_blobs(n: usize, blobs: &[(f64, f64, f64, f64)]) -> Array2<f64> {
141        Array2::from_shape_fn((n, n), |(r, c)| blobs.iter().map(|&(br, bc, s, a)| a * (-((r as f64 - br).powi(2) + (c as f64 - bc).powi(2)) / (2.0 * s * s)).exp()).sum())
142    }
143
144    #[test]
145    fn finds_gaussian_blobs_at_their_centres_with_the_right_scale() {
146        let img = gaussian_blobs(80, &[(24.0, 24.0, 4.0, 1.0), (52.0, 56.0, 7.0, 1.0)]);
147        let blobs = blob_detection(&img, 2.5, 10.0, 11, 0.05, 0.5).unwrap();
148        assert_eq!(blobs.len(), 2, "{blobs:?}");
149        let small = blobs.iter().find(|b| b.row.abs_diff(24) <= 1).expect("small blob");
150        let large = blobs.iter().find(|b| b.row.abs_diff(52) <= 1).expect("large blob");
151        assert!(small.col.abs_diff(24) <= 1 && large.col.abs_diff(56) <= 1);
152        // For a Gaussian blob of standard deviation s the normalised LoG peaks at sigma = s.
153        assert!((small.sigma / 4.0 - 1.0).abs() < 0.15, "small sigma {}", small.sigma);
154        assert!((large.sigma / 7.0 - 1.0).abs() < 0.15, "large sigma {}", large.sigma);
155        assert!((large.radius() / (7.0 * std::f64::consts::SQRT_2) - 1.0).abs() < 0.15);
156    }
157
158    #[test]
159    fn a_disc_peaks_at_its_radius_over_root_two() {
160        let img = Array2::from_shape_fn((64, 64), |(r, c)| if ((r as f64 - 32.0).powi(2) + (c as f64 - 32.0).powi(2)).sqrt() < 10.0 { 1.0 } else { 0.0 });
161        let blobs = blob_detection(&img, 3.0, 10.0, 10, 0.1, 0.5).unwrap();
162        assert_eq!(blobs.len(), 1, "{blobs:?}");
163        assert!(blobs[0].row.abs_diff(32) <= 1 && blobs[0].col.abs_diff(32) <= 1);
164        assert!((blobs[0].radius() / 10.0 - 1.0).abs() < 0.2, "estimated radius {}", blobs[0].radius());
165    }
166
167    #[test]
168    fn threshold_rejects_weak_blobs_and_dark_blobs_are_ignored() {
169        let img = gaussian_blobs(80, &[(24.0, 24.0, 5.0, 1.0), (56.0, 56.0, 5.0, 0.15)]);
170        let strong_only = blob_detection(&img, 3.0, 8.0, 8, 0.2, 0.5).unwrap();
171        assert_eq!(strong_only.len(), 1);
172        assert!(strong_only[0].row.abs_diff(24) <= 1);
173        let both = blob_detection(&img, 3.0, 8.0, 8, 0.02, 0.5).unwrap();
174        assert_eq!(both.len(), 2);
175        // A dark blob on a bright background is a minimum of the response, not a detection.
176        let dark = gaussian_blobs(60, &[(30.0, 30.0, 5.0, -1.0)]).mapv(|v| v + 1.0);
177        // (A dark blob's LoG response has weak positive sidelobes in a ring around it, about 13%
178        // of the response of an equal-contrast bright blob, so the threshold must exceed that.)
179        assert!(blob_detection(&dark, 3.0, 8.0, 8, 0.15, 0.5).unwrap().is_empty());
180        let bright = gaussian_blobs(60, &[(30.0, 30.0, 5.0, 1.0)]);
181        assert_eq!(blob_detection(&bright, 3.0, 8.0, 8, 0.15, 0.5).unwrap().len(), 1, "the same contrast, bright, is found");
182    }
183
184    #[test]
185    fn nearby_duplicates_are_pruned_by_the_overlap_rule() {
186        let img = gaussian_blobs(80, &[(40.0, 36.0, 5.0, 1.0), (40.0, 44.0, 5.0, 0.9)]);
187        let merged = blob_detection(&img, 3.0, 9.0, 10, 0.05, 0.2).unwrap();
188        let separate = blob_detection(&img, 3.0, 9.0, 10, 0.05, 1.0).unwrap();
189        assert!(merged.len() <= separate.len(), "stricter overlap keeps fewer blobs");
190        // Overlap geometry sanity.
191        let a = Blob { row: 10, col: 10, sigma: 5.0, response: 1.0 };
192        assert_eq!(overlap_fraction(&a, &a), 1.0);
193        assert_eq!(overlap_fraction(&a, &Blob { row: 10, col: 100, sigma: 5.0, response: 1.0 }), 0.0);
194        let half = overlap_fraction(&a, &Blob { row: 10, col: 20, sigma: 5.0, response: 1.0 });
195        assert!(half > 0.0 && half < 1.0, "{half}");
196    }
197
198    #[test]
199    fn flat_and_invalid_inputs() {
200        let flat = Array2::from_elem((30, 30), 0.5);
201        assert!(blob_detection(&flat, 2.0, 6.0, 5, 0.01, 0.5).unwrap().is_empty());
202        assert!(blob_detection(&flat, 0.0, 6.0, 5, 0.01, 0.5).is_err());
203        assert!(blob_detection(&flat, 6.0, 2.0, 5, 0.01, 0.5).is_err());
204        assert!(blob_detection(&flat, 2.0, 6.0, 2, 0.01, 0.5).is_err());
205        assert!(blob_detection(&flat, 2.0, 6.0, 5, -1.0, 0.5).is_err());
206        assert!(blob_detection(&flat, 2.0, 6.0, 5, 0.01, 1.5).is_err());
207        assert!(blob_detection(&Array2::<f64>::zeros((2, 2)), 2.0, 6.0, 5, 0.01, 0.5).is_err());
208    }
209}