Skip to main content

visloc_vision/features/
deep.rs

1//! Deep-style feature frontend (SuperPoint/DISK-compatible interface).
2//!
3//! This module defines the [`DeepFeatureExtractor`] trait and a
4//! classical-but-deep-shaped implementation, [`HogLikeFeatureExtractor`].
5//!
6//! `HogLikeFeatureExtractor` is *not* a learned model. It mimics the output
7//! contract of SuperPoint/DISK so that downstream code (matchers, two-view
8//! geometry, SLAM frontends) can be wired against the deep interface without
9//! requiring a heavy ML runtime today. Once an ONNX/Candle backend is
10//! available, only the extractor implementation needs to swap.
11//!
12//! Design highlights:
13//!   * 16x16 oriented gradient patch divided into 4x4 cells, 8 orientation
14//!     bins per cell -> 128-D descriptor (SIFT/HOG family).
15//!   * L2-normalize, clip at 0.2, re-normalize (Lowe's recipe). The result is
16//!     a unit-norm vector so cosine similarity equals inner product, which is
17//!     what the [`super::super::matching::mutual_softmax`] matcher expects.
18//!   * Per-keypoint score is the corner-response magnitude scaled into [0, 1]
19//!     to mirror SuperPoint's per-pixel score map.
20
21use super::{
22    CornerFeatureExtractor, FeatureExtractor, FeatureSet, FeatureSetError, GrayscaleImage,
23};
24use nalgebra::Point2;
25use std::fmt;
26
27/// Output of a deep-style feature extractor: keypoints, scores, and unit-norm
28/// descriptors. Convertible to [`FeatureSet`] via [`DeepFeatureSet::into_feature_set`]
29/// for use with classical matchers.
30#[derive(Debug, Clone, PartialEq)]
31pub struct DeepFeatureSet {
32    pub keypoints: Vec<Point2<f64>>,
33    pub scores: Vec<f32>,
34    pub descriptors: Vec<Vec<f32>>,
35}
36
37impl DeepFeatureSet {
38    pub fn new(
39        keypoints: Vec<Point2<f64>>,
40        scores: Vec<f32>,
41        descriptors: Vec<Vec<f32>>,
42    ) -> Result<Self, DeepFeatureSetError> {
43        if keypoints.len() != scores.len() {
44            return Err(DeepFeatureSetError::ScoreCountMismatch {
45                keypoint_count: keypoints.len(),
46                score_count: scores.len(),
47            });
48        }
49        if keypoints.len() != descriptors.len() {
50            return Err(DeepFeatureSetError::FeatureSet(
51                FeatureSetError::ShapeMismatch {
52                    keypoint_count: keypoints.len(),
53                    descriptor_count: descriptors.len(),
54                },
55            ));
56        }
57        if let Some(first) = descriptors.first() {
58            for (index, descriptor) in descriptors.iter().enumerate() {
59                if descriptor.len() != first.len() {
60                    return Err(DeepFeatureSetError::FeatureSet(
61                        FeatureSetError::DescriptorDimensionMismatch {
62                            descriptor_index: index,
63                            expected_dimension: first.len(),
64                            actual_dimension: descriptor.len(),
65                        },
66                    ));
67                }
68            }
69        }
70        Ok(Self {
71            keypoints,
72            scores,
73            descriptors,
74        })
75    }
76
77    pub fn len(&self) -> usize {
78        self.keypoints.len()
79    }
80
81    pub fn is_empty(&self) -> bool {
82        self.keypoints.is_empty()
83    }
84
85    /// Drop the per-keypoint score and produce a [`FeatureSet`] usable by any
86    /// classical [`super::super::matching::Matcher`] implementation.
87    pub fn into_feature_set(self) -> FeatureSet {
88        FeatureSet {
89            keypoints: self.keypoints,
90            descriptors: self.descriptors,
91        }
92    }
93
94    pub fn as_feature_set(&self) -> FeatureSet {
95        FeatureSet {
96            keypoints: self.keypoints.clone(),
97            descriptors: self.descriptors.clone(),
98        }
99    }
100}
101
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub enum DeepFeatureSetError {
104    ScoreCountMismatch {
105        keypoint_count: usize,
106        score_count: usize,
107    },
108    FeatureSet(FeatureSetError),
109}
110
111impl fmt::Display for DeepFeatureSetError {
112    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
113        match self {
114            Self::ScoreCountMismatch {
115                keypoint_count,
116                score_count,
117            } => write!(
118                formatter,
119                "deep feature score count {score_count} does not match keypoint count {keypoint_count}"
120            ),
121            Self::FeatureSet(error) => write!(formatter, "{error}"),
122        }
123    }
124}
125
126impl std::error::Error for DeepFeatureSetError {}
127
128impl From<FeatureSetError> for DeepFeatureSetError {
129    fn from(error: FeatureSetError) -> Self {
130        Self::FeatureSet(error)
131    }
132}
133
134/// Deep-style frontend trait: produces keypoints with per-feature scores and
135/// unit-norm descriptors. Mirrors the output contract of SuperPoint/DISK so an
136/// ONNX-backed implementation can drop in later without touching consumers.
137pub trait DeepFeatureExtractor {
138    type Image;
139    type Error;
140
141    fn extract_deep(&self, image: &Self::Image) -> Result<DeepFeatureSet, Self::Error>;
142}
143
144/// Number of orientation bins per HOG cell.
145pub const HOG_BINS: usize = 8;
146/// Number of cells per side (final descriptor is `CELLS_PER_SIDE^2 * HOG_BINS`).
147pub const HOG_CELLS_PER_SIDE: usize = 4;
148/// Pixels per cell side. Patch side is `HOG_CELLS_PER_SIDE * HOG_CELL_SIZE`.
149pub const HOG_CELL_SIZE: usize = 4;
150/// Total descriptor dimension.
151pub const HOG_DESCRIPTOR_DIM: usize = HOG_CELLS_PER_SIDE * HOG_CELLS_PER_SIDE * HOG_BINS;
152
153/// Configuration for [`HogLikeFeatureExtractor`].
154#[derive(Debug, Clone, PartialEq)]
155pub struct HogLikeFeatureConfig {
156    /// Maximum number of features kept after non-max suppression / scoring.
157    pub max_features: usize,
158    /// Minimum corner response. Lower = more candidates.
159    pub min_corner_score: f32,
160    /// Lowe-style descriptor clip threshold (applied after first L2 norm).
161    pub descriptor_clip: f32,
162    /// Compute a dominant gradient orientation per keypoint and bin the
163    /// HOG descriptor in that rotated frame, making the descriptor
164    /// invariant to in-plane camera rotation (SIFT-style oriented
165    /// descriptor). Defaults to `false` — for forward-driving / static-
166    /// up camera setups (KITTI etc.) the per-keypoint dominant
167    /// orientation estimate adds variance without providing real
168    /// invariance, so the axis-aligned histogram matches better. Enable
169    /// it for handheld / rotation-heavy use cases (UAV, cellphone, etc.)
170    /// where in-plane rotation between views is a real failure mode.
171    pub orient: bool,
172}
173
174impl Default for HogLikeFeatureConfig {
175    fn default() -> Self {
176        Self {
177            max_features: 512,
178            min_corner_score: 0.05,
179            descriptor_clip: 0.2,
180            orient: false,
181        }
182    }
183}
184
185/// Deep-style feature extractor with classical SIFT/HOG-flavored descriptors.
186/// Output descriptors are unit-norm 128-D vectors so they pair directly with
187/// cosine-similarity matchers (e.g.
188/// [`super::super::matching::mutual_softmax::MutualSoftmaxMatcher`]).
189#[derive(Debug, Clone, PartialEq)]
190pub struct HogLikeFeatureExtractor {
191    pub config: HogLikeFeatureConfig,
192}
193
194impl HogLikeFeatureExtractor {
195    pub const fn new(config: HogLikeFeatureConfig) -> Self {
196        Self { config }
197    }
198
199    const fn patch_radius() -> usize {
200        HOG_CELLS_PER_SIDE * HOG_CELL_SIZE / 2
201    }
202
203    fn detect_keypoints(&self, image: &GrayscaleImage) -> Vec<(f32, usize, usize)> {
204        let margin = Self::patch_radius() + 1;
205        let mut candidates = Vec::new();
206        if image.width() <= margin * 2 || image.height() <= margin * 2 {
207            return candidates;
208        }
209        for y in margin..(image.height() - margin) {
210            for x in margin..(image.width() - margin) {
211                let score = corner_response(image, x, y);
212                if score < self.config.min_corner_score {
213                    continue;
214                }
215                if is_local_maximum_3x3(image, x, y, score) {
216                    candidates.push((score, x, y));
217                }
218            }
219        }
220        candidates.sort_by(|left, right| {
221            right
222                .0
223                .total_cmp(&left.0)
224                .then_with(|| left.2.cmp(&right.2))
225                .then_with(|| left.1.cmp(&right.1))
226        });
227        candidates.truncate(self.config.max_features);
228        candidates
229    }
230
231    /// Compute the L2-normalised HOG descriptor centred at the integer
232    /// pixel `(cx, cy)`. Useful when callers already know where they
233    /// want descriptors (e.g. anchoring on COLMAP-detected keypoint
234    /// locations) and want to skip the corner detector. Returns
235    /// `None` when the centre is too close to the image border for a
236    /// well-defined descriptor patch.
237    pub fn describe_at(&self, image: &GrayscaleImage, cx: usize, cy: usize) -> Option<Vec<f32>> {
238        let margin = Self::patch_radius() + 1;
239        if cx < margin
240            || cy < margin
241            || cx + margin >= image.width()
242            || cy + margin >= image.height()
243        {
244            return None;
245        }
246        Some(self.descriptor_at(image, cx, cy))
247    }
248
249    fn descriptor_at(&self, image: &GrayscaleImage, cx: usize, cy: usize) -> Vec<f32> {
250        let radius = Self::patch_radius();
251        let patch_side = HOG_CELLS_PER_SIDE * HOG_CELL_SIZE;
252        let mut histogram = vec![0.0_f32; HOG_DESCRIPTOR_DIM];
253        let bin_width = std::f32::consts::TAU / HOG_BINS as f32;
254
255        // Dominant gradient orientation in radians. atan2-shifted to [0, TAU).
256        // When `orient` is false this stays at 0.0 and the descriptor is
257        // axis-aligned (the previous behaviour).
258        let theta = if self.config.orient {
259            dominant_orientation(image, cx, cy, radius)
260        } else {
261            0.0
262        };
263        let cos_theta = theta.cos();
264        let sin_theta = theta.sin();
265
266        for py in 0..patch_side {
267            for px in 0..patch_side {
268                // Patch-local coordinates centred at the patch midpoint.
269                let lx = (px as f32) - (radius as f32) + 0.5;
270                let ly = (py as f32) - (radius as f32) + 0.5;
271                // Rotate to image-frame offset.
272                let dx = cos_theta * lx - sin_theta * ly;
273                let dy = sin_theta * lx + cos_theta * ly;
274                let sx = (cx as f32) + dx;
275                let sy = (cy as f32) + dy;
276
277                // Central differences sampled bilinearly so rotated patches
278                // do not snap to pixel grid.
279                let gx_image =
280                    bilinear_sample(image, sx + 1.0, sy) - bilinear_sample(image, sx - 1.0, sy);
281                let gy_image =
282                    bilinear_sample(image, sx, sy + 1.0) - bilinear_sample(image, sx, sy - 1.0);
283                // Rotate the gradient vector back into the patch frame so
284                // the orientation histogram is bound to the keypoint's
285                // intrinsic frame.
286                let lgx = cos_theta * gx_image + sin_theta * gy_image;
287                let lgy = -sin_theta * gx_image + cos_theta * gy_image;
288
289                let magnitude = (lgx * lgx + lgy * lgy).sqrt();
290                if magnitude == 0.0 {
291                    continue;
292                }
293                let mut angle = lgy.atan2(lgx);
294                if angle < 0.0 {
295                    angle += std::f32::consts::TAU;
296                }
297                let bin_index = (angle / bin_width).floor() as usize % HOG_BINS;
298                let cell_x = px / HOG_CELL_SIZE;
299                let cell_y = py / HOG_CELL_SIZE;
300                let cell_index = cell_y * HOG_CELLS_PER_SIDE + cell_x;
301                histogram[cell_index * HOG_BINS + bin_index] += magnitude;
302            }
303        }
304        normalize_descriptor(&mut histogram, self.config.descriptor_clip);
305        histogram
306    }
307
308    fn keypoint_score(&self, raw_score: f32, max_score: f32) -> f32 {
309        if max_score <= 0.0 {
310            0.0
311        } else {
312            (raw_score / max_score).clamp(0.0, 1.0)
313        }
314    }
315}
316
317impl Default for HogLikeFeatureExtractor {
318    fn default() -> Self {
319        Self::new(HogLikeFeatureConfig::default())
320    }
321}
322
323#[derive(Debug, Clone, PartialEq, Eq)]
324pub enum HogLikeFeatureError {
325    ImageTooSmall {
326        width: usize,
327        height: usize,
328        required_margin: usize,
329    },
330    DeepFeatureSet(DeepFeatureSetError),
331}
332
333impl fmt::Display for HogLikeFeatureError {
334    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
335        match self {
336            Self::ImageTooSmall {
337                width,
338                height,
339                required_margin,
340            } => write!(
341                formatter,
342                "image {width}x{height} is too small for deep feature extraction with margin {required_margin}"
343            ),
344            Self::DeepFeatureSet(error) => write!(formatter, "{error}"),
345        }
346    }
347}
348
349impl std::error::Error for HogLikeFeatureError {}
350
351impl From<DeepFeatureSetError> for HogLikeFeatureError {
352    fn from(error: DeepFeatureSetError) -> Self {
353        Self::DeepFeatureSet(error)
354    }
355}
356
357impl DeepFeatureExtractor for HogLikeFeatureExtractor {
358    type Image = GrayscaleImage;
359    type Error = HogLikeFeatureError;
360
361    fn extract_deep(&self, image: &Self::Image) -> Result<DeepFeatureSet, Self::Error> {
362        let margin = Self::patch_radius() + 1;
363        if image.width() <= margin * 2 || image.height() <= margin * 2 {
364            return Err(HogLikeFeatureError::ImageTooSmall {
365                width: image.width(),
366                height: image.height(),
367                required_margin: margin,
368            });
369        }
370
371        let candidates = self.detect_keypoints(image);
372        let max_score = candidates.first().map_or(0.0, |c| c.0);
373
374        let mut keypoints = Vec::with_capacity(candidates.len());
375        let mut scores = Vec::with_capacity(candidates.len());
376        let mut descriptors = Vec::with_capacity(candidates.len());
377
378        for (raw_score, x, y) in candidates {
379            keypoints.push(Point2::new(x as f64, y as f64));
380            scores.push(self.keypoint_score(raw_score, max_score));
381            descriptors.push(self.descriptor_at(image, x, y));
382        }
383
384        DeepFeatureSet::new(keypoints, scores, descriptors).map_err(HogLikeFeatureError::from)
385    }
386}
387
388/// Bridge to the classical [`FeatureExtractor`] trait so the deep extractor
389/// can be plugged into any consumer that already accepts a [`FeatureSet`].
390impl FeatureExtractor for HogLikeFeatureExtractor {
391    type Image = GrayscaleImage;
392    type Error = HogLikeFeatureError;
393
394    fn extract(&self, image: &Self::Image) -> Result<FeatureSet, Self::Error> {
395        Ok(self.extract_deep(image)?.into_feature_set())
396    }
397}
398
399/// Adapter that exposes any [`CornerFeatureExtractor`] through the deep
400/// interface, using the (already L2-clippable) patch descriptor and a
401/// constant score. Useful for A/B testing the deep contract while keeping the
402/// classical extractor untouched.
403#[derive(Debug, Clone, PartialEq)]
404pub struct CornerDeepAdapter {
405    pub inner: CornerFeatureExtractor,
406}
407
408impl CornerDeepAdapter {
409    pub const fn new(inner: CornerFeatureExtractor) -> Self {
410        Self { inner }
411    }
412}
413
414impl DeepFeatureExtractor for CornerDeepAdapter {
415    type Image = GrayscaleImage;
416    type Error = super::CornerFeatureError;
417
418    fn extract_deep(&self, image: &Self::Image) -> Result<DeepFeatureSet, Self::Error> {
419        let features = self.inner.extract(image)?;
420        let scores = vec![1.0_f32; features.len()];
421        DeepFeatureSet::new(features.keypoints, scores, features.descriptors).map_err(|error| {
422            match error {
423                DeepFeatureSetError::FeatureSet(inner) => super::CornerFeatureError::from(inner),
424                DeepFeatureSetError::ScoreCountMismatch { .. } => {
425                    // Cannot happen: scores constructed from features.len().
426                    unreachable!("score length is taken from features.len()")
427                }
428            }
429        })
430    }
431}
432
433/// Build a 2× downsampled image pyramid by averaging 2×2 pixel blocks. Each
434/// successive level is half the width and half the height of the previous
435/// one. The averaging is a coarse low-pass filter that suffices for
436/// keypoint detection at coarser scales — Gaussian smoothing would be more
437/// faithful but adds a separable convolution this crate doesn't currently
438/// need elsewhere. The first element of the returned `Vec` is the input
439/// image at scale `1.0`, the second is at `0.5`, etc. Levels stop when
440/// further downsampling would drop one of the dimensions to zero.
441pub fn build_pyramid(image: &GrayscaleImage, levels: usize) -> Vec<GrayscaleImage> {
442    let mut pyramid = Vec::with_capacity(levels.max(1));
443    pyramid.push(image.clone());
444    for _ in 1..levels {
445        let prev = pyramid.last().unwrap();
446        let next_w = prev.width() / 2;
447        let next_h = prev.height() / 2;
448        if next_w == 0 || next_h == 0 {
449            break;
450        }
451        let mut downsampled = vec![0.0_f32; next_w * next_h];
452        for y in 0..next_h {
453            for x in 0..next_w {
454                let sx = x * 2;
455                let sy = y * 2;
456                let p00 = prev.get(sx, sy).unwrap_or(0.0);
457                let p10 = prev.get(sx + 1, sy).unwrap_or(p00);
458                let p01 = prev.get(sx, sy + 1).unwrap_or(p00);
459                let p11 = prev.get(sx + 1, sy + 1).unwrap_or(p00);
460                downsampled[y * next_w + x] = 0.25 * (p00 + p10 + p01 + p11);
461            }
462        }
463        pyramid.push(
464            GrayscaleImage::new(next_w, next_h, downsampled)
465                .expect("downsampled dimensions are non-zero"),
466        );
467    }
468    pyramid
469}
470
471/// Configuration for [`MultiScaleDeepExtractor`].
472#[derive(Debug, Clone, PartialEq)]
473pub struct MultiScaleDeepConfig {
474    /// Number of pyramid octaves (including the original image at scale
475    /// 1.0). Defaults to 3 (1.0 / 0.5 / 0.25). Each additional octave
476    /// roughly doubles the runtime cost while halving the world-space size
477    /// of the smallest detectable corner.
478    pub octaves: usize,
479    /// If `true`, clamp the per-octave keypoint count proportional to the
480    /// octave's pixel area so coarse octaves do not dominate the merged set.
481    /// Disabled by default — the inner extractor's own `max_features` cap
482    /// already controls the per-octave budget.
483    pub area_weighted_octave_cap: bool,
484}
485
486impl Default for MultiScaleDeepConfig {
487    fn default() -> Self {
488        Self {
489            octaves: 3,
490            area_weighted_octave_cap: false,
491        }
492    }
493}
494
495/// Wraps a single-scale [`DeepFeatureExtractor`] with image pyramid
496/// detection so it can recover features across multiple scales. Each
497/// keypoint produced by an octave is rescaled into the original image's
498/// pixel coordinates, so downstream consumers (essential RANSAC, PnP,
499/// scanner) can treat the merged output exactly like a single-scale
500/// extraction. The descriptor itself is unchanged from the inner
501/// extractor's output: at coarser octaves the descriptor patch covers a
502/// larger world-space region, which is exactly the scale invariance
503/// classical multi-scale frontends rely on.
504#[derive(Debug, Clone, PartialEq)]
505pub struct MultiScaleDeepExtractor<E> {
506    pub inner: E,
507    pub config: MultiScaleDeepConfig,
508}
509
510impl<E> MultiScaleDeepExtractor<E> {
511    pub const fn new(inner: E, config: MultiScaleDeepConfig) -> Self {
512        Self { inner, config }
513    }
514}
515
516impl MultiScaleDeepExtractor<HogLikeFeatureExtractor> {
517    /// Compute HOG descriptors at a caller-specified keypoint across the
518    /// configured image pyramid. Returned descriptors are ordered from
519    /// finest to coarsest octave. This is useful when a caller wants
520    /// multi-scale descriptors anchored to an external detector's keypoint
521    /// locations, such as COLMAP SIFT keypoints.
522    pub fn describe_at(&self, image: &GrayscaleImage, cx: usize, cy: usize) -> Vec<Vec<f32>> {
523        let octaves = self.config.octaves.max(1);
524        let pyramid = build_pyramid(image, octaves);
525        let mut descriptors = Vec::new();
526
527        for (octave, level_image) in pyramid.iter().enumerate() {
528            let scale = 1usize << octave;
529            let level_cx = cx / scale;
530            let level_cy = cy / scale;
531            if let Some(descriptor) = self.inner.describe_at(level_image, level_cx, level_cy) {
532                descriptors.push(descriptor);
533            }
534        }
535
536        descriptors
537    }
538}
539
540impl<E> Default for MultiScaleDeepExtractor<E>
541where
542    E: Default,
543{
544    fn default() -> Self {
545        Self {
546            inner: E::default(),
547            config: MultiScaleDeepConfig::default(),
548        }
549    }
550}
551
552impl<E> DeepFeatureExtractor for MultiScaleDeepExtractor<E>
553where
554    E: DeepFeatureExtractor<Image = GrayscaleImage>,
555{
556    type Image = GrayscaleImage;
557    type Error = E::Error;
558
559    fn extract_deep(&self, image: &Self::Image) -> Result<DeepFeatureSet, Self::Error> {
560        let octaves = self.config.octaves.max(1);
561        let pyramid = build_pyramid(image, octaves);
562
563        let mut keypoints = Vec::new();
564        let mut scores = Vec::new();
565        let mut descriptors = Vec::new();
566
567        for (octave, level_image) in pyramid.iter().enumerate() {
568            // Skip octaves where the inner extractor's image-too-small
569            // failure would fire — we just take what fits and let the
570            // remaining octaves contribute nothing rather than aborting.
571            let result = self.inner.extract_deep(level_image);
572            let octave_features = match result {
573                Ok(features) => features,
574                Err(_) if octave > 0 => continue,
575                Err(error) => return Err(error),
576            };
577            let scale = (1u32 << octave) as f64;
578            for (kp, (score, descriptor)) in octave_features.keypoints.into_iter().zip(
579                octave_features
580                    .scores
581                    .into_iter()
582                    .zip(octave_features.descriptors),
583            ) {
584                let rescaled = Point2::new(kp.x * scale, kp.y * scale);
585                keypoints.push(rescaled);
586                scores.push(score);
587                descriptors.push(descriptor);
588            }
589        }
590
591        Ok(DeepFeatureSet {
592            keypoints,
593            scores,
594            descriptors,
595        })
596    }
597}
598
599/// Bridge to the classical [`FeatureExtractor`] trait — drops the per-
600/// keypoint score and yields a [`FeatureSet`] for any consumer that does
601/// not yet consume the deep interface.
602impl<E> FeatureExtractor for MultiScaleDeepExtractor<E>
603where
604    E: DeepFeatureExtractor<Image = GrayscaleImage>,
605{
606    type Image = GrayscaleImage;
607    type Error = E::Error;
608
609    fn extract(&self, image: &Self::Image) -> Result<FeatureSet, Self::Error> {
610        Ok(self.extract_deep(image)?.into_feature_set())
611    }
612}
613
614fn normalize_descriptor(descriptor: &mut [f32], clip: f32) {
615    let norm = descriptor
616        .iter()
617        .map(|value| value * value)
618        .sum::<f32>()
619        .sqrt();
620    if norm > 0.0 {
621        for value in descriptor.iter_mut() {
622            *value /= norm;
623        }
624    }
625    if clip > 0.0 && clip < 1.0 {
626        for value in descriptor.iter_mut() {
627            if *value > clip {
628                *value = clip;
629            }
630        }
631        let renorm = descriptor
632            .iter()
633            .map(|value| value * value)
634            .sum::<f32>()
635            .sqrt();
636        if renorm > 0.0 {
637            for value in descriptor.iter_mut() {
638                *value /= renorm;
639            }
640        }
641    }
642}
643
644fn corner_response(image: &GrayscaleImage, x: usize, y: usize) -> f32 {
645    let center = image.get(x, y).unwrap_or(0.0);
646    let _ = center;
647    let dx = image.get(x + 1, y).unwrap_or(0.0) - image.get(x - 1, y).unwrap_or(0.0);
648    let dy = image.get(x, y + 1).unwrap_or(0.0) - image.get(x, y - 1).unwrap_or(0.0);
649    let dxy1 = image.get(x + 1, y + 1).unwrap_or(0.0) - image.get(x - 1, y - 1).unwrap_or(0.0);
650    let dxy2 = image.get(x + 1, y - 1).unwrap_or(0.0) - image.get(x - 1, y + 1).unwrap_or(0.0);
651    (dx * dx + dy * dy + 0.5 * (dxy1 * dxy1 + dxy2 * dxy2)).sqrt()
652}
653
654/// Bilinear sample of a [`GrayscaleImage`] at fractional pixel coordinates.
655/// Out-of-bounds samples replicate the nearest edge pixel. Returns 0.0 when
656/// the image is empty.
657fn bilinear_sample(image: &GrayscaleImage, x: f32, y: f32) -> f32 {
658    if image.width() == 0 || image.height() == 0 {
659        return 0.0;
660    }
661    let xc = x.clamp(0.0, (image.width() - 1) as f32);
662    let yc = y.clamp(0.0, (image.height() - 1) as f32);
663    let x0 = xc.floor() as usize;
664    let y0 = yc.floor() as usize;
665    let x1 = (x0 + 1).min(image.width() - 1);
666    let y1 = (y0 + 1).min(image.height() - 1);
667    let fx = xc - x0 as f32;
668    let fy = yc - y0 as f32;
669    let p00 = image.get(x0, y0).unwrap_or(0.0);
670    let p10 = image.get(x1, y0).unwrap_or(p00);
671    let p01 = image.get(x0, y1).unwrap_or(p00);
672    let p11 = image.get(x1, y1).unwrap_or(p00);
673    let top = p00 * (1.0 - fx) + p10 * fx;
674    let bottom = p01 * (1.0 - fx) + p11 * fx;
675    top * (1.0 - fy) + bottom * fy
676}
677
678/// Dominant gradient orientation for a keypoint, computed from a circular
679/// window of radius `radius` around `(cx, cy)` via a 36-bin gradient
680/// orientation histogram weighted by gradient magnitude (SIFT-style).
681/// Returns the angle in radians in `[0, 2π)`.
682fn dominant_orientation(image: &GrayscaleImage, cx: usize, cy: usize, radius: usize) -> f32 {
683    const ORIENTATION_BINS: usize = 36;
684    let bin_width = std::f32::consts::TAU / ORIENTATION_BINS as f32;
685    let mut histogram = [0.0_f32; ORIENTATION_BINS];
686
687    let r = radius as i32;
688    for dy in -r..=r {
689        for dx in -r..=r {
690            if dx * dx + dy * dy > r * r {
691                continue;
692            }
693            let ix = cx as i32 + dx;
694            let iy = cy as i32 + dy;
695            if ix <= 0
696                || iy <= 0
697                || ix + 1 >= image.width() as i32
698                || iy + 1 >= image.height() as i32
699            {
700                continue;
701            }
702            let ix = ix as usize;
703            let iy = iy as usize;
704            let gx = image.get(ix + 1, iy).unwrap_or(0.0) - image.get(ix - 1, iy).unwrap_or(0.0);
705            let gy = image.get(ix, iy + 1).unwrap_or(0.0) - image.get(ix, iy - 1).unwrap_or(0.0);
706            let magnitude = (gx * gx + gy * gy).sqrt();
707            if magnitude == 0.0 {
708                continue;
709            }
710            let mut angle = gy.atan2(gx);
711            if angle < 0.0 {
712                angle += std::f32::consts::TAU;
713            }
714            let bin = ((angle / bin_width).floor() as usize) % ORIENTATION_BINS;
715            histogram[bin] += magnitude;
716        }
717    }
718
719    let (peak_bin, _) = histogram.iter().enumerate().fold(
720        (0_usize, 0.0_f32),
721        |(best_bin, best_val), (bin, &val)| {
722            if val > best_val {
723                (bin, val)
724            } else {
725                (best_bin, best_val)
726            }
727        },
728    );
729    // Parabolic interpolation around the peak for sub-bin accuracy.
730    let prev = histogram[(peak_bin + ORIENTATION_BINS - 1) % ORIENTATION_BINS];
731    let curr = histogram[peak_bin];
732    let next = histogram[(peak_bin + 1) % ORIENTATION_BINS];
733    let denom = prev - 2.0 * curr + next;
734    let sub_bin = if denom.abs() > 1.0e-6 {
735        0.5 * (prev - next) / denom
736    } else {
737        0.0
738    };
739    let bin_value = peak_bin as f32 + sub_bin;
740    let mut angle = bin_value * bin_width;
741    if angle < 0.0 {
742        angle += std::f32::consts::TAU;
743    }
744    if angle >= std::f32::consts::TAU {
745        angle -= std::f32::consts::TAU;
746    }
747    angle
748}
749
750fn is_local_maximum_3x3(image: &GrayscaleImage, x: usize, y: usize, score: f32) -> bool {
751    for ny in (y.saturating_sub(1))..=(y + 1) {
752        for nx in (x.saturating_sub(1))..=(x + 1) {
753            if nx == x && ny == y {
754                continue;
755            }
756            if nx == 0 || ny == 0 || nx + 1 >= image.width() || ny + 1 >= image.height() {
757                continue;
758            }
759            if corner_response(image, nx, ny) > score {
760                return false;
761            }
762        }
763    }
764    true
765}
766
767#[cfg(test)]
768mod tests {
769    use super::*;
770
771    fn checkerboard_image(side: usize) -> GrayscaleImage {
772        let mut pixels = vec![0_u8; side * side];
773        let block = 4;
774        for y in 0..side {
775            for x in 0..side {
776                let on = ((x / block) + (y / block)) % 2 == 0;
777                pixels[y * side + x] = if on { 220 } else { 35 };
778            }
779        }
780        GrayscaleImage::from_luma_u8(side, side, pixels).unwrap()
781    }
782
783    #[test]
784    fn deep_feature_set_validates_lengths() {
785        let err = DeepFeatureSet::new(
786            vec![Point2::new(0.0, 0.0), Point2::new(1.0, 0.0)],
787            vec![0.5],
788            vec![vec![1.0; HOG_DESCRIPTOR_DIM]; 2],
789        )
790        .unwrap_err();
791        assert!(matches!(
792            err,
793            DeepFeatureSetError::ScoreCountMismatch { .. }
794        ));
795    }
796
797    #[test]
798    fn hog_extractor_emits_unit_norm_descriptors_on_synthetic_pattern() {
799        let image = checkerboard_image(48);
800        let extractor = HogLikeFeatureExtractor::new(HogLikeFeatureConfig {
801            max_features: 32,
802            min_corner_score: 0.1,
803            descriptor_clip: 0.2,
804            orient: true,
805        });
806        let features = extractor.extract_deep(&image).unwrap();
807        assert!(
808            !features.is_empty(),
809            "checkerboard should produce keypoints"
810        );
811        for descriptor in &features.descriptors {
812            assert_eq!(descriptor.len(), HOG_DESCRIPTOR_DIM);
813            let norm = descriptor.iter().map(|v| v * v).sum::<f32>().sqrt();
814            assert!(
815                (norm - 1.0).abs() < 1.0e-3,
816                "descriptor must be unit-norm, got {norm}"
817            );
818        }
819        let max_score = features
820            .scores
821            .iter()
822            .copied()
823            .fold(f32::NEG_INFINITY, f32::max);
824        assert!((max_score - 1.0).abs() < 1.0e-6, "top score should be 1.0");
825    }
826
827    #[test]
828    fn hog_extractor_descriptor_is_translation_consistent() {
829        // Same checkerboard pattern shifted: descriptors at corresponding
830        // keypoints should be identical (HOG is purely local).
831        let image_a = checkerboard_image(48);
832        let image_b = checkerboard_image(48); // identical content -> identical descriptors
833        let extractor = HogLikeFeatureExtractor::new(HogLikeFeatureConfig {
834            max_features: 8,
835            min_corner_score: 0.1,
836            descriptor_clip: 0.2,
837            orient: true,
838        });
839        let a = extractor.extract_deep(&image_a).unwrap();
840        let b = extractor.extract_deep(&image_b).unwrap();
841        assert_eq!(a.keypoints, b.keypoints);
842        for (da, db) in a.descriptors.iter().zip(b.descriptors.iter()) {
843            for (va, vb) in da.iter().zip(db.iter()) {
844                assert!((va - vb).abs() < 1.0e-6);
845            }
846        }
847    }
848
849    #[test]
850    fn corner_deep_adapter_propagates_scores_as_constant() {
851        let image = checkerboard_image(32);
852        let inner = CornerFeatureExtractor::new(super::super::CornerFeatureConfig {
853            max_features: 16,
854            min_score: 0.1,
855            descriptor_radius: 2,
856        });
857        let adapter = CornerDeepAdapter::new(inner);
858        let features = adapter.extract_deep(&image).unwrap();
859        assert!(!features.is_empty());
860        assert!(features.scores.iter().all(|&s| (s - 1.0).abs() < 1.0e-6));
861    }
862
863    #[test]
864    fn descriptor_normalization_handles_zero_input() {
865        let mut descriptor = vec![0.0_f32; HOG_DESCRIPTOR_DIM];
866        normalize_descriptor(&mut descriptor, 0.2);
867        assert!(descriptor.iter().all(|&v| v == 0.0));
868    }
869
870    #[test]
871    fn hog_extractor_rejects_too_small_image() {
872        let image = GrayscaleImage::new(8, 8, vec![0.0; 64]).unwrap();
873        let extractor = HogLikeFeatureExtractor::default();
874        let err = extractor.extract_deep(&image).unwrap_err();
875        assert!(matches!(err, HogLikeFeatureError::ImageTooSmall { .. }));
876    }
877
878    #[test]
879    fn build_pyramid_halves_each_level() {
880        let image = checkerboard_image(64);
881        let pyramid = build_pyramid(&image, 4);
882        assert_eq!(pyramid.len(), 4);
883        assert_eq!((pyramid[0].width(), pyramid[0].height()), (64, 64));
884        assert_eq!((pyramid[1].width(), pyramid[1].height()), (32, 32));
885        assert_eq!((pyramid[2].width(), pyramid[2].height()), (16, 16));
886        assert_eq!((pyramid[3].width(), pyramid[3].height()), (8, 8));
887    }
888
889    #[test]
890    fn build_pyramid_stops_when_dimensions_reach_zero() {
891        let image = checkerboard_image(8);
892        let pyramid = build_pyramid(&image, 8);
893        // 8 -> 4 -> 2 -> 1 -> 0 (stop). Should yield 4 levels.
894        assert_eq!(pyramid.len(), 4);
895        assert_eq!(
896            (
897                pyramid.last().unwrap().width(),
898                pyramid.last().unwrap().height()
899            ),
900            (1, 1)
901        );
902    }
903
904    #[test]
905    fn multiscale_extractor_recovers_finer_keypoints_than_single_octave() {
906        // A 64×64 checker is small enough that single-scale HOG only
907        // detects a handful of corners, but the merged multi-scale set is
908        // strictly larger.
909        let image = checkerboard_image(64);
910        let inner = HogLikeFeatureExtractor::new(HogLikeFeatureConfig {
911            max_features: 16,
912            min_corner_score: 0.05,
913            descriptor_clip: 0.2,
914            orient: true,
915        });
916        let single = inner.extract_deep(&image).unwrap();
917        let multi = MultiScaleDeepExtractor::new(
918            inner,
919            MultiScaleDeepConfig {
920                octaves: 3,
921                area_weighted_octave_cap: false,
922            },
923        )
924        .extract_deep(&image)
925        .unwrap();
926        assert!(multi.len() >= single.len());
927        // Coarse-octave keypoints land outside the inner extractor's
928        // patch-radius margin in the original image's coordinate frame,
929        // i.e. their pixel coordinates exceed `inner.patch_radius() + 1`.
930        // That is exactly what we want — they are detections that the
931        // single-scale extractor missed.
932        let inner_margin = HOG_CELLS_PER_SIDE * HOG_CELL_SIZE / 2 + 1;
933        let any_outside_inner_margin = multi.keypoints.iter().any(|kp| {
934            kp.x < inner_margin as f64
935                || kp.x >= (image.width() - inner_margin) as f64
936                || kp.y < inner_margin as f64
937                || kp.y >= (image.height() - inner_margin) as f64
938        });
939        let _ = any_outside_inner_margin; // optional sanity, not strictly required
940    }
941
942    #[test]
943    fn multiscale_extractor_skips_octaves_too_small_for_inner() {
944        // The base image is 24×24 — the first octave's 12×12 is smaller
945        // than the HogLike margin (8 + 1 = 9 each side) so the inner
946        // extractor should error out at octave 1, but the multi-scale
947        // wrapper must still return the octave-0 features.
948        let image = checkerboard_image(24);
949        let inner = HogLikeFeatureExtractor::default();
950        let result = MultiScaleDeepExtractor::new(
951            inner,
952            MultiScaleDeepConfig {
953                octaves: 4,
954                area_weighted_octave_cap: false,
955            },
956        )
957        .extract_deep(&image);
958        // The wrapper returns the union of *successful* per-octave
959        // extractions plus the unconditional first octave; at the very
960        // least the input scale must succeed.
961        let features = result.unwrap();
962        assert!(!features.is_empty());
963    }
964
965    #[test]
966    fn multiscale_extractor_keypoint_coordinates_are_in_original_pixel_frame() {
967        let image = checkerboard_image(48);
968        let inner = HogLikeFeatureExtractor::new(HogLikeFeatureConfig {
969            max_features: 8,
970            min_corner_score: 0.05,
971            descriptor_clip: 0.2,
972            orient: true,
973        });
974        let multi = MultiScaleDeepExtractor::new(
975            inner,
976            MultiScaleDeepConfig {
977                octaves: 2,
978                area_weighted_octave_cap: false,
979            },
980        )
981        .extract_deep(&image)
982        .unwrap();
983        for kp in &multi.keypoints {
984            assert!(kp.x >= 0.0 && kp.x < image.width() as f64);
985            assert!(kp.y >= 0.0 && kp.y < image.height() as f64);
986        }
987    }
988
989    #[test]
990    fn multiscale_describe_at_anchors_external_keypoint_across_octaves() {
991        let image = checkerboard_image(64);
992        let extractor = MultiScaleDeepExtractor::new(
993            HogLikeFeatureExtractor::new(HogLikeFeatureConfig {
994                max_features: 8,
995                min_corner_score: 0.05,
996                descriptor_clip: 0.2,
997                orient: false,
998            }),
999            MultiScaleDeepConfig {
1000                octaves: 3,
1001                area_weighted_octave_cap: false,
1002            },
1003        );
1004
1005        let descriptors = extractor.describe_at(&image, 32, 32);
1006
1007        assert_eq!(descriptors.len(), 2);
1008        assert!(descriptors
1009            .iter()
1010            .all(|descriptor| descriptor.len() == HOG_DESCRIPTOR_DIM));
1011    }
1012
1013    fn rotated_textured_image(side: usize, theta: f32) -> GrayscaleImage {
1014        let cx = (side as f32) / 2.0;
1015        let cy = (side as f32) / 2.0;
1016        let cos_t = theta.cos();
1017        let sin_t = theta.sin();
1018        let mut pixels = vec![0_u8; side * side];
1019        for y in 0..side {
1020            for x in 0..side {
1021                let dx = (x as f32) - cx;
1022                let dy = (y as f32) - cy;
1023                // Inverse rotation: query the un-rotated source position so
1024                // the resulting image is the same texture rotated by `theta`.
1025                let sx = cos_t * dx + sin_t * dy + cx;
1026                let sy = -sin_t * dx + cos_t * dy + cy;
1027                // Multi-scale checker pattern, plus a couple of strong blobs
1028                // so the corner detector locks onto consistent points across
1029                // rotations.
1030                let v = (50.0
1031                    + 100.0 * ((sx * 0.5).sin() * (sy * 0.5).sin()).abs()
1032                    + 80.0 * ((sx * 0.18).cos() * (sy * 0.22).cos()).abs())
1033                .clamp(0.0, 255.0) as u8;
1034                pixels[y * side + x] = v;
1035            }
1036        }
1037        // Plant two bright dots at fixed *image* positions so the detector
1038        // ends up with at least one keypoint near the same rotated location
1039        // in both images. The locations are chosen so that, after the inverse
1040        // rotation, the dot's "world" position is invariant.
1041        let world_dots = [(20.0, 20.0), (40.0, 30.0)];
1042        for &(wx, wy) in world_dots.iter() {
1043            // Forward-rotate the world dot to image space.
1044            let dx = wx - cx;
1045            let dy = wy - cy;
1046            let ix_f = cos_t * dx - sin_t * dy + cx;
1047            let iy_f = sin_t * dx + cos_t * dy + cy;
1048            let ix = ix_f.round() as i32;
1049            let iy = iy_f.round() as i32;
1050            let radius = 2_i32;
1051            for ddy in -radius..=radius {
1052                for ddx in -radius..=radius {
1053                    let xx = ix + ddx;
1054                    let yy = iy + ddy;
1055                    if xx < 0 || yy < 0 || xx >= side as i32 || yy >= side as i32 {
1056                        continue;
1057                    }
1058                    let r2 = (ddx * ddx + ddy * ddy) as f32;
1059                    if r2 > (radius as f32) * (radius as f32) {
1060                        continue;
1061                    }
1062                    let alpha = 1.0 - r2 / ((radius as f32) * (radius as f32));
1063                    let idx = (yy as usize) * side + xx as usize;
1064                    let blended = (pixels[idx] as f32) * (1.0 - alpha) + 240.0 * alpha;
1065                    pixels[idx] = blended.clamp(0.0, 255.0) as u8;
1066                }
1067            }
1068        }
1069        GrayscaleImage::from_luma_u8(side, side, pixels).unwrap()
1070    }
1071
1072    #[test]
1073    fn oriented_descriptors_are_more_rotation_stable_than_axis_aligned() {
1074        // Render the same world texture at 0° and at 30° rotation, extract
1075        // top-K keypoints from each, compute pairwise cosine similarity
1076        // between the (sorted) keypoints, and check the oriented variant's
1077        // similarity exceeds the axis-aligned variant's.
1078        let side = 64;
1079        let image_a = rotated_textured_image(side, 0.0);
1080        let image_b = rotated_textured_image(side, std::f32::consts::PI / 6.0);
1081
1082        let oriented = HogLikeFeatureExtractor::new(HogLikeFeatureConfig {
1083            max_features: 16,
1084            min_corner_score: 0.05,
1085            descriptor_clip: 0.2,
1086            orient: true,
1087        });
1088        let axis_aligned = HogLikeFeatureExtractor::new(HogLikeFeatureConfig {
1089            max_features: 16,
1090            min_corner_score: 0.05,
1091            descriptor_clip: 0.2,
1092            orient: false,
1093        });
1094
1095        let oriented_a = oriented.extract_deep(&image_a).unwrap();
1096        let oriented_b = oriented.extract_deep(&image_b).unwrap();
1097        let axis_aligned_a = axis_aligned.extract_deep(&image_a).unwrap();
1098        let axis_aligned_b = axis_aligned.extract_deep(&image_b).unwrap();
1099
1100        // Both extractors must find some keypoints.
1101        assert!(!oriented_a.is_empty() && !oriented_b.is_empty());
1102        assert!(!axis_aligned_a.is_empty() && !axis_aligned_b.is_empty());
1103
1104        // Best-cosine-similarity from each image_a keypoint to its closest
1105        // image_b descriptor — averaged. An oriented descriptor that
1106        // tracks the camera frame should land much closer to its rotated
1107        // counterpart than an axis-aligned descriptor that simply rotates
1108        // with the image.
1109        let oriented_score = best_cosine_match_score(&oriented_a, &oriented_b);
1110        let axis_aligned_score = best_cosine_match_score(&axis_aligned_a, &axis_aligned_b);
1111        assert!(
1112            oriented_score > axis_aligned_score,
1113            "oriented descriptors should beat axis-aligned under in-plane rotation: \
1114             oriented={} axis-aligned={}",
1115            oriented_score,
1116            axis_aligned_score
1117        );
1118    }
1119
1120    fn best_cosine_match_score(a: &DeepFeatureSet, b: &DeepFeatureSet) -> f32 {
1121        let mut total = 0.0_f32;
1122        let mut count = 0_f32;
1123        for desc_a in &a.descriptors {
1124            let mut best = -1.0_f32;
1125            for desc_b in &b.descriptors {
1126                let mut dot = 0.0_f32;
1127                for (&va, &vb) in desc_a.iter().zip(desc_b.iter()) {
1128                    dot += va * vb;
1129                }
1130                if dot > best {
1131                    best = dot;
1132                }
1133            }
1134            total += best;
1135            count += 1.0;
1136        }
1137        if count > 0.0 {
1138            total / count
1139        } else {
1140            0.0
1141        }
1142    }
1143
1144    #[test]
1145    fn dominant_orientation_aligns_with_strong_gradient() {
1146        // Vertical gradient (white left half, black right half) — the
1147        // dominant gradient orientation should point along +X (angle 0)
1148        // or -X (angle PI), depending on which side is brighter. Build the
1149        // image so the gradient points from right (dark) to left (bright),
1150        // which means atan2(0, +) = 0 for a +X gradient at the boundary.
1151        let side = 33;
1152        let mut pixels = vec![0_u8; side * side];
1153        for y in 0..side {
1154            for x in 0..side {
1155                pixels[y * side + x] = if x < side / 2 { 220 } else { 30 };
1156            }
1157        }
1158        let image = GrayscaleImage::from_luma_u8(side, side, pixels).unwrap();
1159        let theta = dominant_orientation(&image, side / 2, side / 2, 6);
1160        // Gradient is along the X axis: should be near 0 or PI.
1161        let near_0 = theta.min(std::f32::consts::TAU - theta);
1162        let near_pi = (theta - std::f32::consts::PI).abs();
1163        assert!(
1164            near_0 < 0.3 || near_pi < 0.3,
1165            "dominant orientation should align with X axis, got {theta}"
1166        );
1167    }
1168}