1use nalgebra::{Point2, Point3};
13use thiserror::Error;
14use visloc_core::geometry::Pose;
15use visloc_core::types::{Camera, CameraModel};
16use visloc_vision::features::FeatureSet;
17
18use crate::global_sfm::{
19 reconstruct_global_sfm, GlobalReconstructionError, GlobalReconstructionTuning,
20};
21use crate::incremental_sfm::{
22 incremental_sfm, IncrementalSfmConfig, IncrementalSfmError, IncrementalSfmResult,
23 PairwiseMatches, SfmTrack,
24};
25
26#[derive(Debug, Clone, PartialEq)]
28pub struct PerImageCameras {
29 cameras: Vec<Camera>,
30 reference_index: usize,
31}
32
33#[derive(Debug, Clone, PartialEq, Error)]
36pub enum PerImageCameraError {
37 #[error("per-image calibration contains no cameras")]
38 Empty,
39 #[error("camera {index} uses unsupported model {model}")]
40 UnsupportedModel { index: usize, model: String },
41 #[error("camera {index} has {actual} parameters; not enough for the model's intrinsics")]
42 ParameterCount { index: usize, actual: usize },
43 #[error("camera {index} has invalid parameter {name}={value}")]
44 InvalidParameter {
45 index: usize,
46 name: &'static str,
47 value: f64,
48 },
49 #[error("camera index {index} is outside 0..{len}")]
50 ImageIndex { index: usize, len: usize },
51 #[error("per-image camera count {cameras} does not match feature count {features}")]
52 FeatureCount { cameras: usize, features: usize },
53 #[error("image dimension count {actual} does not match camera count {expected}")]
54 DimensionCount { actual: usize, expected: usize },
55 #[error(
56 "image {index} dimensions {actual_width}x{actual_height} do not match calibration {expected_width}x{expected_height}"
57 )]
58 DimensionMismatch {
59 index: usize,
60 actual_width: u32,
61 actual_height: u32,
62 expected_width: u32,
63 expected_height: u32,
64 },
65 #[error(
66 "image {image} keypoint {keypoint} is non-finite or outside {width}x{height}: ({x}, {y})"
67 )]
68 InvalidKeypoint {
69 image: usize,
70 keypoint: usize,
71 x: f64,
72 y: f64,
73 width: u32,
74 height: u32,
75 },
76 #[error("feature set {image} is invalid: {message}")]
77 InvalidFeatures { image: usize, message: String },
78}
79
80#[derive(Debug, Error)]
82pub enum PerImageCameraIncrementalError {
83 #[error("invalid per-image calibration: {0}")]
84 Camera(#[from] PerImageCameraError),
85 #[error("incremental SfM failed: {0}")]
86 Incremental(#[from] IncrementalSfmError),
87}
88
89#[derive(Debug, Error)]
91pub enum PerImageCameraGlobalError {
92 #[error("invalid per-image calibration: {0}")]
93 Camera(#[from] PerImageCameraError),
94 #[error("global SfM failed: {0}")]
95 Global(#[from] GlobalReconstructionError),
96}
97
98impl PerImageCameras {
99 pub fn new(cameras: Vec<Camera>) -> Result<Self, PerImageCameraError> {
103 if cameras.is_empty() {
104 return Err(PerImageCameraError::Empty);
105 }
106 for (index, camera) in cameras.iter().enumerate() {
107 if matches!(camera.model, CameraModel::Unknown(_)) {
108 return Err(PerImageCameraError::UnsupportedModel {
109 index,
110 model: format!("{:?}", camera.model),
111 });
112 }
113 let Some((fx, fy, cx, cy)) = camera.intrinsics() else {
114 return Err(PerImageCameraError::ParameterCount {
115 index,
116 actual: camera.params.len(),
117 });
118 };
119 if camera.width == 0 {
120 return Err(PerImageCameraError::InvalidParameter {
121 index,
122 name: "width",
123 value: camera.width as f64,
124 });
125 }
126 if camera.height == 0 {
127 return Err(PerImageCameraError::InvalidParameter {
128 index,
129 name: "height",
130 value: camera.height as f64,
131 });
132 }
133 for (name, value) in [("fx", fx), ("fy", fy), ("cx", cx), ("cy", cy)] {
134 if !value.is_finite() || ((name == "fx" || name == "fy") && value <= 0.0) {
135 return Err(PerImageCameraError::InvalidParameter { index, name, value });
136 }
137 }
138 if let Some(&value) = camera.params.iter().find(|value| !value.is_finite()) {
139 return Err(PerImageCameraError::InvalidParameter {
140 index,
141 name: "params",
142 value,
143 });
144 }
145 }
146 Ok(Self {
147 cameras,
148 reference_index: 0,
149 })
150 }
151
152 pub fn from_slice(cameras: &[Camera]) -> Result<Self, PerImageCameraError> {
154 Self::new(cameras.to_vec())
155 }
156
157 pub fn len(&self) -> usize {
158 self.cameras.len()
159 }
160
161 pub fn is_empty(&self) -> bool {
162 self.cameras.is_empty()
163 }
164
165 pub fn cameras(&self) -> &[Camera] {
166 &self.cameras
167 }
168
169 pub fn camera(&self, image_index: usize) -> Result<&Camera, PerImageCameraError> {
170 self.cameras
171 .get(image_index)
172 .ok_or(PerImageCameraError::ImageIndex {
173 index: image_index,
174 len: self.cameras.len(),
175 })
176 }
177
178 pub fn reference_camera(&self) -> &Camera {
181 &self.cameras[self.reference_index]
182 }
183
184 pub fn has_shared_geometry(&self) -> bool {
187 let reference = self.reference_camera();
188 self.cameras.iter().all(|camera| {
189 camera.model == reference.model
190 && camera.width == reference.width
191 && camera.height == reference.height
192 && camera.params == reference.params
193 })
194 }
195
196 pub fn validate_image_dimensions(
199 &self,
200 dimensions: &[(u32, u32)],
201 ) -> Result<(), PerImageCameraError> {
202 if dimensions.len() != self.cameras.len() {
203 return Err(PerImageCameraError::DimensionCount {
204 actual: dimensions.len(),
205 expected: self.cameras.len(),
206 });
207 }
208 for (index, (&(actual_width, actual_height), camera)) in
209 dimensions.iter().zip(&self.cameras).enumerate()
210 {
211 if actual_width != camera.width || actual_height != camera.height {
212 return Err(PerImageCameraError::DimensionMismatch {
213 index,
214 actual_width,
215 actual_height,
216 expected_width: camera.width,
217 expected_height: camera.height,
218 });
219 }
220 }
221 Ok(())
222 }
223
224 pub fn validate_features(&self, features: &[FeatureSet]) -> Result<(), PerImageCameraError> {
229 if features.len() != self.cameras.len() {
230 return Err(PerImageCameraError::FeatureCount {
231 cameras: self.cameras.len(),
232 features: features.len(),
233 });
234 }
235 for (image, (feature_set, camera)) in features.iter().zip(&self.cameras).enumerate() {
236 feature_set
237 .validate()
238 .map_err(|error| PerImageCameraError::InvalidFeatures {
239 image,
240 message: error.to_string(),
241 })?;
242 for (keypoint, point) in feature_set.keypoints.iter().enumerate() {
243 if !point.x.is_finite()
244 || !point.y.is_finite()
245 || point.x < 0.0
246 || point.y < 0.0
247 || point.x >= camera.width as f64
248 || point.y >= camera.height as f64
249 {
250 return Err(PerImageCameraError::InvalidKeypoint {
251 image,
252 keypoint,
253 x: point.x,
254 y: point.y,
255 width: camera.width,
256 height: camera.height,
257 });
258 }
259 }
260 }
261 Ok(())
262 }
263
264 pub fn to_reference_pixel(
268 &self,
269 image_index: usize,
270 pixel: &Point2<f64>,
271 ) -> Result<Point2<f64>, PerImageCameraError> {
272 let camera = self.camera(image_index)?;
273 if self.has_shared_geometry() {
274 return Ok(*pixel);
275 }
276 let normalized =
277 camera
278 .normalize_pixel(pixel)
279 .ok_or_else(|| PerImageCameraError::InvalidKeypoint {
280 image: image_index,
281 keypoint: 0,
282 x: pixel.x,
283 y: pixel.y,
284 width: camera.width,
285 height: camera.height,
286 })?;
287 self.reference_camera()
288 .project(&Point3::new(normalized.x, normalized.y, 1.0))
289 .ok_or_else(|| PerImageCameraError::InvalidKeypoint {
290 image: image_index,
291 keypoint: 0,
292 x: pixel.x,
293 y: pixel.y,
294 width: camera.width,
295 height: camera.height,
296 })
297 }
298
299 pub fn from_reference_pixel(
302 &self,
303 image_index: usize,
304 pixel: &Point2<f64>,
305 ) -> Result<Point2<f64>, PerImageCameraError> {
306 let camera = self.camera(image_index)?;
307 if self.has_shared_geometry() {
308 return Ok(*pixel);
309 }
310 let normalized = self
311 .reference_camera()
312 .normalize_pixel(pixel)
313 .ok_or_else(|| PerImageCameraError::InvalidKeypoint {
314 image: image_index,
315 keypoint: 0,
316 x: pixel.x,
317 y: pixel.y,
318 width: camera.width,
319 height: camera.height,
320 })?;
321 camera
322 .project(&Point3::new(normalized.x, normalized.y, 1.0))
323 .ok_or_else(|| PerImageCameraError::InvalidKeypoint {
324 image: image_index,
325 keypoint: 0,
326 x: pixel.x,
327 y: pixel.y,
328 width: camera.width,
329 height: camera.height,
330 })
331 }
332
333 pub fn canonicalize_features(
336 &self,
337 features: &[FeatureSet],
338 ) -> Result<Vec<FeatureSet>, PerImageCameraError> {
339 let mut canonical = features.to_vec();
343 self.canonicalize_features_in_place(&mut canonical)?;
344 Ok(canonical)
345 }
346
347 pub fn canonicalize_features_in_place(
355 &self,
356 features: &mut [FeatureSet],
357 ) -> Result<(), PerImageCameraError> {
358 self.validate_features(features)?;
359 if self.has_shared_geometry() {
360 return Ok(());
361 }
362 let canonical_keypoints = features
363 .iter()
364 .enumerate()
365 .map(|(image, feature_set)| {
366 feature_set
367 .keypoints
368 .iter()
369 .map(|pixel| self.to_reference_pixel(image, pixel))
370 .collect::<Result<Vec<_>, _>>()
371 })
372 .collect::<Result<Vec<_>, _>>()?;
373 for (feature_set, keypoints) in features.iter_mut().zip(canonical_keypoints) {
374 feature_set.keypoints = keypoints;
375 }
376 Ok(())
377 }
378}
379
380pub fn incremental_sfm_with_per_image_cameras(
387 cameras: &PerImageCameras,
388 features: &[FeatureSet],
389 pairwise: &[PairwiseMatches],
390 config: &IncrementalSfmConfig,
391) -> Result<IncrementalSfmResult, PerImageCameraIncrementalError> {
392 let canonical = cameras.canonicalize_features(features)?;
393 Ok(incremental_sfm(
394 cameras.reference_camera(),
395 &canonical,
396 pairwise,
397 config,
398 )?)
399}
400
401#[allow(clippy::type_complexity)]
405pub fn reconstruct_global_sfm_with_per_image_cameras(
406 cameras: &PerImageCameras,
407 features: &[FeatureSet],
408 pairwise: &[PairwiseMatches],
409 tuning: &GlobalReconstructionTuning,
410 mapper: &IncrementalSfmConfig,
411) -> Result<(Vec<Option<Pose>>, Vec<SfmTrack>, f64), PerImageCameraGlobalError> {
412 let canonical = cameras.canonicalize_features(features)?;
413 Ok(reconstruct_global_sfm(
414 cameras.reference_camera(),
415 &canonical,
416 pairwise,
417 tuning,
418 mapper,
419 )?)
420}
421
422#[cfg(test)]
423mod tests {
424 use super::*;
425 use nalgebra::{UnitQuaternion, Vector3};
426 use visloc_core::geometry::SE3;
427 use visloc_vision::pnp::Correspondence2D3D;
428 use visloc_vision::ransac::{PnPRansac, RobustPoseEstimator};
429 use visloc_vision::stereo_bootstrap::triangulate_two_view_left_frame;
430
431 fn camera(id: u64, width: u32, height: u32, fx: f64, fy: f64) -> Camera {
432 Camera::pinhole(
433 id,
434 width,
435 height,
436 fx,
437 fy,
438 width as f64 / 2.0,
439 height as f64 / 2.0,
440 )
441 }
442
443 fn features(points: Vec<Point2<f64>>) -> FeatureSet {
444 FeatureSet::new(points, vec![vec![1.0, 2.0]; 1]).unwrap()
445 }
446
447 #[test]
448 fn shared_geometry_is_an_exact_feature_noop() {
449 let cameras = PerImageCameras::new(vec![camera(4, 100, 80, 50.0, 50.0); 2]).unwrap();
450 let input = vec![
451 features(vec![Point2::new(10.0, 20.0)]),
452 features(vec![Point2::new(30.0, 40.0)]),
453 ];
454 assert_eq!(cameras.canonicalize_features(&input).unwrap(), input);
455 }
456
457 #[test]
458 fn different_focal_lengths_preserve_normalized_bearing() {
459 let first = camera(1, 100, 80, 50.0, 50.0);
460 let second = camera(2, 200, 160, 100.0, 80.0);
461 let cameras = PerImageCameras::new(vec![first.clone(), second.clone()]).unwrap();
462 let input = vec![
463 features(vec![Point2::new(50.0, 40.0)]),
464 features(vec![Point2::new(100.0, 80.0)]),
465 ];
466 let converted = cameras.canonicalize_features(&input).unwrap();
467 let normalized_before = second.normalize_pixel(&input[1].keypoints[0]).unwrap();
468 let normalized_after = first.normalize_pixel(&converted[1].keypoints[0]).unwrap();
469 assert!((normalized_before.x - normalized_after.x).abs() < 1e-12);
470 assert!((normalized_before.y - normalized_after.y).abs() < 1e-12);
471 }
472
473 #[test]
474 fn in_place_canonicalization_keeps_descriptor_storage_and_matches_owned() {
475 let first = camera(1, 100, 80, 50.0, 50.0);
476 let second = camera(2, 200, 160, 100.0, 80.0);
477 let cameras = PerImageCameras::new(vec![first, second]).unwrap();
478 let input = vec![
479 features(vec![Point2::new(50.0, 40.0)]),
480 features(vec![Point2::new(100.0, 80.0)]),
481 ];
482 let mut in_place = input.clone();
483 let descriptor_storage: Vec<*const Vec<f32>> = in_place
484 .iter()
485 .map(|feature_set| feature_set.descriptors.as_ptr())
486 .collect();
487 cameras
488 .canonicalize_features_in_place(&mut in_place)
489 .unwrap();
490 let owned = cameras.canonicalize_features(&input).unwrap();
491
492 assert_eq!(in_place, owned);
493 for (feature_set, storage) in in_place.iter().zip(descriptor_storage) {
494 assert_eq!(feature_set.descriptors.as_ptr(), storage);
495 }
496 assert_eq!(in_place[0].descriptors, input[0].descriptors);
497 assert_eq!(in_place[1].descriptors, input[1].descriptors);
498 }
499
500 #[test]
501 fn dimensions_and_parameters_are_checked() {
502 let invalid_camera = Camera {
503 id: 1,
504 model: CameraModel::Pinhole,
505 width: 100,
506 height: 80,
507 params: vec![50.0, f64::NAN, 50.0, 40.0],
508 };
509 assert!(matches!(
510 PerImageCameras::new(vec![invalid_camera]),
511 Err(PerImageCameraError::InvalidParameter { name: "fy", .. })
512 ));
513 let cameras = PerImageCameras::new(vec![camera(1, 100, 80, 50.0, 50.0)]).unwrap();
514 assert!(matches!(
515 cameras.validate_image_dimensions(&[(99, 80)]),
516 Err(PerImageCameraError::DimensionMismatch { .. })
517 ));
518 }
519
520 #[test]
521 fn distinct_cameras_preserve_triangulation_and_pnp_rays() {
522 let left = camera(7, 640, 480, 500.0, 500.0);
523 let right = camera(9, 800, 600, 700.0, 680.0);
524 let rig = PerImageCameras::new(vec![left.clone(), right.clone()]).unwrap();
525 let left_to_right = SE3::new(UnitQuaternion::identity(), Vector3::new(-0.25, 0.0, 0.0));
526 let points = [
527 Point3::new(-0.8, -0.6, 4.0),
528 Point3::new(0.7, -0.5, 4.5),
529 Point3::new(-0.6, 0.7, 5.0),
530 Point3::new(0.8, 0.6, 5.5),
531 Point3::new(-0.2, 0.1, 6.0),
532 Point3::new(0.4, -0.2, 6.5),
533 Point3::new(-0.5, 0.3, 7.0),
534 Point3::new(0.2, 0.5, 7.5),
535 ];
536 let mut pnp = Vec::with_capacity(points.len());
537 for point in points {
538 let left_pixel = left.project(&point).unwrap();
539 let right_pixel = right
540 .project(&left_to_right.transform_point(&point))
541 .unwrap();
542 let triangulated = triangulate_two_view_left_frame(
543 &left,
544 &right,
545 &left_to_right,
546 &left_pixel,
547 &right_pixel,
548 )
549 .unwrap();
550 assert!((triangulated - point).norm() < 1.0e-8);
551 pnp.push(Correspondence2D3D {
552 point2d: rig.to_reference_pixel(1, &right_pixel).unwrap(),
553 point3d: point,
554 confidence: None,
555 });
556 }
557 let report = PnPRansac::default()
558 .estimate(&pnp, rig.reference_camera())
559 .expect("canonicalized rays must support PnP");
560 assert!(report.inliers.len() >= 6);
561 assert!(
562 report
563 .pose
564 .world_to_camera
565 .rotation
566 .rotation_to(&left_to_right.rotation)
567 .angle()
568 < 1.0e-6
569 );
570 assert!(
571 (report.pose.world_to_camera.translation - left_to_right.translation).norm() < 1.0e-6,
572 "PnP translation drifted: {:?}",
573 report.pose.world_to_camera.translation
574 );
575 }
576
577 #[test]
578 fn fisheye_cameras_are_accepted_and_preserve_rays() {
579 let fisheye = Camera::opencv_fisheye(
580 1,
581 640,
582 480,
583 300.0,
584 300.0,
585 320.0,
586 240.0,
587 [-0.02, 0.01, 0.0, 0.0],
588 );
589 let pinhole = camera(2, 640, 480, 500.0, 500.0);
590 let rig = PerImageCameras::new(vec![pinhole, fisheye.clone()]).unwrap();
591
592 for point in [Point3::new(0.4, -0.2, 1.0), Point3::new(-0.6, 0.3, 1.2)] {
593 let fisheye_pixel = fisheye.project(&point).unwrap();
594 let canonical = rig.to_reference_pixel(1, &fisheye_pixel).unwrap();
595 let recovered = rig.from_reference_pixel(1, &canonical).unwrap();
596 let expected = fisheye.unit_ray_from_pixel(&fisheye_pixel).unwrap();
597 let actual = fisheye.unit_ray_from_pixel(&recovered).unwrap();
598 assert!(
599 (actual - expected).norm() < 1e-9,
600 "{actual:?} vs {expected:?}"
601 );
602 }
603
604 assert!(matches!(
605 PerImageCameras::new(vec![Camera {
606 id: 3,
607 model: CameraModel::Unknown("BOGUS".to_owned()),
608 width: 10,
609 height: 10,
610 params: vec![1.0; 4],
611 }]),
612 Err(PerImageCameraError::UnsupportedModel { .. })
613 ));
614 }
615
616 #[test]
617 fn fisheye_cameras_triangulate() {
618 let left = Camera::opencv_fisheye(
619 1,
620 640,
621 480,
622 300.0,
623 300.0,
624 320.0,
625 240.0,
626 [-0.02, 0.01, 0.0, 0.0],
627 );
628 let right = Camera::opencv_fisheye(
629 2,
630 640,
631 480,
632 310.0,
633 310.0,
634 320.0,
635 240.0,
636 [-0.02, 0.01, 0.0, 0.0],
637 );
638 let left_to_right = SE3::new(UnitQuaternion::identity(), Vector3::new(-0.2, 0.0, 0.0));
639 for point in [
640 Point3::new(-0.5, -0.3, 3.0),
641 Point3::new(0.6, 0.4, 4.0),
642 Point3::new(0.1, -0.6, 5.0),
643 ] {
644 let left_pixel = left.project(&point).unwrap();
645 let right_pixel = right
646 .project(&left_to_right.transform_point(&point))
647 .unwrap();
648 let triangulated = triangulate_two_view_left_frame(
649 &left,
650 &right,
651 &left_to_right,
652 &left_pixel,
653 &right_pixel,
654 )
655 .unwrap();
656 assert!(
657 (triangulated - point).norm() < 1e-6,
658 "{triangulated:?} vs {point:?}"
659 );
660 }
661 }
662}