Skip to main content

lib_jsl_dsp/discrete/image/feature_extraction/
sift.rs

1//! Scale-Invariant Feature Transform (SIFT).
2//!
3//! SIFT finds distinctive local features that can be matched between images of the same scene
4//! despite changes in position, scale, rotation and brightness/contrast. Following Lowe (2004):
5//!
6//! 1. **Scale space.** The image is blurred by a ladder of Gaussians grouped in *octaves*; each octave
7//!    covers a doubling of the blur `σ` with `scales_per_octave` steps, and the next octave starts from
8//!    a half-size copy.
9//! 2. **Detection.** Subtracting adjacent blurred images gives difference-of-Gaussian (DoG) images, an
10//!    approximation of the scale-normalised Laplacian. Local extrema over position *and* scale
11//!    (3×3×3 neighbourhoods) are candidate keypoints.
12//! 3. **Localisation.** A quadratic fit refines each candidate to sub-pixel, sub-scale accuracy;
13//!    low-contrast candidates and candidates on edges (where the 2×2 Hessian is badly conditioned)
14//!    are discarded as unstable.
15//! 4. **Orientation.** A histogram of gradient directions around the keypoint (Gaussian weighted)
16//!    gives one or more dominant orientations; a keypoint is created for each. Describing the
17//!    neighbourhood relative to this orientation makes the descriptor rotation invariant.
18//! 5. **Descriptor.** The orientation-aligned neighbourhood is divided into a 4×4 grid; each cell
19//!    holds an 8-bin gradient histogram (trilinearly interpolated), giving a 128-vector, normalised
20//!    and clipped at 0.2 to resist contrast and illumination changes.
21//!
22//! The input image is first normalised to `[0, 1]`, so the thresholds are relative to the image's
23//! own dynamic range and a uniform brightness/contrast change does not alter the result. A
24//! constant image has no features.
25//!
26//! Compared with the original paper, the image is not upsampled first (so the finest features, below
27//! about 2 pixels, are missed).
28//!
29//! See the book entry [Local features](https://jwkunz.github.io/lib_jsl/book/image/features.html#sift).
30
31use crate::discrete::image::filters::gaussian_blur::gaussian_blur;
32use lib_jsl_core::ErrorsJSL;
33use ndarray::Array2;
34use std::f64::consts::TAU;
35
36const DESCRIPTOR_WIDTH: usize = 4;
37const DESCRIPTOR_BINS: usize = 8;
38const ORIENTATION_BINS: usize = 36;
39const MAX_REFINE_STEPS: usize = 5;
40
41/// SIFT parameters.
42#[derive(Clone, Debug, PartialEq)]
43pub struct SiftParams {
44    /// Scale steps per octave (3 in Lowe's paper).
45    pub scales_per_octave: usize,
46    /// Base blur `σ₀` of each octave (1.6).
47    pub sigma: f64,
48    /// Blur assumed already present in the input (0.5).
49    pub initial_blur: f64,
50    /// Minimum DoG magnitude (after normalising the image to `[0, 1]`) of a refined keypoint,
51    /// scaled by `1 / scales_per_octave` (0.04).
52    pub contrast_threshold: f64,
53    /// Principal-curvature ratio limit for rejecting edge responses (10).
54    pub edge_threshold: f64,
55    /// Maximum number of octaves; `None` uses as many as fit (down to 16-pixel images).
56    pub max_octaves: Option<usize>,
57}
58
59impl Default for SiftParams {
60    fn default() -> Self {
61        SiftParams { scales_per_octave: 3, sigma: 1.6, initial_blur: 0.5, contrast_threshold: 0.04, edge_threshold: 10.0, max_octaves: None }
62    }
63}
64
65/// A SIFT keypoint with its descriptor.
66#[derive(Clone, Debug, PartialEq)]
67pub struct SiftKeypoint {
68    /// Column in the input image (sub-pixel).
69    pub x: f64,
70    /// Row in the input image (sub-pixel).
71    pub y: f64,
72    /// Detection scale in input pixels (the blur `σ` of the matching DoG layer).
73    pub sigma: f64,
74    /// Dominant gradient orientation in radians, in `[0, 2π)`, measured from the +column axis
75    /// toward the +row axis.
76    pub orientation: f64,
77    /// Absolute DoG value at the refined extremum (a contrast/strength measure).
78    pub response: f64,
79    pub octave: usize,
80    /// The 128-element descriptor (unit length).
81    pub descriptor: Vec<f64>,
82}
83
84struct Octave {
85    gaussians: Vec<Array2<f64>>,
86    dogs: Vec<Array2<f64>>,
87}
88
89fn downsample(img: &Array2<f64>) -> Array2<f64> {
90    let (rows, cols) = img.dim();
91    Array2::from_shape_fn((rows / 2, cols / 2), |(r, c)| img[(2 * r, 2 * c)])
92}
93
94fn build_octaves(image: &Array2<f64>, p: &SiftParams) -> Result<Vec<Octave>, ErrorsJSL> {
95    let s = p.scales_per_octave;
96    let k = 2f64.powf(1.0 / s as f64);
97    let (rows, cols) = image.dim();
98    let min_dim = rows.min(cols);
99    let fit = ((min_dim as f64 / 16.0).log2().floor().max(1.0)) as usize;
100    let n_octaves = p.max_octaves.map_or(fit, |m| m.min(fit)).max(1);
101    let mut base = gaussian_blur(image, (p.sigma * p.sigma - p.initial_blur * p.initial_blur).sqrt())?;
102    let mut octaves = Vec::with_capacity(n_octaves);
103    for _ in 0..n_octaves {
104        let mut gaussians = vec![base.clone()];
105        for i in 1..s + 3 {
106            let sigma_prev = p.sigma * k.powi(i as i32 - 1);
107            let sigma_inc = (sigma_prev * sigma_prev * (k * k - 1.0)).sqrt();
108            gaussians.push(gaussian_blur(&gaussians[i - 1], sigma_inc)?);
109        }
110        let dogs: Vec<Array2<f64>> = (0..s + 2).map(|i| &gaussians[i + 1] - &gaussians[i]).collect();
111        base = downsample(&gaussians[s]);
112        octaves.push(Octave { gaussians, dogs });
113    }
114    Ok(octaves)
115}
116
117/// Solves the 3×3 system `A x = b` by Cramer's rule, or `None` if singular.
118fn solve3(a: [[f64; 3]; 3], b: [f64; 3]) -> Option<[f64; 3]> {
119    let det = |m: [[f64; 3]; 3]| m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]);
120    let d = det(a);
121    if d.abs() < 1e-12 {
122        return None;
123    }
124    let mut x = [0.0; 3];
125    for (col, xc) in x.iter_mut().enumerate() {
126        let mut m = a;
127        for row in 0..3 {
128            m[row][col] = b[row];
129        }
130        *xc = det(m) / d;
131    }
132    Some(x)
133}
134
135struct Candidate {
136    layer: usize,
137    row: usize,
138    col: usize,
139    /// Sub-pixel offsets from the integer position (x = column, y = row, s = layer).
140    dx: f64,
141    dy: f64,
142    ds: f64,
143    contrast: f64,
144}
145
146/// Refines an extremum of the DoG stack and rejects unstable ones.
147fn refine(oct: &Octave, p: &SiftParams, mut layer: usize, mut row: usize, mut col: usize) -> Option<Candidate> {
148    let s = p.scales_per_octave;
149    let (rows, cols) = oct.dogs[0].dim();
150    for _ in 0..MAX_REFINE_STEPS {
151        if layer < 1 || layer > s || row < 1 || col < 1 || row + 2 > rows || col + 2 > cols {
152            return None;
153        }
154        let (dm, d0, dp) = (&oct.dogs[layer - 1], &oct.dogs[layer], &oct.dogs[layer + 1]);
155        let v = d0[(row, col)];
156        let g = [(d0[(row, col + 1)] - d0[(row, col - 1)]) / 2.0, (d0[(row + 1, col)] - d0[(row - 1, col)]) / 2.0, (dp[(row, col)] - dm[(row, col)]) / 2.0];
157        let dxx = d0[(row, col + 1)] + d0[(row, col - 1)] - 2.0 * v;
158        let dyy = d0[(row + 1, col)] + d0[(row - 1, col)] - 2.0 * v;
159        let dss = dp[(row, col)] + dm[(row, col)] - 2.0 * v;
160        let dxy = (d0[(row + 1, col + 1)] - d0[(row + 1, col - 1)] - d0[(row - 1, col + 1)] + d0[(row - 1, col - 1)]) / 4.0;
161        let dxs = (dp[(row, col + 1)] - dp[(row, col - 1)] - dm[(row, col + 1)] + dm[(row, col - 1)]) / 4.0;
162        let dys = (dp[(row + 1, col)] - dp[(row - 1, col)] - dm[(row + 1, col)] + dm[(row - 1, col)]) / 4.0;
163        let h = [[dxx, dxy, dxs], [dxy, dyy, dys], [dxs, dys, dss]];
164        // ANCHOR: sift_refine
165        let x = solve3(h, [-g[0], -g[1], -g[2]])?;
166        if x.iter().all(|v| v.abs() < 0.5) {
167            let contrast = v + 0.5 * (g[0] * x[0] + g[1] * x[1] + g[2] * x[2]);
168            if contrast.abs() * (s as f64) < p.contrast_threshold {
169                return None;
170            }
171            let (tr, det) = (dxx + dyy, dxx * dyy - dxy * dxy);
172            let r = p.edge_threshold;
173            if det <= 0.0 || r * tr * tr >= (r + 1.0) * (r + 1.0) * det {
174                return None;
175            }
176            return Some(Candidate { layer, row, col, dx: x[0], dy: x[1], ds: x[2], contrast });
177        }
178        // ANCHOR_END: sift_refine
179        // Move to the neighbouring sample the offset points to and try again.
180        let step = |v: f64| v.round() as isize;
181        let (nl, nr, nc) = (layer as isize + step(x[2]), row as isize + step(x[1]), col as isize + step(x[0]));
182        if nl < 0 || nr < 0 || nc < 0 {
183            return None;
184        }
185        layer = nl as usize;
186        row = nr as usize;
187        col = nc as usize;
188    }
189    None
190}
191
192fn is_extremum(oct: &Octave, layer: usize, r: usize, c: usize) -> bool {
193    let v = oct.dogs[layer][(r, c)];
194    let (mut is_max, mut is_min) = (true, true);
195    for l in layer - 1..=layer + 1 {
196        for rr in r - 1..=r + 1 {
197            for cc in c - 1..=c + 1 {
198                if (l, rr, cc) == (layer, r, c) {
199                    continue;
200                }
201                let n = oct.dogs[l][(rr, cc)];
202                if n >= v {
203                    is_max = false;
204                }
205                if n <= v {
206                    is_min = false;
207                }
208            }
209        }
210    }
211    is_max || is_min
212}
213
214/// Dominant gradient orientations around a keypoint, as angles in `[0, 2π)`.
215fn dominant_orientations(img: &Array2<f64>, row: usize, col: usize, sigma_oct: f64) -> Vec<f64> {
216    let (rows, cols) = img.dim();
217    let radius = (3.0 * 1.5 * sigma_oct).round() as isize;
218    let denom = 2.0 * (1.5 * sigma_oct).powi(2);
219    let mut hist = [0.0f64; ORIENTATION_BINS];
220    for dy in -radius..=radius {
221        let r = row as isize + dy;
222        if r < 1 || r >= rows as isize - 1 {
223            continue;
224        }
225        for dx in -radius..=radius {
226            let c = col as isize + dx;
227            if c < 1 || c >= cols as isize - 1 {
228                continue;
229            }
230            let (r, c) = (r as usize, c as usize);
231            let gx = img[(r, c + 1)] - img[(r, c - 1)];
232            let gy = img[(r + 1, c)] - img[(r - 1, c)];
233            let w = (-((dx * dx + dy * dy) as f64) / denom).exp();
234            let angle = gy.atan2(gx).rem_euclid(TAU);
235            let bin = (angle / TAU * ORIENTATION_BINS as f64).round() as usize % ORIENTATION_BINS;
236            hist[bin] += w * gx.hypot(gy);
237        }
238    }
239    for _ in 0..6 {
240        let prev = hist;
241        for j in 0..ORIENTATION_BINS {
242            hist[j] = (prev[(j + ORIENTATION_BINS - 1) % ORIENTATION_BINS] + prev[j] + prev[(j + 1) % ORIENTATION_BINS]) / 3.0;
243        }
244    }
245    let max = hist.iter().cloned().fold(0.0, f64::max);
246    if max <= 0.0 {
247        return Vec::new();
248    }
249    let mut out = Vec::new();
250    for j in 0..ORIENTATION_BINS {
251        let (l, c, r) = (hist[(j + ORIENTATION_BINS - 1) % ORIENTATION_BINS], hist[j], hist[(j + 1) % ORIENTATION_BINS]);
252        if c > l && c > r && c >= 0.8 * max {
253            let offset = 0.5 * (l - r) / (l - 2.0 * c + r);
254            out.push(((j as f64 + offset) / ORIENTATION_BINS as f64 * TAU).rem_euclid(TAU));
255        }
256    }
257    out
258}
259
260/// The 128-D descriptor of the neighbourhood of `(row, col)` aligned with `orientation`.
261fn compute_descriptor(img: &Array2<f64>, row: usize, col: usize, sigma_oct: f64, orientation: f64) -> Vec<f64> {
262    let (rows, cols) = img.dim();
263    let (d, n) = (DESCRIPTOR_WIDTH, DESCRIPTOR_BINS);
264    let (cos_t, sin_t) = (orientation.cos(), orientation.sin());
265    let hist_width = 3.0 * sigma_oct;
266    let radius = ((hist_width * std::f64::consts::SQRT_2 * (d as f64 + 1.0) * 0.5).round() as isize).min((rows.min(cols) / 2) as isize);
267    let exp_scale = -1.0 / (d as f64 * d as f64 * 0.5);
268    // Padded histogram so interpolation can spill one cell past each edge.
269    let mut hist = vec![0.0f64; (d + 2) * (d + 2) * n];
270    let idx = |r: usize, c: usize, o: usize| (r * (d + 2) + c) * n + o;
271    for i in -radius..=radius {
272        for j in -radius..=radius {
273            let c_rot = (j as f64 * cos_t + i as f64 * sin_t) / hist_width;
274            let r_rot = (-(j as f64) * sin_t + i as f64 * cos_t) / hist_width;
275            let rbin = r_rot + d as f64 / 2.0 - 0.5;
276            let cbin = c_rot + d as f64 / 2.0 - 0.5;
277            if !(rbin > -1.0 && rbin < d as f64 && cbin > -1.0 && cbin < d as f64) {
278                continue;
279            }
280            let (rr, cc) = (row as isize + i, col as isize + j);
281            if rr < 1 || rr >= rows as isize - 1 || cc < 1 || cc >= cols as isize - 1 {
282                continue;
283            }
284            let (rr, cc) = (rr as usize, cc as usize);
285            let gx = img[(rr, cc + 1)] - img[(rr, cc - 1)];
286            let gy = img[(rr + 1, cc)] - img[(rr - 1, cc)];
287            let mag = gx.hypot(gy) * (exp_scale * (c_rot * c_rot + r_rot * r_rot)).exp();
288            let ori = (gy.atan2(gx) - orientation).rem_euclid(TAU);
289            let obin = ori / TAU * n as f64;
290            let (r0, c0, o0) = (rbin.floor(), cbin.floor(), obin.floor());
291            let (fr, fc, fo) = (rbin - r0, cbin - c0, obin - o0);
292            let (r0, c0, o0) = ((r0 as isize + 1) as usize, (c0 as isize + 1) as usize, o0 as usize);
293            for (dr, wr) in [(0usize, 1.0 - fr), (1, fr)] {
294                for (dc, wc) in [(0usize, 1.0 - fc), (1, fc)] {
295                    for (dobin, wo) in [(0usize, 1.0 - fo), (1, fo)] {
296                        hist[idx(r0 + dr, c0 + dc, (o0 + dobin) % n)] += mag * wr * wc * wo;
297                    }
298                }
299            }
300        }
301    }
302    let mut desc = Vec::with_capacity(d * d * n);
303    for r in 1..=d {
304        for c in 1..=d {
305            for o in 0..n {
306                desc.push(hist[idx(r, c, o)]);
307            }
308        }
309    }
310    let normalise = |v: &mut Vec<f64>| {
311        let norm = v.iter().map(|x| x * x).sum::<f64>().sqrt();
312        if norm > 1e-12 {
313            v.iter_mut().for_each(|x| *x /= norm);
314        }
315    };
316    normalise(&mut desc);
317    desc.iter_mut().for_each(|x| *x = x.min(0.2));
318    normalise(&mut desc);
319    desc
320}
321
322/// Detects SIFT keypoints and computes their descriptors.
323pub fn sift(image: &Array2<f64>, params: &SiftParams) -> Result<Vec<SiftKeypoint>, ErrorsJSL> {
324    if params.scales_per_octave < 1 || !(params.sigma > params.initial_blur) || !(params.contrast_threshold >= 0.0) || !(params.edge_threshold > 0.0) {
325        return Err(ErrorsJSL::InvalidInputRange("Invalid SIFT parameters"));
326    }
327    let (rows, cols) = image.dim();
328    if rows < 16 || cols < 16 {
329        return Err(ErrorsJSL::InvalidInputRange("Image must be at least 16x16"));
330    }
331    if image.iter().any(|v| !v.is_finite()) {
332        return Err(ErrorsJSL::InvalidInputRange("Image must be finite"));
333    }
334    let (lo, hi) = image.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(l, h), &v| (l.min(v), h.max(v)));
335    if hi - lo <= 0.0 {
336        return Ok(Vec::new());
337    }
338    let normalised = image.mapv(|v| (v - lo) / (hi - lo));
339    let octaves = build_octaves(&normalised, params)?;
340    let s = params.scales_per_octave;
341    let mut keypoints = Vec::new();
342    for (o, oct) in octaves.iter().enumerate() {
343        let (orows, ocols) = oct.dogs[0].dim();
344        let pre = 0.5 * params.contrast_threshold / s as f64;
345        for layer in 1..=s {
346            for r in 1..orows.saturating_sub(1) {
347                for c in 1..ocols.saturating_sub(1) {
348                    if oct.dogs[layer][(r, c)].abs() <= pre || !is_extremum(oct, layer, r, c) {
349                        continue;
350                    }
351                    let Some(cand) = refine(oct, params, layer, r, c) else { continue };
352                    let sigma_oct = params.sigma * 2f64.powf((cand.layer as f64 + cand.ds) / s as f64);
353                    let img = &oct.gaussians[cand.layer];
354                    let scale = (1usize << o) as f64;
355                    for orientation in dominant_orientations(img, cand.row, cand.col, sigma_oct) {
356                        keypoints.push(SiftKeypoint {
357                            x: (cand.col as f64 + cand.dx) * scale,
358                            y: (cand.row as f64 + cand.dy) * scale,
359                            sigma: sigma_oct * scale,
360                            orientation,
361                            response: cand.contrast.abs(),
362                            octave: o,
363                            descriptor: compute_descriptor(img, cand.row, cand.col, sigma_oct, orientation),
364                        });
365                    }
366                }
367            }
368        }
369    }
370    Ok(keypoints)
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376    use crate::discrete::image::feature_extraction::match_descriptors;
377
378    /// A deterministic smooth random texture, rich in blobs and corners.
379    fn texture(n: usize, seed0: u64) -> Array2<f64> {
380        let mut seed = seed0;
381        let noise = Array2::from_shape_fn((n, n), |_| {
382            seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
383            (seed >> 33) as f64 / (1u64 << 31) as f64
384        });
385        gaussian_blur(&noise, 2.0).unwrap()
386    }
387
388    fn descriptors(k: &[SiftKeypoint]) -> Vec<Vec<f64>> {
389        k.iter().map(|kp| kp.descriptor.clone()).collect()
390    }
391
392    #[test]
393    fn a_constant_image_has_no_features() {
394        assert!(sift(&Array2::from_elem((64, 64), 0.4), &SiftParams::default()).unwrap().is_empty());
395    }
396
397    #[test]
398    fn a_single_gaussian_blob_is_found_at_its_centre_and_scale() {
399        let s = 4.0;
400        let img = Array2::from_shape_fn((96, 96), |(r, c)| (-((r as f64 - 48.0).powi(2) + (c as f64 - 48.0).powi(2)) / (2.0 * s * s)).exp());
401        let kps = sift(&img, &SiftParams::default()).unwrap();
402        assert!(!kps.is_empty());
403        let best = kps.iter().max_by(|a, b| a.response.partial_cmp(&b.response).unwrap()).unwrap();
404        assert!((best.x - 48.0).abs() < 1.0 && (best.y - 48.0).abs() < 1.0, "({}, {})", best.x, best.y);
405        assert!((best.sigma / s - 1.0).abs() < 0.3, "sigma {} vs blob std {s}", best.sigma);
406        // A radially symmetric blob has no preferred direction; whatever orientation is chosen,
407        // the descriptor is a valid unit vector.
408        assert!((best.descriptor.iter().map(|v| v * v).sum::<f64>() - 1.0).abs() < 1e-9);
409    }
410
411    #[test]
412    fn descriptors_are_unit_length_clipped_and_finite() {
413        let kps = sift(&texture(128, 1), &SiftParams::default()).unwrap();
414        assert!(kps.len() > 40, "{} keypoints", kps.len());
415        for k in &kps {
416            assert_eq!(k.descriptor.len(), 128);
417            assert!(k.descriptor.iter().all(|v| v.is_finite() && *v >= 0.0 && *v <= 1.0 + 1e-9));
418            let norm = k.descriptor.iter().map(|v| v * v).sum::<f64>().sqrt();
419            assert!((norm - 1.0).abs() < 1e-9);
420            assert!((0.0..TAU).contains(&k.orientation));
421            assert!(k.x >= 0.0 && k.x < 128.0 && k.y >= 0.0 && k.y < 128.0);
422        }
423    }
424
425    #[test]
426    fn invariant_to_translation() {
427        let t = texture(176, 2);
428        let a = t.slice(ndarray::s![16..144, 16..144]).to_owned();
429        let b = t.slice(ndarray::s![23..151, 11..139]).to_owned(); // content moves by (-7 rows, +5 columns)
430        let (ka, kb) = (sift(&a, &SiftParams::default()).unwrap(), sift(&b, &SiftParams::default()).unwrap());
431        let matches = match_descriptors(&descriptors(&ka), &descriptors(&kb), 0.8, true).unwrap();
432        assert!(matches.len() >= 25, "only {} matches from {} and {} keypoints", matches.len(), ka.len(), kb.len());
433        let consistent = matches.iter().filter(|m| (kb[m.index_b].x - ka[m.index_a].x - 5.0).abs() < 1.5 && (kb[m.index_b].y - ka[m.index_a].y + 7.0).abs() < 1.5).count();
434        assert!(consistent as f64 >= 0.85 * matches.len() as f64, "{consistent} of {} matches follow the shift", matches.len());
435    }
436
437    #[test]
438    fn invariant_to_a_quarter_turn_rotation_and_reports_the_rotation() {
439        let n = 128;
440        let a = texture(n, 3);
441        // Rotate 90 degrees counter-clockwise: b[r][c] = a[c][n-1-r].
442        let b = Array2::from_shape_fn((n, n), |(r, c)| a[(c, n - 1 - r)]);
443        let (ka, kb) = (sift(&a, &SiftParams::default()).unwrap(), sift(&b, &SiftParams::default()).unwrap());
444        let matches = match_descriptors(&descriptors(&ka), &descriptors(&kb), 0.8, true).unwrap();
445        assert!(matches.len() >= 25, "only {} matches", matches.len());
446        // A point (x = col, y = row) in a lands at (x', y') = (y, n-1-x) in b.
447        let positional = matches.iter().filter(|m| (kb[m.index_b].x - ka[m.index_a].y).abs() < 1.5 && (kb[m.index_b].y - (n as f64 - 1.0 - ka[m.index_a].x)).abs() < 1.5).count();
448        assert!(positional as f64 >= 0.85 * matches.len() as f64, "{positional} of {}", matches.len());
449        // The orientation changes by the same quarter turn for the consistent matches.
450        let diffs: Vec<f64> = matches.iter().map(|m| (kb[m.index_b].orientation - ka[m.index_a].orientation).rem_euclid(TAU)).collect();
451        let mut hist = [0usize; 4];
452        for d in &diffs {
453            hist[((d / (TAU / 4.0)).round() as usize) % 4] += 1;
454        }
455        let dominant = hist.iter().cloned().max().unwrap();
456        assert!(dominant as f64 >= 0.8 * diffs.len() as f64, "orientation differences cluster at a quarter-turn multiple: {hist:?}");
457    }
458
459    #[test]
460    fn invariant_to_brightness_and_contrast_changes() {
461        let a = texture(128, 4);
462        let b = a.mapv(|v| 0.35 * v + 0.2);
463        let (ka, kb) = (sift(&a, &SiftParams::default()).unwrap(), sift(&b, &SiftParams::default()).unwrap());
464        assert_eq!(ka.len(), kb.len(), "the image is normalised, so an affine intensity change is invisible");
465        let matches = match_descriptors(&descriptors(&ka), &descriptors(&kb), 0.8, true).unwrap();
466        assert!(matches.len() as f64 >= 0.9 * ka.len() as f64);
467        assert!(matches.iter().all(|m| m.distance < 1e-6 && (ka[m.index_a].x - kb[m.index_b].x).abs() < 1e-6 && (ka[m.index_a].y - kb[m.index_b].y).abs() < 1e-6));
468    }
469
470    #[test]
471    fn stricter_thresholds_keep_fewer_keypoints() {
472        let t = texture(128, 5);
473        let base = sift(&t, &SiftParams::default()).unwrap().len();
474        let strict = sift(&t, &SiftParams { contrast_threshold: 0.12, ..SiftParams::default() }).unwrap().len();
475        let one_octave = sift(&t, &SiftParams { max_octaves: Some(1), ..SiftParams::default() }).unwrap();
476        assert!(strict < base, "{strict} vs {base}");
477        assert!(one_octave.iter().all(|k| k.octave == 0));
478    }
479
480    #[test]
481    fn invalid_inputs() {
482        assert!(sift(&Array2::<f64>::zeros((8, 64)), &SiftParams::default()).is_err());
483        let mut img = texture(32, 6);
484        img[(3, 3)] = f64::NAN;
485        assert!(sift(&img, &SiftParams::default()).is_err());
486        let ok = texture(32, 6);
487        assert!(sift(&ok, &SiftParams { scales_per_octave: 0, ..SiftParams::default() }).is_err());
488        assert!(sift(&ok, &SiftParams { sigma: 0.4, ..SiftParams::default() }).is_err());
489        assert!(sift(&ok, &SiftParams { edge_threshold: 0.0, ..SiftParams::default() }).is_err());
490    }
491}