1use super::{
22 CornerFeatureExtractor, FeatureExtractor, FeatureSet, FeatureSetError, GrayscaleImage,
23};
24use nalgebra::Point2;
25use std::fmt;
26
27#[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 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
134pub trait DeepFeatureExtractor {
138 type Image;
139 type Error;
140
141 fn extract_deep(&self, image: &Self::Image) -> Result<DeepFeatureSet, Self::Error>;
142}
143
144pub const HOG_BINS: usize = 8;
146pub const HOG_CELLS_PER_SIDE: usize = 4;
148pub const HOG_CELL_SIZE: usize = 4;
150pub const HOG_DESCRIPTOR_DIM: usize = HOG_CELLS_PER_SIDE * HOG_CELLS_PER_SIDE * HOG_BINS;
152
153#[derive(Debug, Clone, PartialEq)]
155pub struct HogLikeFeatureConfig {
156 pub max_features: usize,
158 pub min_corner_score: f32,
160 pub descriptor_clip: f32,
162 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#[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 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 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 let lx = (px as f32) - (radius as f32) + 0.5;
270 let ly = (py as f32) - (radius as f32) + 0.5;
271 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 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 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
388impl 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#[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 unreachable!("score length is taken from features.len()")
427 }
428 }
429 })
430 }
431}
432
433pub 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#[derive(Debug, Clone, PartialEq)]
473pub struct MultiScaleDeepConfig {
474 pub octaves: usize,
479 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#[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 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 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
599impl<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
654fn 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
678fn 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 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 let image_a = checkerboard_image(48);
832 let image_b = checkerboard_image(48); 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 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 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 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; }
941
942 #[test]
943 fn multiscale_extractor_skips_octaves_too_small_for_inner() {
944 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 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 let sx = cos_t * dx + sin_t * dy + cx;
1026 let sy = -sin_t * dx + cos_t * dy + cy;
1027 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 let world_dots = [(20.0, 20.0), (40.0, 30.0)];
1042 for &(wx, wy) in world_dots.iter() {
1043 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 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 assert!(!oriented_a.is_empty() && !oriented_b.is_empty());
1102 assert!(!axis_aligned_a.is_empty() && !axis_aligned_b.is_empty());
1103
1104 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 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 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}