Skip to main content

lib_jsl_dsp/discrete/image/
feature_extraction.rs

1//! Image feature extraction.
2//!
3//! See the book entry [Local features](https://jwkunz.github.io/lib_jsl/book/image/features.html#matching).
4
5pub mod sift;
6pub mod surf;
7pub mod hough_transform;
8pub mod blob_detection;
9
10use lib_jsl_core::ErrorsJSL;
11
12/// A correspondence between a descriptor in set A and one in set B.
13#[derive(Clone, Copy, Debug, PartialEq)]
14pub struct DescriptorMatch {
15    pub index_a: usize,
16    pub index_b: usize,
17    /// Euclidean distance between the two descriptors.
18    pub distance: f64,
19}
20
21fn euclidean(a: &[f64], b: &[f64]) -> f64 {
22    a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum::<f64>().sqrt()
23}
24
25/// Matches descriptors by nearest neighbour with Lowe's ratio test.
26///
27/// For each descriptor in `a` the two nearest descriptors in `b` are found; the match is accepted
28/// only if the nearest is closer than `ratio` times the second nearest (0.75 is typical, smaller
29/// is stricter). This rejects ambiguous descriptors that resemble several candidates. With
30/// `mutual` set, a match must also be the nearest neighbour of its partner in the other direction.
31pub fn match_descriptors(a: &[Vec<f64>], b: &[Vec<f64>], ratio: f64, mutual: bool) -> Result<Vec<DescriptorMatch>, ErrorsJSL> {
32    if !(ratio > 0.0 && ratio <= 1.0) {
33        return Err(ErrorsJSL::InvalidInputRange("ratio must be in (0, 1]"));
34    }
35    let dim = a.first().or(b.first()).map_or(0, |d| d.len());
36    if a.iter().chain(b).any(|d| d.len() != dim) {
37        return Err(ErrorsJSL::InvalidInputRange("All descriptors must have the same length"));
38    }
39    if b.is_empty() {
40        return Ok(Vec::new());
41    }
42    let nearest = |query: &[f64], set: &[Vec<f64>]| -> (usize, f64, f64) {
43        let (mut best, mut best_d, mut second_d) = (0usize, f64::INFINITY, f64::INFINITY);
44        for (i, cand) in set.iter().enumerate() {
45            let d = euclidean(query, cand);
46            if d < best_d {
47                second_d = best_d;
48                best_d = d;
49                best = i;
50            } else if d < second_d {
51                second_d = d;
52            }
53        }
54        (best, best_d, second_d)
55    };
56    // ANCHOR: ratio_test
57    let mut out = Vec::new();
58    for (i, q) in a.iter().enumerate() {
59        let (j, d1, d2) = nearest(q, b);
60        // With a single candidate there is no second neighbour to compare against.
61        let passes = d2.is_infinite() || d1 < ratio * d2;
62        if passes && (!mutual || nearest(&b[j], a).0 == i) {
63            out.push(DescriptorMatch { index_a: i, index_b: j, distance: d1 });
64        }
65    }
66    Ok(out)
67    // ANCHOR_END: ratio_test
68}
69
70#[cfg(test)]
71mod matching_tests {
72    use super::*;
73
74    fn lcg(seed: &mut u64) -> f64 {
75        *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
76        ((*seed >> 33) as f64 / (1u64 << 31) as f64) - 0.5
77    }
78
79    fn random_set(n: usize, dim: usize, seed: &mut u64) -> Vec<Vec<f64>> {
80        (0..n).map(|_| (0..dim).map(|_| lcg(seed)).collect()).collect()
81    }
82
83    #[test]
84    fn recovers_a_shuffled_noisy_copy() {
85        let mut seed = 3;
86        let a = random_set(60, 32, &mut seed);
87        // b is a permutation of a with a little noise.
88        let perm: Vec<usize> = (0..60).map(|i| (i * 17 + 5) % 60).collect();
89        let b: Vec<Vec<f64>> = perm.iter().map(|&k| a[k].iter().map(|v| v + 0.01 * lcg(&mut seed)).collect()).collect();
90        let m = match_descriptors(&a, &b, 0.8, false).unwrap();
91        assert_eq!(m.len(), 60);
92        for mm in &m {
93            assert_eq!(perm[mm.index_b], mm.index_a);
94            assert!(mm.distance < 0.2);
95        }
96        assert_eq!(match_descriptors(&a, &b, 0.8, true).unwrap().len(), 60);
97    }
98
99    #[test]
100    fn the_ratio_test_rejects_ambiguous_descriptors() {
101        let a = vec![vec![0.0, 0.0]];
102        // Two near-identical candidates: the nearest is not clearly better than the second.
103        let b = vec![vec![1.0, 0.0], vec![1.0, 0.01]];
104        assert!(match_descriptors(&a, &b, 0.8, false).unwrap().is_empty());
105        // A distinct nearest neighbour passes.
106        let b2 = vec![vec![0.1, 0.0], vec![1.0, 1.0]];
107        let m = match_descriptors(&a, &b2, 0.8, false).unwrap();
108        assert_eq!((m[0].index_b, (m[0].distance - 0.1).abs() < 1e-12), (0, true));
109        // A single candidate has no competitor and is accepted.
110        assert_eq!(match_descriptors(&a, &[vec![5.0, 5.0]], 0.5, false).unwrap().len(), 1);
111    }
112
113    #[test]
114    fn mutual_checking_discards_one_sided_matches() {
115        // Both a0 and a1 prefer b0, but b0 prefers a0.
116        let a = vec![vec![0.0], vec![0.4]];
117        let b = vec![vec![0.1], vec![10.0]];
118        assert_eq!(match_descriptors(&a, &b, 1.0, false).unwrap().len(), 2);
119        let m = match_descriptors(&a, &b, 1.0, true).unwrap();
120        assert_eq!(m.len(), 1);
121        assert_eq!((m[0].index_a, m[0].index_b), (0, 0));
122    }
123
124    #[test]
125    fn empty_sets_and_invalid_arguments() {
126        let a = vec![vec![1.0, 2.0]];
127        assert!(match_descriptors(&a, &[], 0.8, false).unwrap().is_empty());
128        assert!(match_descriptors(&[], &a, 0.8, false).unwrap().is_empty());
129        assert!(match_descriptors(&a, &a, 0.0, false).is_err() && match_descriptors(&a, &a, 1.5, false).is_err());
130        assert!(match_descriptors(&a, &[vec![1.0]], 0.8, false).is_err(), "mismatched dimensions");
131    }
132}