Skip to main content

lib_jsl_dsp/discrete/image/feature_extraction/
surf.rs

1//! Speeded-Up Robust Features (SURF).
2//!
3//! SURF is a faster relative of SIFT built on the *integral image*, in which the sum of any
4//! axis-aligned rectangle costs four lookups regardless of its size. Following Bay et al. (2008):
5//!
6//! 1. **Detection.** The determinant of the Hessian `Dxx Dyy − (0.9 Dxy)²` is approximated with box
7//!    filters of increasing size (9, 15, 21, 27, then 15, 27, 39, 51, … in octaves). Instead of
8//!    shrinking the image, SURF *grows the filter*, so each scale costs the same. Local maxima over
9//!    position and scale are refined with a quadratic fit.
10//! 2. **Orientation.** Haar-wavelet responses in a circle of radius `6s` are weighted by a Gaussian
11//!    and a `π/3` window is slid around the circle; the window with the longest summed response
12//!    gives the dominant orientation.
13//! 3. **Descriptor.** A `20s × 20s` square aligned with that orientation is divided into 4×4
14//!    subregions of 5×5 Haar samples; each subregion contributes `(Σdx, Σdy, Σ|dx|, Σ|dy|)`, giving
15//!    a 64-vector normalised to unit length. (`upright` skips orientation for speed when images are
16//!    not rotated.)
17//!
18//! The image is normalised to `[0, 1]` first, so the detection threshold is relative to its dynamic
19//! range. The sign of the Laplacian (`Dxx + Dyy`) is stored so bright blobs on dark and dark on
20//! bright are never matched.
21//!
22//! See the book entry [Local features](https://jwkunz.github.io/lib_jsl/book/image/features.html#surf-and-the-integral-image).
23
24use lib_jsl_core::ErrorsJSL;
25use ndarray::Array2;
26use std::f64::consts::{PI, TAU};
27
28/// An integral image (summed-area table): `box_sum` of any rectangle in four lookups.
29#[derive(Clone, Debug, PartialEq)]
30pub struct IntegralImage {
31    /// `(rows + 1) × (cols + 1)`; `table[(r, c)]` is the sum of `image[..r, ..c]`.
32    table: Array2<f64>,
33}
34
35impl IntegralImage {
36    pub fn new(image: &Array2<f64>) -> IntegralImage {
37        let (rows, cols) = image.dim();
38        let mut table = Array2::<f64>::zeros((rows + 1, cols + 1));
39        for r in 0..rows {
40            let mut running = 0.0;
41            for c in 0..cols {
42                running += image[(r, c)];
43                table[(r + 1, c + 1)] = table[(r, c + 1)] + running;
44            }
45        }
46        IntegralImage { table }
47    }
48
49    pub fn rows(&self) -> usize {
50        self.table.nrows() - 1
51    }
52
53    pub fn cols(&self) -> usize {
54        self.table.ncols() - 1
55    }
56
57    /// Sum of the `height × width` rectangle whose top-left pixel is `(row, col)`; the part outside
58    /// the image contributes zero (so `row`/`col` may be negative).
59    pub fn box_sum(&self, row: isize, col: isize, height: usize, width: usize) -> f64 {
60        let (rows, cols) = (self.rows() as isize, self.cols() as isize);
61        let r0 = row.clamp(0, rows) as usize;
62        let c0 = col.clamp(0, cols) as usize;
63        let r1 = (row + height as isize).clamp(0, rows) as usize;
64        let c1 = (col + width as isize).clamp(0, cols) as usize;
65        if r1 <= r0 || c1 <= c0 {
66            return 0.0;
67        }
68        self.table[(r1, c1)] - self.table[(r0, c1)] - self.table[(r1, c0)] + self.table[(r0, c0)]
69    }
70
71    /// Haar wavelet response along x (right half minus left half) of a `size × size` window
72    /// centred on `(row, col)`.
73    fn haar_x(&self, row: isize, col: isize, size: usize) -> f64 {
74        let h = (size / 2) as isize;
75        self.box_sum(row - h, col, size, size / 2) - self.box_sum(row - h, col - h, size, size / 2)
76    }
77
78    /// Haar wavelet response along y (lower half minus upper half).
79    fn haar_y(&self, row: isize, col: isize, size: usize) -> f64 {
80        let h = (size / 2) as isize;
81        self.box_sum(row, col - h, size / 2, size) - self.box_sum(row - h, col - h, size / 2, size)
82    }
83}
84
85/// SURF parameters.
86#[derive(Clone, Debug, PartialEq)]
87pub struct SurfParams {
88    /// Number of octaves (default 3).
89    pub octaves: usize,
90    /// Filter sizes per octave (default 4).
91    pub intervals: usize,
92    /// Pixel step between response samples in the first octave (2 by default; 1 is denser and slower).
93    pub init_sample: usize,
94    /// Minimum Hessian-determinant response, for an image normalised to `[0, 1]` (default 0.0004).
95    pub threshold: f64,
96    /// Skip orientation assignment (U-SURF): faster, valid when the image is not rotated.
97    pub upright: bool,
98}
99
100impl Default for SurfParams {
101    fn default() -> Self {
102        SurfParams { octaves: 3, intervals: 4, init_sample: 2, threshold: 4e-4, upright: false }
103    }
104}
105
106/// A SURF keypoint with its descriptor.
107#[derive(Clone, Debug, PartialEq)]
108pub struct SurfKeypoint {
109    /// Column (sub-pixel).
110    pub x: f64,
111    /// Row (sub-pixel).
112    pub y: f64,
113    /// Scale `σ` in pixels (`1.2 · filter size / 9`).
114    pub scale: f64,
115    /// Orientation in radians, in `[0, 2π)` (0 when `upright`).
116    pub orientation: f64,
117    /// `+1` if the Laplacian is positive (bright blob on dark), `-1` otherwise.
118    pub laplacian_sign: i8,
119    /// The Hessian-determinant response.
120    pub response: f64,
121    /// The 64-element unit descriptor.
122    pub descriptor: Vec<f64>,
123}
124
125struct ResponseLayer {
126    filter: usize,
127    step: usize,
128    rows: usize,
129    cols: usize,
130    response: Array2<f64>,
131    laplacian: Array2<i8>,
132}
133
134impl ResponseLayer {
135    fn build(integral: &IntegralImage, filter: usize, step: usize) -> ResponseLayer {
136        let (rows, cols) = (integral.rows() / step, integral.cols() / step);
137        let (b, l) = ((filter as isize - 1) / 2, (filter / 3) as isize);
138        let w = filter;
139        let inv_area = 1.0 / (w * w) as f64;
140        let mut response = Array2::<f64>::zeros((rows, cols));
141        let mut laplacian = Array2::<i8>::zeros((rows, cols));
142        for ar in 0..rows {
143            for ac in 0..cols {
144                let (r, c) = ((ar * step) as isize, (ac * step) as isize);
145                let ls = l as usize;
146                // ANCHOR: box_hessian
147                let dxx = (integral.box_sum(r - l + 1, c - b, 2 * ls - 1, w) - 3.0 * integral.box_sum(r - l + 1, c - l / 2, 2 * ls - 1, ls)) * inv_area;
148                let dyy = (integral.box_sum(r - b, c - l + 1, w, 2 * ls - 1) - 3.0 * integral.box_sum(r - l / 2, c - l + 1, ls, 2 * ls - 1)) * inv_area;
149                let dxy = (integral.box_sum(r - l, c + 1, ls, ls) + integral.box_sum(r + 1, c - l, ls, ls) - integral.box_sum(r - l, c - l, ls, ls) - integral.box_sum(r + 1, c + 1, ls, ls)) * inv_area;
150                response[(ar, ac)] = dxx * dyy - 0.81 * dxy * dxy;
151                laplacian[(ar, ac)] = if dxx + dyy >= 0.0 { 1 } else { -1 };
152                // ANCHOR_END: box_hessian
153            }
154        }
155        ResponseLayer { filter, step, rows, cols, response, laplacian }
156    }
157}
158
159fn solve3(a: [[f64; 3]; 3], b: [f64; 3]) -> Option<[f64; 3]> {
160    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]);
161    let d = det(a);
162    if d.abs() < 1e-30 {
163        return None;
164    }
165    let mut x = [0.0; 3];
166    for (col, xc) in x.iter_mut().enumerate() {
167        let mut m = a;
168        for row in 0..3 {
169            m[row][col] = b[row];
170        }
171        *xc = det(m) / d;
172    }
173    Some(x)
174}
175
176/// Interpolated extremum position (in pixels) and scale of a response-layer maximum.
177fn interpolate(layers: [&ResponseLayer; 3], r: usize, c: usize) -> Option<(f64, f64, f64)> {
178    let [bot, mid, top] = layers;
179    let v = mid.response[(r, c)];
180    let g = [
181        (mid.response[(r, c + 1)] - mid.response[(r, c - 1)]) / 2.0,
182        (mid.response[(r + 1, c)] - mid.response[(r - 1, c)]) / 2.0,
183        (top.response[(r, c)] - bot.response[(r, c)]) / 2.0,
184    ];
185    let dxx = mid.response[(r, c + 1)] + mid.response[(r, c - 1)] - 2.0 * v;
186    let dyy = mid.response[(r + 1, c)] + mid.response[(r - 1, c)] - 2.0 * v;
187    let dss = top.response[(r, c)] + bot.response[(r, c)] - 2.0 * v;
188    let dxy = (mid.response[(r + 1, c + 1)] - mid.response[(r + 1, c - 1)] - mid.response[(r - 1, c + 1)] + mid.response[(r - 1, c - 1)]) / 4.0;
189    let dxs = (top.response[(r, c + 1)] - top.response[(r, c - 1)] - bot.response[(r, c + 1)] + bot.response[(r, c - 1)]) / 4.0;
190    let dys = (top.response[(r + 1, c)] - top.response[(r - 1, c)] - bot.response[(r + 1, c)] + bot.response[(r - 1, c)]) / 4.0;
191    let x = solve3([[dxx, dxy, dxs], [dxy, dyy, dys], [dxs, dys, dss]], [-g[0], -g[1], -g[2]])?;
192    if x.iter().all(|o| o.abs() < 1.0) {
193        let step = mid.step as f64;
194        let filter = mid.filter as f64 + x[2] * (mid.filter as f64 - bot.filter as f64);
195        Some(((c as f64 + x[0]) * step, (r as f64 + x[1]) * step, 1.2 / 9.0 * filter))
196    } else {
197        None
198    }
199}
200
201fn dominant_orientation(integral: &IntegralImage, x: f64, y: f64, scale: f64) -> f64 {
202    let (xi, yi, s) = (x.round() as isize, y.round() as isize, scale.round().max(1.0) as isize);
203    let size = (4.0 * scale).round().max(2.0) as usize;
204    let mut samples: Vec<(f64, f64, f64)> = Vec::new(); // (dx, dy, polar angle)
205    for i in -6isize..=6 {
206        for j in -6isize..=6 {
207            if i * i + j * j < 36 {
208                let weight = (-((i * i + j * j) as f64) / (2.0 * 2.5 * 2.5)).exp() / (2.0 * PI * 2.5 * 2.5).sqrt();
209                let (row, col) = (yi + j * s, xi + i * s);
210                let (dx, dy) = (weight * integral.haar_x(row, col, size), weight * integral.haar_y(row, col, size));
211                samples.push((dx, dy, dy.atan2(dx)));
212            }
213        }
214    }
215    let (mut best_len, mut best_angle) = (-1.0, 0.0);
216    let mut theta = 0.0;
217    while theta < TAU {
218        let (mut sx, mut sy) = (0.0, 0.0);
219        for &(dx, dy, ang) in &samples {
220            // Angular distance on the circle, window half-width pi/6.
221            let diff = (ang - theta + PI).rem_euclid(TAU) - PI;
222            if diff.abs() < PI / 6.0 {
223                sx += dx;
224                sy += dy;
225            }
226        }
227        let len = sx * sx + sy * sy;
228        if len > best_len {
229            best_len = len;
230            best_angle = sy.atan2(sx);
231        }
232        theta += 0.15;
233    }
234    best_angle.rem_euclid(TAU)
235}
236
237fn compute_descriptor(integral: &IntegralImage, x: f64, y: f64, scale: f64, orientation: f64) -> Vec<f64> {
238    let (cos_t, sin_t) = (orientation.cos(), orientation.sin());
239    let haar_size = (2.0 * scale).round().max(2.0) as usize;
240    let mut desc = Vec::with_capacity(64);
241    for sub_v in 0..4 {
242        for sub_u in 0..4 {
243            let (mut sdu, mut sdv, mut sadu, mut sadv) = (0.0, 0.0, 0.0, 0.0);
244            for v_idx in 0..5 {
245                for u_idx in 0..5 {
246                    // Sample position in the keypoint frame, in units of the scale: -10 .. +10.
247                    let u = (sub_u as f64 * 5.0 + u_idx as f64 - 9.5) * scale;
248                    let v = (sub_v as f64 * 5.0 + v_idx as f64 - 9.5) * scale;
249                    let px = x + u * cos_t - v * sin_t;
250                    let py = y + u * sin_t + v * cos_t;
251                    let (rx, ry) = (integral.haar_x(py.round() as isize, px.round() as isize, haar_size), integral.haar_y(py.round() as isize, px.round() as isize, haar_size));
252                    // Express the response in the keypoint frame and weight by a Gaussian about the centre.
253                    let (du, dv) = (rx * cos_t + ry * sin_t, -rx * sin_t + ry * cos_t);
254                    let r2 = (u / scale).powi(2) + (v / scale).powi(2);
255                    let w = (-r2 / (2.0 * 3.3 * 3.3)).exp();
256                    sdu += w * du;
257                    sdv += w * dv;
258                    sadu += w * du.abs();
259                    sadv += w * dv.abs();
260                }
261            }
262            desc.extend([sdu, sdv, sadu, sadv]);
263        }
264    }
265    let norm = desc.iter().map(|d| d * d).sum::<f64>().sqrt();
266    if norm > 1e-12 {
267        desc.iter_mut().for_each(|d| *d /= norm);
268    }
269    desc
270}
271
272/// Detects SURF keypoints and computes their descriptors.
273pub fn surf(image: &Array2<f64>, params: &SurfParams) -> Result<Vec<SurfKeypoint>, ErrorsJSL> {
274    if params.octaves < 1 || params.intervals < 3 || params.init_sample < 1 || !(params.threshold >= 0.0) {
275        return Err(ErrorsJSL::InvalidInputRange("Invalid SURF parameters"));
276    }
277    let (rows, cols) = image.dim();
278    if rows < 32 || cols < 32 {
279        return Err(ErrorsJSL::InvalidInputRange("Image must be at least 32x32"));
280    }
281    if image.iter().any(|v| !v.is_finite()) {
282        return Err(ErrorsJSL::InvalidInputRange("Image must be finite"));
283    }
284    let (lo, hi) = image.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(l, h), &v| (l.min(v), h.max(v)));
285    if hi - lo <= 0.0 {
286        return Ok(Vec::new());
287    }
288    let integral = IntegralImage::new(&image.mapv(|v| (v - lo) / (hi - lo)));
289
290    let mut keypoints = Vec::new();
291    let mut start = 9usize;
292    for o in 0..params.octaves {
293        let spacing = 6 * (1usize << o);
294        let step = params.init_sample * (1usize << o);
295        let filters: Vec<usize> = (0..params.intervals).map(|i| start + i * spacing).collect();
296        start += spacing;
297        if filters.last().is_none_or(|&f| f >= rows.min(cols)) {
298            break; // the filter would not fit in the image
299        }
300        let layers: Vec<ResponseLayer> = filters.iter().map(|&f| ResponseLayer::build(&integral, f, step)).collect();
301        for t in 1..layers.len() - 1 {
302            let (bot, mid, top) = (&layers[t - 1], &layers[t], &layers[t + 1]);
303            let border = top.filter.div_ceil(2) / step + 1;
304            for r in border..mid.rows.saturating_sub(border) {
305                for c in border..mid.cols.saturating_sub(border) {
306                    let v = mid.response[(r, c)];
307                    if v <= params.threshold {
308                        continue;
309                    }
310                    let mut is_max = true;
311                    'check: for (li, layer) in [bot, mid, top].iter().enumerate() {
312                        for dr in -1isize..=1 {
313                            for dc in -1isize..=1 {
314                                if li == 1 && dr == 0 && dc == 0 {
315                                    continue;
316                                }
317                                if layer.response[((r as isize + dr) as usize, (c as isize + dc) as usize)] >= v {
318                                    is_max = false;
319                                    break 'check;
320                                }
321                            }
322                        }
323                    }
324                    if !is_max {
325                        continue;
326                    }
327                    let Some((x, y, scale)) = interpolate([bot, mid, top], r, c) else { continue };
328                    let orientation = if params.upright { 0.0 } else { dominant_orientation(&integral, x, y, scale) };
329                    keypoints.push(SurfKeypoint {
330                        x,
331                        y,
332                        scale,
333                        orientation,
334                        laplacian_sign: mid.laplacian[(r, c)],
335                        response: v,
336                        descriptor: compute_descriptor(&integral, x, y, scale, orientation),
337                    });
338                }
339            }
340        }
341    }
342    Ok(keypoints)
343}
344
345#[cfg(test)]
346mod tests {
347    use super::*;
348    use crate::discrete::image::feature_extraction::match_descriptors;
349    use crate::discrete::image::filters::gaussian_blur::gaussian_blur;
350
351    fn texture(n: usize, seed0: u64) -> Array2<f64> {
352        let mut seed = seed0;
353        let noise = Array2::from_shape_fn((n, n), |_| {
354            seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
355            (seed >> 33) as f64 / (1u64 << 31) as f64
356        });
357        gaussian_blur(&noise, 2.0).unwrap()
358    }
359
360    fn descriptors(k: &[SurfKeypoint]) -> Vec<Vec<f64>> {
361        k.iter().map(|kp| kp.descriptor.clone()).collect()
362    }
363
364    fn dense() -> SurfParams {
365        SurfParams { init_sample: 1, ..SurfParams::default() }
366    }
367
368    #[test]
369    fn integral_image_box_sums_are_exact_including_clipped_boxes() {
370        let img = Array2::from_shape_fn((7, 9), |(r, c)| (r * 9 + c) as f64 + 1.0);
371        let ii = IntegralImage::new(&img);
372        let naive = |r0: isize, c0: isize, h: usize, w: usize| -> f64 {
373            let mut s = 0.0;
374            for r in r0..r0 + h as isize {
375                for c in c0..c0 + w as isize {
376                    if (0..7).contains(&r) && (0..9).contains(&c) {
377                        s += img[(r as usize, c as usize)];
378                    }
379                }
380            }
381            s
382        };
383        for (r0, c0, h, w) in [(0, 0, 7, 9), (2, 3, 3, 4), (-2, -3, 5, 6), (5, 7, 10, 10), (3, 3, 0, 4), (-5, -5, 2, 2)] {
384            assert!((ii.box_sum(r0, c0, h, w) - naive(r0, c0, h, w)).abs() < 1e-9, "box ({r0},{c0}) {h}x{w}");
385        }
386        assert_eq!((ii.rows(), ii.cols()), (7, 9));
387    }
388
389    #[test]
390    fn haar_responses_detect_the_direction_of_a_ramp() {
391        let ii = IntegralImage::new(&Array2::from_shape_fn((40, 40), |(r, c)| 2.0 * c as f64 + 1.0 * r as f64));
392        let (hx, hy) = (ii.haar_x(20, 20, 8), ii.haar_y(20, 20, 8));
393        assert!(hx > 0.0 && hy > 0.0 && hx > hy, "x gradient is twice the y gradient: {hx} {hy}");
394        assert!((hx / hy - 2.0).abs() < 1e-9);
395    }
396
397    #[test]
398    fn a_constant_image_has_no_features() {
399        assert!(surf(&Array2::from_elem((64, 64), 0.3), &SurfParams::default()).unwrap().is_empty());
400    }
401
402    #[test]
403    fn a_gaussian_blob_is_found_at_its_centre_with_a_matching_scale() {
404        let s = 6.0;
405        let img = Array2::from_shape_fn((100, 100), |(r, c)| (-((r as f64 - 50.0).powi(2) + (c as f64 - 50.0).powi(2)) / (2.0 * s * s)).exp());
406        let kps = surf(&img, &dense()).unwrap();
407        assert!(!kps.is_empty());
408        let best = kps.iter().max_by(|a, b| a.response.partial_cmp(&b.response).unwrap()).unwrap();
409        assert!((best.x - 50.0).abs() < 1.5 && (best.y - 50.0).abs() < 1.5, "({}, {})", best.x, best.y);
410        assert!((best.scale / s - 1.0).abs() < 0.4, "scale {} vs blob std {s}", best.scale);
411        assert_eq!(best.laplacian_sign, -1, "a bright blob has a negative Laplacian of intensity");
412        assert!((best.descriptor.iter().map(|v| v * v).sum::<f64>() - 1.0).abs() < 1e-9);
413    }
414
415    #[test]
416    fn descriptors_are_64_dimensional_unit_vectors() {
417        let kps = surf(&texture(128, 1), &SurfParams::default()).unwrap();
418        assert!(kps.len() > 20, "{} keypoints", kps.len());
419        for k in &kps {
420            assert_eq!(k.descriptor.len(), 64);
421            assert!((k.descriptor.iter().map(|v| v * v).sum::<f64>().sqrt() - 1.0).abs() < 1e-9);
422            assert!((0.0..TAU).contains(&k.orientation) && k.x >= 0.0 && k.y >= 0.0 && k.x < 128.0 && k.y < 128.0);
423            assert!(k.laplacian_sign == 1 || k.laplacian_sign == -1);
424        }
425        let upright = surf(&texture(128, 1), &SurfParams { upright: true, ..SurfParams::default() }).unwrap();
426        assert!(upright.iter().all(|k| k.orientation == 0.0));
427    }
428
429    #[test]
430    fn invariant_to_translation() {
431        let t = texture(176, 2);
432        let a = t.slice(ndarray::s![16..144, 16..144]).to_owned();
433        let b = t.slice(ndarray::s![23..151, 11..139]).to_owned();
434        let (ka, kb) = (surf(&a, &dense()).unwrap(), surf(&b, &dense()).unwrap());
435        let matches = match_descriptors(&descriptors(&ka), &descriptors(&kb), 0.8, true).unwrap();
436        assert!(matches.len() >= 12, "only {} matches from {} and {} keypoints", matches.len(), ka.len(), kb.len());
437        let consistent = matches.iter().filter(|m| (kb[m.index_b].x - ka[m.index_a].x - 5.0).abs() < 2.0 && (kb[m.index_b].y - ka[m.index_a].y + 7.0).abs() < 2.0).count();
438        assert!(consistent as f64 >= 0.8 * matches.len() as f64, "{consistent} of {} follow the shift", matches.len());
439    }
440
441    #[test]
442    fn invariant_to_a_quarter_turn_rotation() {
443        let n = 128;
444        let a = texture(n, 3);
445        let b = Array2::from_shape_fn((n, n), |(r, c)| a[(c, n - 1 - r)]);
446        let (ka, kb) = (surf(&a, &dense()).unwrap(), surf(&b, &dense()).unwrap());
447        let matches = match_descriptors(&descriptors(&ka), &descriptors(&kb), 0.8, true).unwrap();
448        assert!(matches.len() >= 12, "only {} matches from {} and {} keypoints", matches.len(), ka.len(), kb.len());
449        let positional = matches.iter().filter(|m| (kb[m.index_b].x - ka[m.index_a].y).abs() < 2.5 && (kb[m.index_b].y - (n as f64 - 1.0 - ka[m.index_a].x)).abs() < 2.5).count();
450        assert!(positional as f64 >= 0.8 * matches.len() as f64, "{positional} of {} map correctly", matches.len());
451        // Matching keypoints keep their Laplacian sign.
452        assert!(matches.iter().filter(|m| ka[m.index_a].laplacian_sign == kb[m.index_b].laplacian_sign).count() as f64 >= 0.9 * matches.len() as f64);
453    }
454
455    #[test]
456    fn invariant_to_contrast_changes_because_the_image_is_normalised() {
457        let a = texture(128, 4);
458        let b = a.mapv(|v| 0.4 * v + 0.3);
459        let (ka, kb) = (surf(&a, &SurfParams::default()).unwrap(), surf(&b, &SurfParams::default()).unwrap());
460        assert_eq!(ka.len(), kb.len());
461        let matches = match_descriptors(&descriptors(&ka), &descriptors(&kb), 0.8, true).unwrap();
462        assert!(matches.len() as f64 >= 0.9 * ka.len() as f64);
463        assert!(matches.iter().all(|m| m.distance < 1e-6));
464    }
465
466    #[test]
467    fn a_higher_threshold_keeps_fewer_keypoints() {
468        let t = texture(128, 5);
469        let base = surf(&t, &SurfParams::default()).unwrap().len();
470        let strict = surf(&t, &SurfParams { threshold: 4e-3, ..SurfParams::default() }).unwrap().len();
471        assert!(strict < base, "{strict} vs {base}");
472    }
473
474    #[test]
475    fn invalid_inputs() {
476        assert!(surf(&Array2::<f64>::zeros((20, 64)), &SurfParams::default()).is_err());
477        let mut img = texture(64, 6);
478        img[(2, 2)] = f64::INFINITY;
479        assert!(surf(&img, &SurfParams::default()).is_err());
480        let ok = texture(64, 6);
481        assert!(surf(&ok, &SurfParams { octaves: 0, ..SurfParams::default() }).is_err());
482        assert!(surf(&ok, &SurfParams { intervals: 2, ..SurfParams::default() }).is_err());
483        assert!(surf(&ok, &SurfParams { init_sample: 0, ..SurfParams::default() }).is_err());
484        assert!(surf(&ok, &SurfParams { threshold: -1.0, ..SurfParams::default() }).is_err());
485    }
486}