1pub mod deep;
2pub mod global_descriptor_onnx;
3pub mod lightglue_onnx;
4pub mod sift;
5pub mod superpoint_onnx;
6
7pub use deep::{
8 build_pyramid, CornerDeepAdapter, DeepFeatureExtractor, DeepFeatureSet, DeepFeatureSetError,
9 HogLikeFeatureConfig, HogLikeFeatureError, HogLikeFeatureExtractor, MultiScaleDeepConfig,
10 MultiScaleDeepExtractor, HOG_BINS, HOG_CELLS_PER_SIDE, HOG_CELL_SIZE, HOG_DESCRIPTOR_DIM,
11};
12
13use nalgebra::Point2;
14use std::convert::Infallible;
15use std::fmt;
16use std::marker::PhantomData;
17
18pub trait FeatureExtractor {
19 type Image;
20 type Error;
21
22 fn extract(&self, image: &Self::Image) -> Result<FeatureSet, Self::Error>;
23}
24
25#[derive(Debug, Clone, PartialEq)]
26pub struct FeatureSet {
27 pub keypoints: Vec<Point2<f64>>,
28 pub descriptors: Vec<Vec<f32>>,
29}
30
31impl FeatureSet {
32 pub fn new(
33 keypoints: Vec<Point2<f64>>,
34 descriptors: Vec<Vec<f32>>,
35 ) -> Result<Self, FeatureSetError> {
36 let features = Self {
37 keypoints,
38 descriptors,
39 };
40 features.validate()?;
41 Ok(features)
42 }
43
44 pub fn validate(&self) -> Result<(), FeatureSetError> {
45 if self.keypoints.len() != self.descriptors.len() {
46 return Err(FeatureSetError::ShapeMismatch {
47 keypoint_count: self.keypoints.len(),
48 descriptor_count: self.descriptors.len(),
49 });
50 }
51
52 let Some(first_descriptor) = self.descriptors.first() else {
53 return Ok(());
54 };
55 let descriptor_dimension = first_descriptor.len();
56 for (index, descriptor) in self.descriptors.iter().enumerate() {
57 if descriptor.len() != descriptor_dimension {
58 return Err(FeatureSetError::DescriptorDimensionMismatch {
59 descriptor_index: index,
60 expected_dimension: descriptor_dimension,
61 actual_dimension: descriptor.len(),
62 });
63 }
64 }
65
66 Ok(())
67 }
68
69 pub fn len(&self) -> usize {
70 self.keypoints.len()
71 }
72
73 pub fn is_empty(&self) -> bool {
74 self.keypoints.is_empty()
75 }
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub enum FeatureSetError {
80 ShapeMismatch {
81 keypoint_count: usize,
82 descriptor_count: usize,
83 },
84 DescriptorDimensionMismatch {
85 descriptor_index: usize,
86 expected_dimension: usize,
87 actual_dimension: usize,
88 },
89}
90
91impl fmt::Display for FeatureSetError {
92 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
93 match self {
94 Self::ShapeMismatch {
95 keypoint_count,
96 descriptor_count,
97 } => write!(
98 formatter,
99 "feature shape mismatch: {keypoint_count} keypoint(s), {descriptor_count} descriptor(s)"
100 ),
101 Self::DescriptorDimensionMismatch {
102 descriptor_index,
103 expected_dimension,
104 actual_dimension,
105 } => write!(
106 formatter,
107 "descriptor {descriptor_index} has dimension {actual_dimension}, expected {expected_dimension}"
108 ),
109 }
110 }
111}
112
113impl std::error::Error for FeatureSetError {}
114
115#[derive(Debug, Clone, PartialEq)]
116pub struct GrayscaleImage {
117 width: usize,
118 height: usize,
119 pixels: Vec<f32>,
120}
121
122impl GrayscaleImage {
123 pub fn new(width: usize, height: usize, pixels: Vec<f32>) -> Result<Self, GrayscaleImageError> {
124 if width == 0 || height == 0 {
125 return Err(GrayscaleImageError::EmptyImage);
126 }
127 let expected_len = width * height;
128 if pixels.len() != expected_len {
129 return Err(GrayscaleImageError::PixelCountMismatch {
130 width,
131 height,
132 expected_len,
133 actual_len: pixels.len(),
134 });
135 }
136 Ok(Self {
137 width,
138 height,
139 pixels,
140 })
141 }
142
143 pub fn from_luma_u8(
144 width: usize,
145 height: usize,
146 pixels: Vec<u8>,
147 ) -> Result<Self, GrayscaleImageError> {
148 let pixels = pixels
149 .into_iter()
150 .map(|value| value as f32 / 255.0)
151 .collect();
152 Self::new(width, height, pixels)
153 }
154
155 pub const fn width(&self) -> usize {
156 self.width
157 }
158
159 pub const fn height(&self) -> usize {
160 self.height
161 }
162
163 pub fn pixels(&self) -> &[f32] {
164 &self.pixels
165 }
166
167 pub fn get(&self, x: usize, y: usize) -> Option<f32> {
168 if x >= self.width || y >= self.height {
169 return None;
170 }
171 Some(self.pixels[y * self.width + x])
172 }
173
174 fn pixel_unchecked(&self, x: usize, y: usize) -> f32 {
175 self.pixels[y * self.width + x]
176 }
177}
178
179#[derive(Debug, Clone, PartialEq, Eq)]
180pub enum GrayscaleImageError {
181 EmptyImage,
182 PixelCountMismatch {
183 width: usize,
184 height: usize,
185 expected_len: usize,
186 actual_len: usize,
187 },
188}
189
190impl fmt::Display for GrayscaleImageError {
191 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
192 match self {
193 Self::EmptyImage => write!(formatter, "grayscale image dimensions must be non-zero"),
194 Self::PixelCountMismatch {
195 width,
196 height,
197 expected_len,
198 actual_len,
199 } => write!(
200 formatter,
201 "grayscale image {width}x{height} expects {expected_len} pixel(s), got {actual_len}"
202 ),
203 }
204 }
205}
206
207impl std::error::Error for GrayscaleImageError {}
208
209#[derive(Debug, Clone, PartialEq)]
210pub struct CornerFeatureConfig {
211 pub max_features: usize,
212 pub min_score: f32,
213 pub descriptor_radius: usize,
214}
215
216impl Default for CornerFeatureConfig {
217 fn default() -> Self {
218 Self {
219 max_features: 256,
220 min_score: 0.05,
221 descriptor_radius: 2,
222 }
223 }
224}
225
226#[derive(Debug, Clone, PartialEq)]
227pub struct CornerFeatureExtractor {
228 pub config: CornerFeatureConfig,
229}
230
231impl CornerFeatureExtractor {
232 pub const fn new(config: CornerFeatureConfig) -> Self {
233 Self { config }
234 }
235
236 fn required_margin(&self) -> usize {
237 self.config.descriptor_radius.max(1)
238 }
239
240 fn corner_score(image: &GrayscaleImage, x: usize, y: usize) -> f32 {
241 let dx = image.pixel_unchecked(x + 1, y) - image.pixel_unchecked(x - 1, y);
242 let dy = image.pixel_unchecked(x, y + 1) - image.pixel_unchecked(x, y - 1);
243 let dxy1 = image.pixel_unchecked(x + 1, y + 1) - image.pixel_unchecked(x - 1, y - 1);
244 let dxy2 = image.pixel_unchecked(x + 1, y - 1) - image.pixel_unchecked(x - 1, y + 1);
245 (dx * dx + dy * dy + 0.5 * (dxy1 * dxy1 + dxy2 * dxy2)).sqrt()
246 }
247
248 fn is_local_maximum(image: &GrayscaleImage, x: usize, y: usize, score: f32) -> bool {
249 for neighbor_y in (y - 1)..=(y + 1) {
250 for neighbor_x in (x - 1)..=(x + 1) {
251 if neighbor_x == x && neighbor_y == y {
252 continue;
253 }
254 if neighbor_x == 0
255 || neighbor_y == 0
256 || neighbor_x + 1 >= image.width
257 || neighbor_y + 1 >= image.height
258 {
259 continue;
260 }
261 if Self::corner_score(image, neighbor_x, neighbor_y) > score {
262 return false;
263 }
264 }
265 }
266 true
267 }
268
269 fn descriptor(&self, image: &GrayscaleImage, x: usize, y: usize) -> Vec<f32> {
270 let radius = self.config.descriptor_radius;
271 let center = image.pixel_unchecked(x, y);
272 let side = radius * 2 + 1;
273 let mut descriptor = Vec::with_capacity(side * side);
274 for yy in (y - radius)..=(y + radius) {
275 for xx in (x - radius)..=(x + radius) {
276 descriptor.push(image.pixel_unchecked(xx, yy) - center);
277 }
278 }
279 descriptor
280 }
281
282 pub fn describe_at(&self, image: &GrayscaleImage, x: usize, y: usize) -> Option<Vec<f32>> {
287 let radius = self.required_margin();
288 if x < radius || y < radius || x + radius >= image.width() || y + radius >= image.height() {
289 return None;
290 }
291 Some(self.descriptor(image, x, y))
292 }
293}
294
295impl Default for CornerFeatureExtractor {
296 fn default() -> Self {
297 Self::new(CornerFeatureConfig::default())
298 }
299}
300
301#[derive(Debug, Clone, PartialEq, Eq)]
302pub enum CornerFeatureError {
303 ImageTooSmall {
304 width: usize,
305 height: usize,
306 required_margin: usize,
307 },
308 FeatureSet(FeatureSetError),
309}
310
311impl fmt::Display for CornerFeatureError {
312 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
313 match self {
314 Self::ImageTooSmall {
315 width,
316 height,
317 required_margin,
318 } => write!(
319 formatter,
320 "image {width}x{height} is too small for feature extraction with margin {required_margin}"
321 ),
322 Self::FeatureSet(error) => write!(formatter, "{error}"),
323 }
324 }
325}
326
327impl std::error::Error for CornerFeatureError {}
328
329impl From<FeatureSetError> for CornerFeatureError {
330 fn from(error: FeatureSetError) -> Self {
331 Self::FeatureSet(error)
332 }
333}
334
335impl FeatureExtractor for CornerFeatureExtractor {
336 type Image = GrayscaleImage;
337 type Error = CornerFeatureError;
338
339 fn extract(&self, image: &Self::Image) -> Result<FeatureSet, Self::Error> {
340 let margin = self.required_margin();
341 if image.width <= margin * 2 || image.height <= margin * 2 {
342 return Err(CornerFeatureError::ImageTooSmall {
343 width: image.width,
344 height: image.height,
345 required_margin: margin,
346 });
347 }
348
349 let mut candidates = Vec::new();
350 for y in margin..(image.height - margin) {
351 for x in margin..(image.width - margin) {
352 let score = Self::corner_score(image, x, y);
353 if score < self.config.min_score {
354 continue;
355 }
356 if Self::is_local_maximum(image, x, y, score) {
357 candidates.push((score, x, y));
358 }
359 }
360 }
361
362 candidates.sort_by(|left, right| {
363 right
364 .0
365 .total_cmp(&left.0)
366 .then_with(|| left.2.cmp(&right.2))
367 .then_with(|| left.1.cmp(&right.1))
368 });
369 candidates.truncate(self.config.max_features);
370
371 let mut keypoints = Vec::with_capacity(candidates.len());
372 let mut descriptors = Vec::with_capacity(candidates.len());
373 for (_score, x, y) in candidates {
374 keypoints.push(Point2::new(x as f64, y as f64));
375 descriptors.push(self.descriptor(image, x, y));
376 }
377
378 FeatureSet::new(keypoints, descriptors).map_err(CornerFeatureError::from)
379 }
380}
381
382#[derive(Debug, Clone, PartialEq)]
383pub struct ProvidedFeatureExtractor {
384 pub features: FeatureSet,
385}
386
387impl ProvidedFeatureExtractor {
388 pub const fn new(features: FeatureSet) -> Self {
389 Self { features }
390 }
391}
392
393impl FeatureExtractor for ProvidedFeatureExtractor {
394 type Image = ();
395 type Error = Infallible;
396
397 fn extract(&self, _image: &Self::Image) -> Result<FeatureSet, Self::Error> {
398 Ok(self.features.clone())
399 }
400}
401
402#[derive(Debug, Clone)]
403pub struct FnFeatureExtractor<F, I, E> {
404 extract_fn: F,
405 _phantom: PhantomData<fn(&I) -> E>,
406}
407
408impl<F, I, E> FnFeatureExtractor<F, I, E> {
409 pub fn new(extract_fn: F) -> Self {
410 Self {
411 extract_fn,
412 _phantom: PhantomData,
413 }
414 }
415}
416
417impl<F, I, E> FeatureExtractor for FnFeatureExtractor<F, I, E>
418where
419 F: Fn(&I) -> Result<FeatureSet, E>,
420{
421 type Image = I;
422 type Error = E;
423
424 fn extract(&self, image: &Self::Image) -> Result<FeatureSet, Self::Error> {
425 (self.extract_fn)(image)
426 }
427}
428
429#[cfg(test)]
430mod tests {
431 use super::{
432 CornerFeatureConfig, CornerFeatureError, CornerFeatureExtractor, FeatureExtractor,
433 FeatureSet, FeatureSetError, FnFeatureExtractor, GrayscaleImage, GrayscaleImageError,
434 ProvidedFeatureExtractor,
435 };
436 use nalgebra::Point2;
437
438 #[test]
439 fn feature_set_new_validates_shapes() {
440 let error = FeatureSet::new(vec![Point2::new(1.0, 2.0)], Vec::new()).unwrap_err();
441
442 assert_eq!(
443 error,
444 FeatureSetError::ShapeMismatch {
445 keypoint_count: 1,
446 descriptor_count: 0,
447 }
448 );
449 }
450
451 #[test]
452 fn feature_set_new_validates_descriptor_dimensions() {
453 let error = FeatureSet::new(
454 vec![Point2::new(1.0, 2.0), Point2::new(3.0, 4.0)],
455 vec![vec![1.0, 2.0], vec![3.0]],
456 )
457 .unwrap_err();
458
459 assert_eq!(
460 error,
461 FeatureSetError::DescriptorDimensionMismatch {
462 descriptor_index: 1,
463 expected_dimension: 2,
464 actual_dimension: 1,
465 }
466 );
467 }
468
469 #[test]
470 fn provided_feature_extractor_returns_static_features() {
471 let features = FeatureSet::new(vec![Point2::new(1.0, 2.0)], vec![vec![0.5]]).unwrap();
472 let extractor = ProvidedFeatureExtractor::new(features.clone());
473
474 assert_eq!(extractor.extract(&()).unwrap(), features);
475 }
476
477 #[test]
478 fn fn_feature_extractor_wraps_external_extractor_logic() {
479 let extractor = FnFeatureExtractor::new(|image: &&str| {
480 FeatureSet::new(
481 vec![Point2::new(image.len() as f64, 0.0)],
482 vec![vec![image.len() as f32]],
483 )
484 });
485
486 let features = extractor.extract(&"abc").unwrap();
487
488 assert_eq!(features.len(), 1);
489 assert_eq!(features.keypoints[0], Point2::new(3.0, 0.0));
490 assert_eq!(features.descriptors[0], vec![3.0]);
491 }
492
493 #[test]
494 fn grayscale_image_validates_pixel_count() {
495 let error = GrayscaleImage::new(2, 2, vec![0.0; 3]).unwrap_err();
496
497 assert_eq!(
498 error,
499 GrayscaleImageError::PixelCountMismatch {
500 width: 2,
501 height: 2,
502 expected_len: 4,
503 actual_len: 3,
504 }
505 );
506 }
507
508 #[test]
509 fn corner_feature_extractor_detects_synthetic_corner() {
510 let mut pixels = vec![0_u8; 11 * 11];
511 for y in 5..11 {
512 for x in 5..11 {
513 pixels[y * 11 + x] = 255;
514 }
515 }
516 let image = GrayscaleImage::from_luma_u8(11, 11, pixels).unwrap();
517 let extractor = CornerFeatureExtractor::new(CornerFeatureConfig {
518 max_features: 4,
519 min_score: 0.5,
520 descriptor_radius: 1,
521 });
522
523 let features = extractor.extract(&image).unwrap();
524
525 assert!(!features.is_empty());
526 assert!(features.len() <= 4);
527 assert_eq!(features.descriptors[0].len(), 9);
528 assert!(features
529 .keypoints
530 .iter()
531 .any(|point| (point.x - 5.0).abs() <= 1.0 && (point.y - 5.0).abs() <= 1.0));
532 }
533
534 #[test]
535 fn corner_feature_extractor_rejects_too_small_images() {
536 let image = GrayscaleImage::new(3, 3, vec![0.0; 9]).unwrap();
537 let extractor = CornerFeatureExtractor::new(CornerFeatureConfig {
538 max_features: 8,
539 min_score: 0.0,
540 descriptor_radius: 2,
541 });
542
543 let error = extractor.extract(&image).unwrap_err();
544
545 assert_eq!(
546 error,
547 CornerFeatureError::ImageTooSmall {
548 width: 3,
549 height: 3,
550 required_margin: 2,
551 }
552 );
553 }
554}