1#![forbid(unsafe_code)]
2#![allow(rustdoc::private_intra_doc_links, rustdoc::broken_intra_doc_links)]
6mod binary_index;
14mod correspondence;
15mod keyframe_retrieval;
16mod map_merge;
17mod odom_correction;
18mod wheel_calibration;
19mod wheel_gyro;
20
21use std::collections::HashSet;
22
23use nalgebra::Point3;
24use visloc_core::geometry::Pose;
25use visloc_core::types::{
26 Camera, CameraId, Frame, FrameId, LandmarkDescriptorStore, LandmarkId,
27 LocalizationFailureReason, LocalizationResult, LocalizationSuccess, QueryImage, VisualMap,
28};
29use visloc_vision::features::{FeatureExtractor, FeatureSet};
30use visloc_vision::matching::{BruteForceMatcher, Matcher};
31use visloc_vision::pnp::Correspondence2D3D;
32use visloc_vision::ransac::{PnPRansac, RobustPoseEstimator};
33
34pub use binary_index::{BinaryLandmarkIndex, BinaryMatchGates, PackedDescriptors};
35pub use correspondence::{
36 AllLandmarksSelector, CandidateSelector, CorrespondenceBuildError, CorrespondenceBuilder,
37 CorrespondenceSet, FixedLandmarkSelector, IntersectCandidateSelector,
38 ProjectionCorrespondenceBuilder, RadiusLandmarkSelector,
39};
40pub use keyframe_retrieval::KeyframeRetrieval;
41pub use map_merge::{
42 merge_maps, register_map, MapMergeConfig, MapMergeError, MapRegistration, MergedMap,
43};
44pub use odom_correction::{FixOutcome, OdomCorrection, OdomCorrectionConfig};
45pub use wheel_calibration::{
46 CalibrationSource, WheelCalibration, WheelCalibrationConfig, WheelCalibrationEstimate,
47};
48pub use wheel_gyro::{GyroWheelConfig, GyroWheelOdometry};
49
50#[derive(Debug, Clone, PartialEq)]
51pub struct LocalizationConfig {
52 pub ratio: Option<f32>,
53 pub ransac_iterations: usize,
54 pub reprojection_threshold: f64,
55 pub min_inliers: usize,
56 pub min_inlier_ratio: f64,
57 pub max_mean_reprojection_error: Option<f64>,
58 pub max_median_reprojection_error: Option<f64>,
59 pub max_reprojection_error: Option<f64>,
60}
61
62impl Default for LocalizationConfig {
63 fn default() -> Self {
64 Self {
65 ratio: Some(0.8),
66 ransac_iterations: 128,
67 reprojection_threshold: 4.0,
68 min_inliers: 0,
69 min_inlier_ratio: 0.0,
70 max_mean_reprojection_error: None,
71 max_median_reprojection_error: None,
72 max_reprojection_error: None,
73 }
74 }
75}
76
77#[derive(Debug, Clone, PartialEq)]
78pub struct FrameLocalizationResult {
79 pub frame_id: FrameId,
80 pub result: LocalizationResult,
81}
82
83pub trait MapProvider {
84 fn visual_map(&self) -> &VisualMap;
85}
86
87pub trait DescriptorProvider {
88 fn landmark_descriptor_store(&self) -> Option<&LandmarkDescriptorStore>;
89}
90
91#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
92pub struct MapProviderStats {
93 pub camera_count: usize,
94 pub landmark_count: usize,
95 pub keyframe_count: usize,
96 pub descriptor_count: usize,
97}
98
99pub fn map_provider_stats<P>(provider: &P) -> MapProviderStats
100where
101 P: MapProvider + DescriptorProvider,
102{
103 let map = provider.visual_map();
104 let descriptor_count = provider.landmark_descriptor_store().map_or_else(
105 || {
106 map.landmarks
107 .values()
108 .filter(|landmark| landmark.descriptor.is_some())
109 .count()
110 },
111 LandmarkDescriptorStore::len,
112 );
113
114 MapProviderStats {
115 camera_count: map.cameras.len(),
116 landmark_count: map.landmarks.len(),
117 keyframe_count: map.keyframes.len(),
118 descriptor_count,
119 }
120}
121
122#[derive(Debug, Clone, PartialEq)]
123pub struct LocalizationPrior {
124 pub pose: Option<Pose>,
125 pub position_world: Option<Point3<f64>>,
126 pub radius: Option<f64>,
127}
128
129impl LocalizationPrior {
130 pub const fn none() -> Self {
131 Self {
132 pose: None,
133 position_world: None,
134 radius: None,
135 }
136 }
137
138 pub const fn from_pose(pose: Pose, radius: f64) -> Self {
139 Self {
140 pose: Some(pose),
141 position_world: None,
142 radius: Some(radius),
143 }
144 }
145
146 pub const fn from_position(position_world: Point3<f64>, radius: f64) -> Self {
147 Self {
148 pose: None,
149 position_world: Some(position_world),
150 radius: Some(radius),
151 }
152 }
153
154 pub fn center_world(&self) -> Option<Point3<f64>> {
155 if let Some(position_world) = self.position_world {
156 Some(position_world)
157 } else {
158 self.pose.as_ref().map(Pose::camera_center_world)
159 }
160 }
161
162 pub fn to_radius_submap_selector(&self) -> Option<RadiusSubmapSelector> {
163 Some(RadiusSubmapSelector::new(
164 self.center_world()?,
165 self.radius?,
166 ))
167 }
168}
169
170impl Default for LocalizationPrior {
171 fn default() -> Self {
172 Self::none()
173 }
174}
175
176pub trait SubmapSelector<P>
177where
178 P: MapProvider + DescriptorProvider,
179{
180 fn select_submap(&self, provider: &P) -> InMemoryMapProvider;
181}
182
183#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
184pub struct AllMapSelector;
185
186impl<P> SubmapSelector<P> for AllMapSelector
187where
188 P: MapProvider + DescriptorProvider,
189{
190 fn select_submap(&self, provider: &P) -> InMemoryMapProvider {
191 if let Some(descriptor_store) = provider.landmark_descriptor_store() {
192 InMemoryMapProvider::with_descriptor_store(
193 provider.visual_map().clone(),
194 descriptor_store.clone(),
195 )
196 } else {
197 InMemoryMapProvider::new(provider.visual_map().clone())
198 }
199 }
200}
201
202#[derive(Debug, Clone, PartialEq, Eq)]
203pub struct FixedLandmarkSubmapSelector {
204 pub landmark_ids: Vec<LandmarkId>,
205}
206
207impl FixedLandmarkSubmapSelector {
208 pub fn new(mut landmark_ids: Vec<LandmarkId>) -> Self {
209 landmark_ids.sort_unstable();
210 landmark_ids.dedup();
211 Self { landmark_ids }
212 }
213}
214
215impl<P> SubmapSelector<P> for FixedLandmarkSubmapSelector
216where
217 P: MapProvider + DescriptorProvider,
218{
219 fn select_submap(&self, provider: &P) -> InMemoryMapProvider {
220 InMemoryMapProvider::from_provider_landmarks(provider, self.landmark_ids.iter().copied())
221 }
222}
223
224#[derive(Debug, Clone, PartialEq)]
225pub struct RadiusSubmapSelector {
226 pub center_world: Point3<f64>,
227 pub radius: f64,
228}
229
230impl RadiusSubmapSelector {
231 pub const fn new(center_world: Point3<f64>, radius: f64) -> Self {
232 Self {
233 center_world,
234 radius,
235 }
236 }
237}
238
239impl<P> SubmapSelector<P> for RadiusSubmapSelector
240where
241 P: MapProvider + DescriptorProvider,
242{
243 fn select_submap(&self, provider: &P) -> InMemoryMapProvider {
244 InMemoryMapProvider::from_provider_radius(provider, self.center_world, self.radius)
245 }
246}
247
248#[derive(Debug, Clone, PartialEq)]
249pub struct PriorSubmapSelector {
250 pub prior: LocalizationPrior,
251}
252
253impl PriorSubmapSelector {
254 pub const fn new(prior: LocalizationPrior) -> Self {
255 Self { prior }
256 }
257}
258
259impl<P> SubmapSelector<P> for PriorSubmapSelector
260where
261 P: MapProvider + DescriptorProvider,
262{
263 fn select_submap(&self, provider: &P) -> InMemoryMapProvider {
264 if let Some(selector) = self.prior.to_radius_submap_selector() {
265 selector.select_submap(provider)
266 } else {
267 AllMapSelector.select_submap(provider)
268 }
269 }
270}
271
272#[derive(Debug, Clone, PartialEq)]
273pub struct SelectableMapProvider<P, S>
274where
275 P: MapProvider + DescriptorProvider,
276 S: SubmapSelector<P>,
277{
278 pub base_provider: P,
279 pub selector: S,
280 selected_provider: InMemoryMapProvider,
281}
282
283impl<P, S> SelectableMapProvider<P, S>
284where
285 P: MapProvider + DescriptorProvider,
286 S: SubmapSelector<P>,
287{
288 pub fn new(base_provider: P, selector: S) -> Self {
289 let selected_provider = selector.select_submap(&base_provider);
290 Self {
291 base_provider,
292 selector,
293 selected_provider,
294 }
295 }
296
297 pub fn refresh(&mut self) {
298 self.selected_provider = self.selector.select_submap(&self.base_provider);
299 }
300
301 pub const fn selected_provider(&self) -> &InMemoryMapProvider {
302 &self.selected_provider
303 }
304}
305
306impl<P, S> MapProvider for SelectableMapProvider<P, S>
307where
308 P: MapProvider + DescriptorProvider,
309 S: SubmapSelector<P>,
310{
311 fn visual_map(&self) -> &VisualMap {
312 self.selected_provider.visual_map()
313 }
314}
315
316impl<P, S> DescriptorProvider for SelectableMapProvider<P, S>
317where
318 P: MapProvider + DescriptorProvider,
319 S: SubmapSelector<P>,
320{
321 fn landmark_descriptor_store(&self) -> Option<&LandmarkDescriptorStore> {
322 self.selected_provider.landmark_descriptor_store()
323 }
324}
325
326#[derive(Debug, Clone, PartialEq)]
327pub struct InMemoryMapProvider {
328 pub map: VisualMap,
329 pub descriptor_store: Option<LandmarkDescriptorStore>,
330}
331
332impl InMemoryMapProvider {
333 pub const fn new(map: VisualMap) -> Self {
334 Self {
335 map,
336 descriptor_store: None,
337 }
338 }
339
340 pub const fn with_descriptor_store(
341 map: VisualMap,
342 descriptor_store: LandmarkDescriptorStore,
343 ) -> Self {
344 Self {
345 map,
346 descriptor_store: Some(descriptor_store),
347 }
348 }
349
350 pub fn from_provider_landmarks<P, I>(provider: &P, landmark_ids: I) -> Self
351 where
352 P: MapProvider + DescriptorProvider,
353 I: IntoIterator<Item = LandmarkId>,
354 {
355 let source_map = provider.visual_map();
356 let landmark_ids = landmark_ids.into_iter().collect::<HashSet<_>>();
357 let mut map = VisualMap::new();
358 map.cameras = source_map.cameras.clone();
359 map.landmarks = source_map
360 .landmarks
361 .iter()
362 .filter(|(landmark_id, _)| landmark_ids.contains(landmark_id))
363 .map(|(landmark_id, landmark)| (*landmark_id, landmark.clone()))
364 .collect();
365 map.landmark_position_covariances = source_map
366 .landmark_position_covariances
367 .iter()
368 .filter(|(landmark_id, _)| landmark_ids.contains(landmark_id))
369 .map(|(landmark_id, covariance)| (*landmark_id, *covariance))
370 .collect();
371 map.keyframes = source_map
372 .keyframes
373 .iter()
374 .filter_map(|(keyframe_id, keyframe)| {
375 let mut keyframe = keyframe.clone();
376 keyframe
377 .observations
378 .retain(|observation| landmark_ids.contains(&observation.landmark_id));
379 if keyframe.observations.is_empty() {
380 None
381 } else {
382 Some((*keyframe_id, keyframe))
383 }
384 })
385 .collect();
386
387 let descriptor_store = descriptor_store_for_submap(provider, &map);
388 Self {
389 map,
390 descriptor_store,
391 }
392 }
393
394 pub fn from_provider_radius<P>(provider: &P, center_world: Point3<f64>, radius: f64) -> Self
395 where
396 P: MapProvider + DescriptorProvider,
397 {
398 let landmark_ids = if radius < 0.0 {
399 Vec::new()
400 } else {
401 let radius_squared = radius * radius;
402 provider
403 .visual_map()
404 .landmarks
405 .values()
406 .filter(|landmark| {
407 (landmark.position - center_world).norm_squared() <= radius_squared
408 })
409 .map(|landmark| landmark.id)
410 .collect::<Vec<_>>()
411 };
412 Self::from_provider_landmarks(provider, landmark_ids)
413 }
414}
415
416impl MapProvider for InMemoryMapProvider {
417 fn visual_map(&self) -> &VisualMap {
418 &self.map
419 }
420}
421
422impl DescriptorProvider for InMemoryMapProvider {
423 fn landmark_descriptor_store(&self) -> Option<&LandmarkDescriptorStore> {
424 self.descriptor_store.as_ref()
425 }
426}
427
428fn descriptor_store_for_submap<P>(
429 provider: &P,
430 submap: &VisualMap,
431) -> Option<LandmarkDescriptorStore>
432where
433 P: MapProvider + DescriptorProvider,
434{
435 let mut descriptor_store = LandmarkDescriptorStore::new();
436 if let Some(source_store) = provider.landmark_descriptor_store() {
437 let mut landmark_ids: Vec<u64> = submap.landmarks.keys().copied().collect();
443 landmark_ids.sort();
444 for landmark_id in landmark_ids {
445 if let Some(descriptor) = source_store.get(landmark_id) {
446 descriptor_store.insert(landmark_id, descriptor.to_vec());
447 }
448 }
449 } else {
450 descriptor_store = LandmarkDescriptorStore::from_visual_map(submap);
451 }
452
453 if descriptor_store.is_empty() {
454 None
455 } else {
456 Some(descriptor_store)
457 }
458}
459
460#[derive(Debug, Clone)]
461pub struct ImageLocalizer<X, P = LocalizationPipeline> {
462 pub extractor: X,
463 pub pipeline: P,
464}
465
466impl<X> ImageLocalizer<X, LocalizationPipeline>
467where
468 X: FeatureExtractor,
469{
470 pub fn new(extractor: X) -> Self {
471 Self {
472 extractor,
473 pipeline: LocalizationPipeline::default(),
474 }
475 }
476}
477
478impl<X, P> ImageLocalizer<X, P>
479where
480 X: FeatureExtractor,
481{
482 pub const fn with_pipeline(extractor: X, pipeline: P) -> Self {
483 Self {
484 extractor,
485 pipeline,
486 }
487 }
488}
489
490#[derive(Debug, Clone)]
491pub struct LocalizationPipeline<M = BruteForceMatcher, S = AllLandmarksSelector, E = PnPRansac> {
492 pub matcher: M,
493 pub candidate_selector: S,
494 pub pose_estimator: E,
495 pub config: LocalizationConfig,
496}
497
498impl Default for LocalizationPipeline<BruteForceMatcher, AllLandmarksSelector, PnPRansac> {
499 fn default() -> Self {
500 let config = LocalizationConfig::default();
501 Self {
502 matcher: BruteForceMatcher {
503 ratio: config.ratio,
504 },
505 candidate_selector: AllLandmarksSelector,
506 pose_estimator: PnPRansac {
507 pose_estimator: Default::default(),
508 iterations: config.ransac_iterations,
509 reprojection_threshold: config.reprojection_threshold,
510 ..PnPRansac::default()
511 },
512 config,
513 }
514 }
515}
516
517impl<M> LocalizationPipeline<M, AllLandmarksSelector, PnPRansac>
518where
519 M: Matcher + Clone,
520{
521 pub fn new(matcher: M, config: LocalizationConfig) -> Self {
522 Self {
523 matcher,
524 candidate_selector: AllLandmarksSelector,
525 pose_estimator: PnPRansac {
526 pose_estimator: Default::default(),
527 iterations: config.ransac_iterations,
528 reprojection_threshold: config.reprojection_threshold,
529 ..PnPRansac::default()
530 },
531 config,
532 }
533 }
534}
535
536impl<M, S> LocalizationPipeline<M, S, PnPRansac>
537where
538 M: Matcher + Clone,
539 S: CandidateSelector + Clone,
540{
541 pub fn with_candidate_selector(
542 matcher: M,
543 candidate_selector: S,
544 config: LocalizationConfig,
545 ) -> Self {
546 Self {
547 matcher,
548 candidate_selector,
549 pose_estimator: PnPRansac {
550 pose_estimator: Default::default(),
551 iterations: config.ransac_iterations,
552 reprojection_threshold: config.reprojection_threshold,
553 ..PnPRansac::default()
554 },
555 config,
556 }
557 }
558}
559
560impl<M, S, E> LocalizationPipeline<M, S, E>
561where
562 M: Matcher + Clone,
563 S: CandidateSelector + Clone,
564 E: RobustPoseEstimator + Clone,
565{
566 pub const fn with_pose_estimator(
567 matcher: M,
568 candidate_selector: S,
569 pose_estimator: E,
570 config: LocalizationConfig,
571 ) -> Self {
572 Self {
573 matcher,
574 candidate_selector,
575 pose_estimator,
576 config,
577 }
578 }
579
580 pub fn localize(&self, query: &QueryImage, map: &VisualMap) -> LocalizationResult {
581 let descriptor_store = LandmarkDescriptorStore::from_visual_map(map);
582 self.localize_with_descriptor_store(query, map, &descriptor_store)
583 }
584
585 pub fn localize_with_provider<P>(&self, query: &QueryImage, provider: &P) -> LocalizationResult
586 where
587 P: MapProvider + DescriptorProvider,
588 {
589 let map = provider.visual_map();
590 if let Some(descriptor_store) = provider.landmark_descriptor_store() {
591 self.localize_with_descriptor_store(query, map, descriptor_store)
592 } else {
593 let descriptor_store = LandmarkDescriptorStore::from_visual_map(map);
594 self.localize_with_descriptor_store(query, map, &descriptor_store)
595 }
596 }
597
598 pub fn localize_image_with_extractor<X>(
599 &self,
600 image: &X::Image,
601 camera: Camera,
602 map: &VisualMap,
603 extractor: &X,
604 ) -> Result<LocalizationResult, X::Error>
605 where
606 X: FeatureExtractor,
607 {
608 let descriptor_store = LandmarkDescriptorStore::from_visual_map(map);
609 self.localize_image_with_extractor_and_descriptor_store(
610 image,
611 camera,
612 map,
613 &descriptor_store,
614 extractor,
615 )
616 }
617
618 pub fn localize_image_with_extractor_and_provider<X, P>(
619 &self,
620 image: &X::Image,
621 camera: Camera,
622 provider: &P,
623 extractor: &X,
624 ) -> Result<LocalizationResult, X::Error>
625 where
626 X: FeatureExtractor,
627 P: MapProvider + DescriptorProvider,
628 {
629 let features = extractor.extract(image)?;
630 let query = query_from_features(camera, features);
631 Ok(self.localize_with_provider(&query, provider))
632 }
633
634 pub fn localize_image_with_extractor_and_descriptor_store<X>(
635 &self,
636 image: &X::Image,
637 camera: Camera,
638 map: &VisualMap,
639 descriptor_store: &LandmarkDescriptorStore,
640 extractor: &X,
641 ) -> Result<LocalizationResult, X::Error>
642 where
643 X: FeatureExtractor,
644 {
645 let features = extractor.extract(image)?;
646 let query = query_from_features(camera, features);
647 Ok(self.localize_with_descriptor_store(&query, map, descriptor_store))
648 }
649
650 pub fn localize_frame(&self, frame: &Frame, map: &VisualMap) -> LocalizationResult {
651 let descriptor_store = LandmarkDescriptorStore::from_visual_map(map);
652 self.localize_frame_with_descriptor_store(frame, map, &descriptor_store)
653 }
654
655 pub fn localize_frame_with_provider<P>(&self, frame: &Frame, provider: &P) -> LocalizationResult
656 where
657 P: MapProvider + DescriptorProvider,
658 {
659 let map = provider.visual_map();
660 if let Some(descriptor_store) = provider.landmark_descriptor_store() {
661 self.localize_frame_with_descriptor_store(frame, map, descriptor_store)
662 } else {
663 let descriptor_store = LandmarkDescriptorStore::from_visual_map(map);
664 self.localize_frame_with_descriptor_store(frame, map, &descriptor_store)
665 }
666 }
667
668 pub fn localize_frame_image_with_extractor<X>(
669 &self,
670 frame_id: FrameId,
671 camera_id: CameraId,
672 image: &X::Image,
673 map: &VisualMap,
674 extractor: &X,
675 ) -> Result<FrameLocalizationResult, X::Error>
676 where
677 X: FeatureExtractor,
678 {
679 let descriptor_store = LandmarkDescriptorStore::from_visual_map(map);
680 self.localize_frame_image_with_extractor_and_descriptor_store(
681 frame_id,
682 camera_id,
683 image,
684 map,
685 &descriptor_store,
686 extractor,
687 )
688 }
689
690 pub fn localize_frame_image_with_extractor_and_provider<X, P>(
691 &self,
692 frame_id: FrameId,
693 camera_id: CameraId,
694 image: &X::Image,
695 provider: &P,
696 extractor: &X,
697 ) -> Result<FrameLocalizationResult, X::Error>
698 where
699 X: FeatureExtractor,
700 P: MapProvider + DescriptorProvider,
701 {
702 let map = provider.visual_map();
703 if let Some(descriptor_store) = provider.landmark_descriptor_store() {
704 self.localize_frame_image_with_extractor_and_descriptor_store(
705 frame_id,
706 camera_id,
707 image,
708 map,
709 descriptor_store,
710 extractor,
711 )
712 } else {
713 let descriptor_store = LandmarkDescriptorStore::from_visual_map(map);
714 self.localize_frame_image_with_extractor_and_descriptor_store(
715 frame_id,
716 camera_id,
717 image,
718 map,
719 &descriptor_store,
720 extractor,
721 )
722 }
723 }
724
725 pub fn localize_frame_image_with_extractor_and_descriptor_store<X>(
726 &self,
727 frame_id: FrameId,
728 camera_id: CameraId,
729 image: &X::Image,
730 map: &VisualMap,
731 descriptor_store: &LandmarkDescriptorStore,
732 extractor: &X,
733 ) -> Result<FrameLocalizationResult, X::Error>
734 where
735 X: FeatureExtractor,
736 {
737 let Some(camera) = map.cameras.get(&camera_id).cloned() else {
738 return Ok(FrameLocalizationResult {
739 frame_id,
740 result: LocalizationResult::failure(
741 LocalizationFailureReason::MissingCamera { camera_id },
742 0,
743 0,
744 0,
745 ),
746 });
747 };
748 let result = self.localize_image_with_extractor_and_descriptor_store(
749 image,
750 camera,
751 map,
752 descriptor_store,
753 extractor,
754 )?;
755 Ok(FrameLocalizationResult { frame_id, result })
756 }
757
758 pub fn localize_frames(
759 &self,
760 frames: &[Frame],
761 map: &VisualMap,
762 ) -> Vec<FrameLocalizationResult> {
763 let descriptor_store = LandmarkDescriptorStore::from_visual_map(map);
764 self.localize_frames_with_descriptor_store(frames, map, &descriptor_store)
765 }
766
767 pub fn localize_frame_with_descriptor_store(
768 &self,
769 frame: &Frame,
770 map: &VisualMap,
771 descriptor_store: &LandmarkDescriptorStore,
772 ) -> LocalizationResult {
773 let Some(camera) = map.cameras.get(&frame.camera_id).cloned() else {
774 return LocalizationResult::failure(
775 LocalizationFailureReason::MissingCamera {
776 camera_id: frame.camera_id,
777 },
778 0,
779 0,
780 0,
781 );
782 };
783 let query = QueryImage::from_frame(frame, camera);
784 self.localize_with_descriptor_store(&query, map, descriptor_store)
785 }
786
787 pub fn localize_frame_with_candidate_selector_and_descriptor_store<S2>(
788 &self,
789 frame: &Frame,
790 map: &VisualMap,
791 descriptor_store: &LandmarkDescriptorStore,
792 candidate_selector: S2,
793 ) -> LocalizationResult
794 where
795 S2: CandidateSelector + Clone,
796 {
797 let Some(camera) = map.cameras.get(&frame.camera_id).cloned() else {
798 return LocalizationResult::failure(
799 LocalizationFailureReason::MissingCamera {
800 camera_id: frame.camera_id,
801 },
802 0,
803 0,
804 0,
805 );
806 };
807 let query = QueryImage::from_frame(frame, camera);
808 self.localize_with_candidate_selector_and_descriptor_store(
809 &query,
810 map,
811 descriptor_store,
812 candidate_selector,
813 )
814 }
815
816 pub fn localize_frames_with_descriptor_store(
817 &self,
818 frames: &[Frame],
819 map: &VisualMap,
820 descriptor_store: &LandmarkDescriptorStore,
821 ) -> Vec<FrameLocalizationResult> {
822 frames
823 .iter()
824 .map(|frame| FrameLocalizationResult {
825 frame_id: frame.id,
826 result: self.localize_frame_with_descriptor_store(frame, map, descriptor_store),
827 })
828 .collect()
829 }
830
831 pub fn localize_with_candidate_selector_and_descriptor_store<S2>(
832 &self,
833 query: &QueryImage,
834 map: &VisualMap,
835 descriptor_store: &LandmarkDescriptorStore,
836 candidate_selector: S2,
837 ) -> LocalizationResult
838 where
839 S2: CandidateSelector + Clone,
840 {
841 self.run_localization(query, map, descriptor_store, candidate_selector, None)
842 }
843
844 pub fn localize_with_candidate_selector_and_descriptor_store_and_pose_prior<S2>(
845 &self,
846 query: &QueryImage,
847 map: &VisualMap,
848 descriptor_store: &LandmarkDescriptorStore,
849 candidate_selector: S2,
850 pose_prior: Option<&Pose>,
851 ) -> LocalizationResult
852 where
853 S2: CandidateSelector + Clone,
854 {
855 self.run_localization(query, map, descriptor_store, candidate_selector, pose_prior)
856 }
857
858 pub fn localize_with_descriptor_store(
859 &self,
860 query: &QueryImage,
861 map: &VisualMap,
862 descriptor_store: &LandmarkDescriptorStore,
863 ) -> LocalizationResult {
864 self.run_localization(
865 query,
866 map,
867 descriptor_store,
868 self.candidate_selector.clone(),
869 None,
870 )
871 }
872
873 pub fn localize_frame_with_projection_window_and_descriptor_store(
882 &self,
883 frame: &Frame,
884 map: &VisualMap,
885 descriptor_store: &LandmarkDescriptorStore,
886 pose_prior: &Pose,
887 candidate_radius: Option<f64>,
888 search_radius_px: f64,
889 ) -> LocalizationResult {
890 self.localize_frame_with_projection_window_descriptor_store_and_query_landmark_ratio(
891 frame,
892 map,
893 descriptor_store,
894 pose_prior,
895 candidate_radius,
896 search_radius_px,
897 None,
898 )
899 }
900
901 #[allow(clippy::too_many_arguments)]
905 pub fn localize_frame_with_projection_window_descriptor_store_and_query_landmark_ratio(
906 &self,
907 frame: &Frame,
908 map: &VisualMap,
909 descriptor_store: &LandmarkDescriptorStore,
910 pose_prior: &Pose,
911 candidate_radius: Option<f64>,
912 search_radius_px: f64,
913 max_query_landmark_distance_ratio: Option<f32>,
914 ) -> LocalizationResult {
915 let Some(camera) = map.cameras.get(&frame.camera_id).cloned() else {
916 return LocalizationResult::failure(
917 LocalizationFailureReason::MissingCamera {
918 camera_id: frame.camera_id,
919 },
920 0,
921 0,
922 0,
923 );
924 };
925 let query = QueryImage::from_frame(frame, camera);
926
927 if let Some(radius) = candidate_radius {
928 let radius_selector =
929 RadiusLandmarkSelector::new(pose_prior.camera_center_world(), radius);
930 let candidate_selector =
931 IntersectCandidateSelector::new(self.candidate_selector.clone(), radius_selector);
932 self.localize_with_projection_window_descriptor_store_and_query_landmark_ratio(
933 &query,
934 map,
935 descriptor_store,
936 candidate_selector,
937 pose_prior,
938 search_radius_px,
939 max_query_landmark_distance_ratio,
940 )
941 } else {
942 self.localize_with_projection_window_descriptor_store_and_query_landmark_ratio(
943 &query,
944 map,
945 descriptor_store,
946 self.candidate_selector.clone(),
947 pose_prior,
948 search_radius_px,
949 max_query_landmark_distance_ratio,
950 )
951 }
952 }
953
954 pub fn localize_with_projection_window_and_descriptor_store<S2>(
955 &self,
956 query: &QueryImage,
957 map: &VisualMap,
958 descriptor_store: &LandmarkDescriptorStore,
959 candidate_selector: S2,
960 pose_prior: &Pose,
961 search_radius_px: f64,
962 ) -> LocalizationResult
963 where
964 S2: CandidateSelector + Clone,
965 {
966 self.localize_with_projection_window_descriptor_store_and_query_landmark_ratio(
967 query,
968 map,
969 descriptor_store,
970 candidate_selector,
971 pose_prior,
972 search_radius_px,
973 None,
974 )
975 }
976
977 #[allow(clippy::too_many_arguments)]
981 pub fn localize_with_projection_window_descriptor_store_and_query_landmark_ratio<S2>(
982 &self,
983 query: &QueryImage,
984 map: &VisualMap,
985 descriptor_store: &LandmarkDescriptorStore,
986 candidate_selector: S2,
987 pose_prior: &Pose,
988 search_radius_px: f64,
989 max_query_landmark_distance_ratio: Option<f32>,
990 ) -> LocalizationResult
991 where
992 S2: CandidateSelector + Clone,
993 {
994 let correspondence_set = match ProjectionCorrespondenceBuilder::with_candidate_selector(
995 self.matcher.clone(),
996 candidate_selector,
997 )
998 .build_with_pose_prior_and_query_landmark_ratio(
999 query,
1000 map,
1001 descriptor_store,
1002 pose_prior,
1003 search_radius_px,
1004 max_query_landmark_distance_ratio,
1005 ) {
1006 Ok(correspondence_set) => correspondence_set,
1007 Err(error) => return result_from_correspondence_error(error),
1008 };
1009 self.estimate_and_gate(&query.camera, correspondence_set, Some(pose_prior))
1010 }
1011
1012 pub fn refine_frame_pose_with_local_map_and_descriptor_store(
1023 &self,
1024 frame: &Frame,
1025 map: &VisualMap,
1026 local_map_descriptor_store: &LandmarkDescriptorStore,
1027 estimated: &LocalizationResult,
1028 refinement_search_radius_px: f64,
1029 ) -> Option<LocalizationResult> {
1030 let estimated_pose = estimated.pose.as_ref()?;
1031 let camera = map.cameras.get(&frame.camera_id)?.clone();
1032 let query = QueryImage::from_frame(frame, camera.clone());
1033
1034 let harvested = ProjectionCorrespondenceBuilder::new(self.matcher.clone())
1035 .build_with_pose_prior(
1036 &query,
1037 map,
1038 local_map_descriptor_store,
1039 estimated_pose,
1040 refinement_search_radius_px,
1041 )
1042 .ok();
1043
1044 let mut seen_landmarks: HashSet<LandmarkId> = HashSet::new();
1045 let mut seen_query_indices: HashSet<usize> = HashSet::new();
1046 let mut correspondences = Vec::new();
1047 let mut query_indices = Vec::new();
1048 let mut landmark_ids = Vec::new();
1049
1050 for ((&query_index, &landmark_id), confidence) in estimated
1051 .inlier_query_indices
1052 .iter()
1053 .zip(estimated.inlier_landmark_ids.iter())
1054 .zip(estimated.inlier_confidences.iter().copied())
1055 {
1056 let Some(point2d) = frame.keypoints.get(query_index).copied() else {
1057 continue;
1058 };
1059 let Some(landmark) = map.landmarks.get(&landmark_id) else {
1060 continue;
1061 };
1062 if !seen_landmarks.insert(landmark_id) || !seen_query_indices.insert(query_index) {
1063 continue;
1064 }
1065 correspondences.push(Correspondence2D3D {
1066 point2d,
1067 point3d: landmark.position,
1068 confidence,
1069 });
1070 query_indices.push(query_index);
1071 landmark_ids.push(landmark_id);
1072 }
1073
1074 if let Some(harvested) = &harvested {
1075 for ((correspondence, &query_index), &landmark_id) in harvested
1076 .correspondences
1077 .iter()
1078 .zip(harvested.query_indices.iter())
1079 .zip(harvested.landmark_ids.iter())
1080 {
1081 if !seen_landmarks.insert(landmark_id) || !seen_query_indices.insert(query_index) {
1082 continue;
1083 }
1084 correspondences.push(correspondence.clone());
1085 query_indices.push(query_index);
1086 landmark_ids.push(landmark_id);
1087 }
1088 }
1089
1090 if same_inlier_assignment(&query_indices, &landmark_ids, estimated) {
1091 return None;
1092 }
1093
1094 let correspondence_count = correspondences.len();
1095 let confidence_weights = correspondence_confidence_weights(&correspondences);
1096 let report = self.pose_estimator.estimate_with_pose_prior_and_weights(
1097 &correspondences,
1098 &camera,
1099 Some(estimated_pose),
1100 confidence_weights.as_deref(),
1101 )?;
1102
1103 let inlier_query_indices = report
1104 .inliers
1105 .iter()
1106 .filter_map(|inlier| query_indices.get(*inlier).copied())
1107 .collect::<Vec<_>>();
1108 let inlier_landmark_ids = report
1109 .inliers
1110 .iter()
1111 .filter_map(|inlier| landmark_ids.get(*inlier).copied())
1112 .collect::<Vec<_>>();
1113 let inlier_confidences = report
1114 .inliers
1115 .iter()
1116 .filter_map(|inlier| correspondences.get(*inlier).map(|corr| corr.confidence))
1117 .collect::<Vec<_>>();
1118
1119 let result = LocalizationResult::success(LocalizationSuccess {
1120 pose: report.pose,
1121 candidate_landmark_count: correspondence_count,
1122 match_count: correspondence_count,
1123 correspondence_count,
1124 inliers: report.inliers,
1125 inlier_query_indices,
1126 inlier_landmark_ids,
1127 inlier_confidences,
1128 inlier_reprojection_errors: report.inlier_reprojection_errors,
1129 mean_reprojection_error: report.mean_reprojection_error,
1130 median_reprojection_error: report.median_reprojection_error,
1131 max_reprojection_error: report.max_reprojection_error,
1132 })
1133 .with_estimator_diagnostics(report.diagnostics);
1134
1135 Some(if passes_quality_gate(&result, &self.config) {
1136 result
1137 } else {
1138 result.rejected_by_quality_gate()
1139 })
1140 }
1141
1142 pub fn revise_frame_pose_with_local_map_and_descriptor_store(
1150 &self,
1151 frame: &Frame,
1152 map: &VisualMap,
1153 local_map_descriptor_store: &LandmarkDescriptorStore,
1154 estimated: &LocalizationResult,
1155 refinement_search_radius_px: f64,
1156 ) -> Option<LocalizationResult> {
1157 let estimated_pose = estimated.pose.as_ref()?;
1158 let camera = map.cameras.get(&frame.camera_id)?.clone();
1159 let query = QueryImage::from_frame(frame, camera);
1160 let correspondence_set = ProjectionCorrespondenceBuilder::new(self.matcher.clone())
1161 .build_with_pose_prior(
1162 &query,
1163 map,
1164 local_map_descriptor_store,
1165 estimated_pose,
1166 refinement_search_radius_px,
1167 )
1168 .ok()?;
1169 if same_inlier_assignment(
1170 &correspondence_set.query_indices,
1171 &correspondence_set.landmark_ids,
1172 estimated,
1173 ) {
1174 return None;
1175 }
1176 Some(self.estimate_and_gate(&query.camera, correspondence_set, Some(estimated_pose)))
1177 }
1178
1179 fn run_localization<S2>(
1180 &self,
1181 query: &QueryImage,
1182 map: &VisualMap,
1183 descriptor_store: &LandmarkDescriptorStore,
1184 candidate_selector: S2,
1185 pose_prior: Option<&Pose>,
1186 ) -> LocalizationResult
1187 where
1188 S2: CandidateSelector + Clone,
1189 {
1190 let correspondence_set = match CorrespondenceBuilder::with_candidate_selector(
1191 self.matcher.clone(),
1192 candidate_selector,
1193 )
1194 .build(query, map, descriptor_store)
1195 {
1196 Ok(correspondence_set) => correspondence_set,
1197 Err(error) => {
1198 return result_from_correspondence_error(error);
1199 }
1200 };
1201 self.estimate_and_gate(&query.camera, correspondence_set, pose_prior)
1202 }
1203
1204 pub fn localize_correspondences(
1208 &self,
1209 camera: &Camera,
1210 correspondence_set: CorrespondenceSet,
1211 ) -> LocalizationResult {
1212 self.estimate_and_gate(camera, correspondence_set, None)
1213 }
1214
1215 fn estimate_and_gate(
1222 &self,
1223 camera: &Camera,
1224 correspondence_set: CorrespondenceSet,
1225 pose_prior: Option<&Pose>,
1226 ) -> LocalizationResult {
1227 let match_count = correspondence_set.match_count;
1228 let candidate_landmark_count = correspondence_set.candidate_landmark_count;
1229 let correspondence_count = correspondence_set.correspondences.len();
1230
1231 let confidence_weights =
1232 correspondence_confidence_weights(&correspondence_set.correspondences);
1233 let pose_report = if pose_prior.is_some() {
1234 self.pose_estimator.estimate_with_pose_prior_and_weights(
1235 &correspondence_set.correspondences,
1236 camera,
1237 pose_prior,
1238 confidence_weights.as_deref(),
1239 )
1240 } else if let Some(weights) = confidence_weights.as_deref() {
1241 self.pose_estimator.estimate_with_weights(
1242 &correspondence_set.correspondences,
1243 camera,
1244 weights,
1245 )
1246 } else {
1247 self.pose_estimator
1248 .estimate(&correspondence_set.correspondences, camera)
1249 };
1250
1251 let Some(report) = pose_report else {
1252 let result = LocalizationResult::failure(
1253 LocalizationFailureReason::PoseEstimationFailed {
1254 correspondence_count,
1255 },
1256 candidate_landmark_count,
1257 match_count,
1258 correspondence_count,
1259 );
1260 if let Some(diagnostics) = self
1261 .pose_estimator
1262 .failure_diagnostics(&correspondence_set.correspondences, camera)
1263 {
1264 return result.with_pose_failure_diagnostics(diagnostics);
1265 }
1266 return result;
1267 };
1268
1269 let inlier_query_indices = report
1270 .inliers
1271 .iter()
1272 .filter_map(|inlier| correspondence_set.query_indices.get(*inlier).copied())
1273 .collect::<Vec<_>>();
1274 let inlier_landmark_ids = report
1275 .inliers
1276 .iter()
1277 .filter_map(|inlier| correspondence_set.landmark_ids.get(*inlier).copied())
1278 .collect::<Vec<_>>();
1279 let inlier_confidences = report
1280 .inliers
1281 .iter()
1282 .filter_map(|inlier| {
1283 correspondence_set
1284 .correspondences
1285 .get(*inlier)
1286 .map(|corr| corr.confidence)
1287 })
1288 .collect::<Vec<_>>();
1289
1290 let result = LocalizationResult::success(LocalizationSuccess {
1291 pose: report.pose,
1292 candidate_landmark_count,
1293 match_count,
1294 correspondence_count,
1295 inliers: report.inliers,
1296 inlier_query_indices,
1297 inlier_landmark_ids,
1298 inlier_confidences,
1299 inlier_reprojection_errors: report.inlier_reprojection_errors,
1300 mean_reprojection_error: report.mean_reprojection_error,
1301 median_reprojection_error: report.median_reprojection_error,
1302 max_reprojection_error: report.max_reprojection_error,
1303 })
1304 .with_estimator_diagnostics(report.diagnostics);
1305
1306 if passes_quality_gate(&result, &self.config) {
1307 result
1308 } else {
1309 result.rejected_by_quality_gate()
1310 }
1311 }
1312}
1313
1314fn correspondence_confidence_weights(
1315 correspondences: &[visloc_vision::pnp::Correspondence2D3D],
1316) -> Option<Vec<f32>> {
1317 let weights = correspondences
1318 .iter()
1319 .map(|correspondence| {
1320 correspondence
1321 .confidence
1322 .filter(|confidence| confidence.is_finite() && *confidence > 0.0)
1323 .unwrap_or(1.0)
1328 })
1329 .collect::<Vec<_>>();
1330 weights
1331 .iter()
1332 .zip(correspondences.iter())
1333 .any(|(weight, correspondence)| *weight > 0.0 && correspondence.confidence.is_some())
1334 .then_some(weights)
1335}
1336
1337fn same_inlier_assignment(
1343 query_indices: &[usize],
1344 landmark_ids: &[LandmarkId],
1345 estimated: &LocalizationResult,
1346) -> bool {
1347 let new_count = query_indices.len().min(landmark_ids.len());
1348 let old_count = estimated
1349 .inlier_query_indices
1350 .len()
1351 .min(estimated.inlier_landmark_ids.len());
1352 if new_count != old_count {
1353 return false;
1354 }
1355 let mut new_pairs = query_indices
1356 .iter()
1357 .copied()
1358 .zip(landmark_ids.iter().copied())
1359 .take(new_count)
1360 .collect::<Vec<_>>();
1361 let mut old_pairs = estimated
1362 .inlier_query_indices
1363 .iter()
1364 .copied()
1365 .zip(estimated.inlier_landmark_ids.iter().copied())
1366 .take(old_count)
1367 .collect::<Vec<_>>();
1368 new_pairs.sort_unstable();
1369 old_pairs.sort_unstable();
1370 new_pairs == old_pairs
1371}
1372
1373impl<X, M, S, E> ImageLocalizer<X, LocalizationPipeline<M, S, E>>
1374where
1375 X: FeatureExtractor,
1376 M: Matcher + Clone,
1377 S: CandidateSelector + Clone,
1378 E: RobustPoseEstimator + Clone,
1379{
1380 pub fn localize_image(
1381 &self,
1382 image: &X::Image,
1383 camera: Camera,
1384 map: &VisualMap,
1385 ) -> Result<LocalizationResult, X::Error> {
1386 self.pipeline
1387 .localize_image_with_extractor(image, camera, map, &self.extractor)
1388 }
1389
1390 pub fn localize_image_with_descriptor_store(
1391 &self,
1392 image: &X::Image,
1393 camera: Camera,
1394 map: &VisualMap,
1395 descriptor_store: &LandmarkDescriptorStore,
1396 ) -> Result<LocalizationResult, X::Error> {
1397 self.pipeline
1398 .localize_image_with_extractor_and_descriptor_store(
1399 image,
1400 camera,
1401 map,
1402 descriptor_store,
1403 &self.extractor,
1404 )
1405 }
1406
1407 pub fn localize_image_with_provider<P2>(
1408 &self,
1409 image: &X::Image,
1410 camera: Camera,
1411 provider: &P2,
1412 ) -> Result<LocalizationResult, X::Error>
1413 where
1414 P2: MapProvider + DescriptorProvider,
1415 {
1416 self.pipeline.localize_image_with_extractor_and_provider(
1417 image,
1418 camera,
1419 provider,
1420 &self.extractor,
1421 )
1422 }
1423
1424 pub fn localize_frame_image(
1425 &self,
1426 frame_id: FrameId,
1427 camera_id: CameraId,
1428 image: &X::Image,
1429 map: &VisualMap,
1430 ) -> Result<FrameLocalizationResult, X::Error> {
1431 self.pipeline.localize_frame_image_with_extractor(
1432 frame_id,
1433 camera_id,
1434 image,
1435 map,
1436 &self.extractor,
1437 )
1438 }
1439
1440 pub fn localize_frame_image_with_descriptor_store(
1441 &self,
1442 frame_id: FrameId,
1443 camera_id: CameraId,
1444 image: &X::Image,
1445 map: &VisualMap,
1446 descriptor_store: &LandmarkDescriptorStore,
1447 ) -> Result<FrameLocalizationResult, X::Error> {
1448 self.pipeline
1449 .localize_frame_image_with_extractor_and_descriptor_store(
1450 frame_id,
1451 camera_id,
1452 image,
1453 map,
1454 descriptor_store,
1455 &self.extractor,
1456 )
1457 }
1458
1459 pub fn localize_frame_image_with_provider<P2>(
1460 &self,
1461 frame_id: FrameId,
1462 camera_id: CameraId,
1463 image: &X::Image,
1464 provider: &P2,
1465 ) -> Result<FrameLocalizationResult, X::Error>
1466 where
1467 P2: MapProvider + DescriptorProvider,
1468 {
1469 self.pipeline
1470 .localize_frame_image_with_extractor_and_provider(
1471 frame_id,
1472 camera_id,
1473 image,
1474 provider,
1475 &self.extractor,
1476 )
1477 }
1478}
1479
1480pub fn localize(query: QueryImage, map: VisualMap) -> LocalizationResult {
1481 LocalizationPipeline::<BruteForceMatcher, AllLandmarksSelector, PnPRansac>::default()
1482 .localize(&query, &map)
1483}
1484
1485pub fn localize_frame(frame: Frame, map: VisualMap) -> LocalizationResult {
1486 LocalizationPipeline::<BruteForceMatcher, AllLandmarksSelector, PnPRansac>::default()
1487 .localize_frame(&frame, &map)
1488}
1489
1490pub fn localize_frames(frames: Vec<Frame>, map: VisualMap) -> Vec<FrameLocalizationResult> {
1491 LocalizationPipeline::<BruteForceMatcher, AllLandmarksSelector, PnPRansac>::default()
1492 .localize_frames(&frames, &map)
1493}
1494
1495pub fn localize_with_descriptor_store(
1496 query: QueryImage,
1497 map: VisualMap,
1498 descriptor_store: LandmarkDescriptorStore,
1499) -> LocalizationResult {
1500 LocalizationPipeline::<BruteForceMatcher, AllLandmarksSelector, PnPRansac>::default()
1501 .localize_with_descriptor_store(&query, &map, &descriptor_store)
1502}
1503
1504pub fn localize_frame_with_descriptor_store(
1505 frame: Frame,
1506 map: VisualMap,
1507 descriptor_store: LandmarkDescriptorStore,
1508) -> LocalizationResult {
1509 LocalizationPipeline::<BruteForceMatcher, AllLandmarksSelector, PnPRansac>::default()
1510 .localize_frame_with_descriptor_store(&frame, &map, &descriptor_store)
1511}
1512
1513pub fn localize_frames_with_descriptor_store(
1514 frames: Vec<Frame>,
1515 map: VisualMap,
1516 descriptor_store: LandmarkDescriptorStore,
1517) -> Vec<FrameLocalizationResult> {
1518 LocalizationPipeline::<BruteForceMatcher, AllLandmarksSelector, PnPRansac>::default()
1519 .localize_frames_with_descriptor_store(&frames, &map, &descriptor_store)
1520}
1521
1522fn query_from_features(camera: Camera, features: FeatureSet) -> QueryImage {
1523 QueryImage {
1524 camera,
1525 keypoints: features.keypoints,
1526 descriptors: features.descriptors,
1527 }
1528}
1529
1530const fn result_from_correspondence_error(error: CorrespondenceBuildError) -> LocalizationResult {
1531 match error {
1532 CorrespondenceBuildError::QueryFeatureShapeMismatch {
1533 keypoint_count,
1534 descriptor_count,
1535 } => LocalizationResult::failure(
1536 LocalizationFailureReason::QueryFeatureShapeMismatch {
1537 keypoint_count,
1538 descriptor_count,
1539 },
1540 0,
1541 0,
1542 0,
1543 ),
1544 CorrespondenceBuildError::NoCandidateLandmarks => {
1545 LocalizationResult::failure(LocalizationFailureReason::NoCandidateLandmarks, 0, 0, 0)
1546 }
1547 CorrespondenceBuildError::NoMapDescriptors {
1548 candidate_landmark_count,
1549 } => LocalizationResult::failure(
1550 LocalizationFailureReason::NoMapDescriptors,
1551 candidate_landmark_count,
1552 0,
1553 0,
1554 ),
1555 CorrespondenceBuildError::NoDescriptorMatches {
1556 candidate_landmark_count,
1557 } => LocalizationResult::failure(
1558 LocalizationFailureReason::NoDescriptorMatches,
1559 candidate_landmark_count,
1560 0,
1561 0,
1562 ),
1563 CorrespondenceBuildError::InvalidQueryLandmarkRatio => LocalizationResult::failure(
1564 LocalizationFailureReason::InvalidProjectionQueryLandmarkRatio,
1565 0,
1566 0,
1567 0,
1568 ),
1569 }
1570}
1571
1572fn passes_quality_gate(result: &LocalizationResult, config: &LocalizationConfig) -> bool {
1573 if result.inlier_count < config.min_inliers {
1574 return false;
1575 }
1576 if result.inlier_ratio < config.min_inlier_ratio {
1577 return false;
1578 }
1579 if let Some(max_error) = config.max_mean_reprojection_error {
1580 if result.reprojection_error.unwrap_or(f64::INFINITY) > max_error {
1581 return false;
1582 }
1583 }
1584 if let Some(max_error) = config.max_median_reprojection_error {
1585 if result.median_reprojection_error.unwrap_or(f64::INFINITY) > max_error {
1586 return false;
1587 }
1588 }
1589 if let Some(max_error) = config.max_reprojection_error {
1590 if result.max_reprojection_error.unwrap_or(f64::INFINITY) > max_error {
1591 return false;
1592 }
1593 }
1594 true
1595}
1596
1597#[cfg(test)]
1598mod confidence_weight_tests {
1599 use super::*;
1600 use nalgebra::{Point2, Point3};
1601 use visloc_vision::pnp::Correspondence2D3D;
1602
1603 fn correspondence(confidence: Option<f32>) -> Correspondence2D3D {
1604 Correspondence2D3D {
1605 point2d: Point2::origin(),
1606 point3d: Point3::new(0.0, 0.0, 1.0),
1607 confidence,
1608 }
1609 }
1610
1611 #[test]
1612 fn mixed_confidence_keeps_classical_correspondences_uniform() {
1613 let correspondences = vec![correspondence(None), correspondence(Some(0.25))];
1614 assert_eq!(
1615 correspondence_confidence_weights(&correspondences),
1616 Some(vec![1.0, 0.25])
1617 );
1618 }
1619
1620 #[test]
1621 fn all_classical_correspondences_keep_unweighted_path() {
1622 let correspondences = vec![correspondence(None), correspondence(None)];
1623 assert_eq!(correspondence_confidence_weights(&correspondences), None);
1624 }
1625}