Skip to main content

visloc_vision/
stereo_bootstrap.rs

1//! Two-view stereo bootstrap: match descriptors between a left/right camera
2//! pair, triangulate each pair via DLT, and return the surviving 3D points
3//! in the left camera frame.
4//!
5//! Companion to [`crate::stereo::triangulate_stereo_pixel`], which assumes
6//! a **rectified** stereo pair (shared intrinsics, identity relative rotation,
7//! pure-translation baseline along the left camera's `+x` axis). The general
8//! 6-DoF stereo case — EuRoC's cam0/cam1 are mounted with a small relative
9//! rotation in addition to the baseline translation — needs a full DLT
10//! triangulation working in normalised image coordinates.
11//!
12//! Inputs are assumed to be **already undistorted**: each `keypoint` in the
13//! supplied [`FeatureSet`] is the "ideal pinhole" pixel position implied by
14//! the camera's intrinsics. Descriptors come from the matcher's
15//! configuration. The bootstrap output is a list of surviving
16//! [`StereoBootstrapLandmark`] entries, one per `(left_index, right_index)`
17//! pair that:
18//!
19//! 1. matched under cross-checked brute-force descriptor matching (with the
20//!    configured Lowe ratio),
21//! 2. triangulated to a 3D point that lies in front of **both** cameras,
22//!    with `Z` in `[min_depth_meters, max_depth_meters]`, and
23//! 3. reprojected back to both pixel observations within
24//!    `max_reprojection_error_pixels`.
25//!
26//! Matches that fail any of those gates are silently dropped — the caller
27//! can keep using a fall-back depth seed for the unmatched left keypoints.
28
29use nalgebra::{Matrix3, Matrix3x4, Matrix4, Point2, Point3};
30use visloc_core::geometry::SE3;
31use visloc_core::types::Camera;
32
33use crate::features::FeatureSet;
34use crate::matching::{BruteForceMatcher, CrossCheckMatcher, Matcher};
35
36/// Tunable knobs for [`bootstrap_stereo_landmarks`].
37#[derive(Debug, Clone, Copy, PartialEq)]
38pub struct StereoBootstrapConfig {
39    /// Lowe ratio for the inner brute-force matcher. `None` disables the
40    /// ratio test; the default mirrors [`BruteForceMatcher::default`].
41    pub matcher_ratio: Option<f32>,
42    /// Minimum positive depth (in metres) the triangulated point must have
43    /// in **both** cameras. Values at or below this threshold are dropped
44    /// as numerically unstable far-field / behind-camera triangulations.
45    pub min_depth_meters: f64,
46    /// Maximum depth (in metres) the triangulated point may have in the
47    /// **left** camera frame. The default is loose enough to admit any
48    /// realistic indoor / outdoor scene while still rejecting matches that
49    /// land at infinity due to a near-zero parallax baseline.
50    pub max_depth_meters: f64,
51    /// Maximum allowed reprojection error (in pixels) for either of the
52    /// two observations. Larger errors are dropped as outliers.
53    pub max_reprojection_error_pixels: f64,
54    /// Independent one-sigma localisation error assigned to each of
55    /// `(u_left, v_left, u_right, v_right)`. The DLT Jacobian propagates this
56    /// pixel covariance into an anisotropic 3-D covariance for every survivor.
57    pub pixel_stddev_pixels: f64,
58}
59
60impl Default for StereoBootstrapConfig {
61    fn default() -> Self {
62        Self {
63            matcher_ratio: Some(0.8),
64            min_depth_meters: 0.1,
65            max_depth_meters: 50.0,
66            max_reprojection_error_pixels: 2.0,
67            pixel_stddev_pixels: 1.0,
68        }
69    }
70}
71
72/// A surviving triangulated stereo match.
73#[derive(Debug, Clone, PartialEq)]
74pub struct StereoBootstrapLandmark {
75    /// Index into `left_features.keypoints` (and `.descriptors`).
76    pub left_keypoint_index: usize,
77    /// Index into `right_features.keypoints`.
78    pub right_keypoint_index: usize,
79    /// Triangulated point expressed in the **left** camera frame. The
80    /// caller is expected to transform this to its desired frame via the
81    /// known world-to-left-camera pose.
82    pub point_left_camera_frame: Point3<f64>,
83    /// Reprojection error (in pixels) of the triangulated point in the
84    /// left image.
85    pub left_reprojection_error_pixels: f64,
86    /// Reprojection error (in pixels) of the triangulated point in the
87    /// right image.
88    pub right_reprojection_error_pixels: f64,
89    /// First-order covariance of the triangulated point in the left-camera
90    /// frame, propagated from the four input pixel coordinates.
91    pub point_covariance_left_camera_frame: Matrix3<f64>,
92}
93
94/// Match descriptors between the two feature sets, triangulate each
95/// surviving pair, and return the matches that pass the configured depth /
96/// reprojection-error gates. Results are returned in `left_keypoint_index`
97/// order.
98///
99/// `left_to_right` is the transform that maps a point expressed in the
100/// **left** camera frame to the **right** camera frame:
101/// `P_right = left_to_right.transform_point(P_left)`. For EuRoC the
102/// caller computes it from the two per-camera `T_BS` body-to-sensor
103/// matrices as `body_to_cam1.inverse().compose(&body_to_cam0)`.
104pub fn bootstrap_stereo_landmarks(
105    left_camera: &Camera,
106    right_camera: &Camera,
107    left_to_right: &SE3,
108    left_features: &FeatureSet,
109    right_features: &FeatureSet,
110    config: &StereoBootstrapConfig,
111) -> Vec<StereoBootstrapLandmark> {
112    if left_features.is_empty() || right_features.is_empty() {
113        return Vec::new();
114    }
115
116    let matcher = CrossCheckMatcher::new(BruteForceMatcher {
117        ratio: config.matcher_ratio,
118    });
119    let matches =
120        matcher.match_descriptors(&left_features.descriptors, &right_features.descriptors);
121
122    let mut survivors = Vec::with_capacity(matches.len());
123    for descriptor_match in matches {
124        let left_keypoint = left_features.keypoints[descriptor_match.query_index];
125        let right_keypoint = right_features.keypoints[descriptor_match.train_index];
126
127        let Some(point_left) = triangulate_two_view_left_frame(
128            left_camera,
129            right_camera,
130            left_to_right,
131            &left_keypoint,
132            &right_keypoint,
133        ) else {
134            continue;
135        };
136
137        // In-front-of-camera + depth-range gate on both cameras.
138        if !point_left.z.is_finite()
139            || point_left.z < config.min_depth_meters
140            || point_left.z > config.max_depth_meters
141        {
142            continue;
143        }
144        let point_right = left_to_right.transform_point(&point_left);
145        if !point_right.z.is_finite() || point_right.z < config.min_depth_meters {
146            continue;
147        }
148
149        // Reprojection-error gate (Euclidean pixel distance) on both
150        // observations. Failed projections (point exactly on principal ray
151        // with degenerate intrinsics) are treated as outliers.
152        let Some(left_projected) = left_camera.project(&point_left) else {
153            continue;
154        };
155        let Some(right_projected) = right_camera.project(&point_right) else {
156            continue;
157        };
158        let left_error = (left_projected - left_keypoint).norm();
159        let right_error = (right_projected - right_keypoint).norm();
160        if left_error > config.max_reprojection_error_pixels
161            || right_error > config.max_reprojection_error_pixels
162        {
163            continue;
164        }
165
166        let Some(point_covariance_left_camera_frame) = propagate_stereo_pixel_covariance(
167            left_camera,
168            right_camera,
169            left_to_right,
170            &left_keypoint,
171            &right_keypoint,
172            config.pixel_stddev_pixels,
173        ) else {
174            continue;
175        };
176
177        survivors.push(StereoBootstrapLandmark {
178            left_keypoint_index: descriptor_match.query_index,
179            right_keypoint_index: descriptor_match.train_index,
180            point_left_camera_frame: point_left,
181            left_reprojection_error_pixels: left_error,
182            right_reprojection_error_pixels: right_error,
183            point_covariance_left_camera_frame,
184        });
185    }
186
187    survivors.sort_by_key(|landmark| landmark.left_keypoint_index);
188    survivors
189}
190
191/// Triangulate known left→right correspondences (e.g. Basalt stereo optical
192/// flow) without descriptor matching. `correspondences` are
193/// `(left_keypoint_index, right_pixel)` pairs into `left_keypoints`.
194pub fn bootstrap_stereo_landmarks_from_correspondences(
195    left_camera: &Camera,
196    right_camera: &Camera,
197    left_to_right: &SE3,
198    left_keypoints: &[Point2<f64>],
199    correspondences: &[(usize, Point2<f64>)],
200    config: &StereoBootstrapConfig,
201) -> Vec<StereoBootstrapLandmark> {
202    let mut survivors = Vec::with_capacity(correspondences.len());
203    for &(left_keypoint_index, right_keypoint) in correspondences {
204        let Some(left_keypoint) = left_keypoints.get(left_keypoint_index).copied() else {
205            continue;
206        };
207        let Some(point_left) = triangulate_two_view_left_frame(
208            left_camera,
209            right_camera,
210            left_to_right,
211            &left_keypoint,
212            &right_keypoint,
213        ) else {
214            continue;
215        };
216        if !point_left.z.is_finite()
217            || point_left.z < config.min_depth_meters
218            || point_left.z > config.max_depth_meters
219        {
220            continue;
221        }
222        let point_right = left_to_right.transform_point(&point_left);
223        if !point_right.z.is_finite() || point_right.z < config.min_depth_meters {
224            continue;
225        }
226        let Some(left_projected) = left_camera.project(&point_left) else {
227            continue;
228        };
229        let Some(right_projected) = right_camera.project(&point_right) else {
230            continue;
231        };
232        let left_error = (left_projected - left_keypoint).norm();
233        let right_error = (right_projected - right_keypoint).norm();
234        if left_error > config.max_reprojection_error_pixels
235            || right_error > config.max_reprojection_error_pixels
236        {
237            continue;
238        }
239        let Some(point_covariance_left_camera_frame) = propagate_stereo_pixel_covariance(
240            left_camera,
241            right_camera,
242            left_to_right,
243            &left_keypoint,
244            &right_keypoint,
245            config.pixel_stddev_pixels,
246        ) else {
247            continue;
248        };
249        survivors.push(StereoBootstrapLandmark {
250            left_keypoint_index,
251            // Not indexed into a right FeatureSet; callers should keep the
252            // right pixel alongside this list (see optical-flow stereo path).
253            right_keypoint_index: 0,
254            point_left_camera_frame: point_left,
255            left_reprojection_error_pixels: left_error,
256            right_reprojection_error_pixels: right_error,
257            point_covariance_left_camera_frame,
258        });
259    }
260    survivors.sort_by_key(|landmark| landmark.left_keypoint_index);
261    survivors
262}
263
264/// Basalt `filterPoints` epipolar gate for already-undistorted stereo pairs.
265///
266/// Builds `E = [t]_× R` from `left_to_right` and drops correspondences whose
267/// unit-bearing Sampson-style score `|b_rightᵀ E b_left|` exceeds
268/// `max_epipolar_error` (Basalt default `0.005`).
269pub fn filter_correspondences_by_epipolar(
270    left_camera: &Camera,
271    right_camera: &Camera,
272    left_to_right: &SE3,
273    left_keypoints: &[Point2<f64>],
274    correspondences: &[(usize, Point2<f64>)],
275    max_epipolar_error: f64,
276) -> Vec<(usize, Point2<f64>)> {
277    let Some(essential) = essential_from_left_to_right(left_to_right) else {
278        return correspondences.to_vec();
279    };
280    correspondences
281        .iter()
282        .copied()
283        .filter(|&(left_idx, right_px)| {
284            let Some(left_px) = left_keypoints.get(left_idx).copied() else {
285                return false;
286            };
287            let Some(b0) = bearing_from_undistorted_pixel(left_camera, left_px) else {
288                return false;
289            };
290            let Some(b1) = bearing_from_undistorted_pixel(right_camera, right_px) else {
291                return false;
292            };
293            let err = (b1.transpose() * essential * b0).x.abs();
294            err <= max_epipolar_error
295        })
296        .collect()
297}
298
299fn essential_from_left_to_right(left_to_right: &SE3) -> Option<Matrix3<f64>> {
300    let rotation = left_to_right.rotation.to_rotation_matrix().into_inner();
301    let t = left_to_right.translation;
302    if t.norm() < 1e-12 {
303        return None;
304    }
305    Some(skew_symmetric(t) * rotation)
306}
307
308fn skew_symmetric(v: nalgebra::Vector3<f64>) -> Matrix3<f64> {
309    Matrix3::new(0.0, -v.z, v.y, v.z, 0.0, -v.x, -v.y, v.x, 0.0)
310}
311
312/// Ideal-pinhole bearing for an **already undistorted** pixel (no second
313/// radial inversion — OF / SuperPoint bootstrap paths undistort upstream).
314fn bearing_from_undistorted_pixel(
315    camera: &Camera,
316    pixel: Point2<f64>,
317) -> Option<nalgebra::Vector3<f64>> {
318    let (fx, fy, cx, cy) = camera.intrinsics()?;
319    if fx.abs() < 1e-12 || fy.abs() < 1e-12 {
320        return None;
321    }
322    let v = nalgebra::Vector3::new((pixel.x - cx) / fx, (pixel.y - cy) / fy, 1.0);
323    let n = v.norm();
324    if n < 1e-12 {
325        return None;
326    }
327    Some(v / n)
328}
329
330/// Propagate independent isotropic left/right keypoint noise through the
331/// general two-view DLT triangulator.
332///
333/// The returned first-order covariance is `J sigma² I Jᵀ`, where the columns
334/// of `J` are central finite differences with respect to
335/// `(u_left, v_left, u_right, v_right)`. This supports EuRoC's non-rectified
336/// 6-DoF cam0/cam1 transform while retaining the familiar quadratic growth of
337/// rectified-stereo depth uncertainty with range.
338pub fn propagate_stereo_pixel_covariance(
339    left_camera: &Camera,
340    right_camera: &Camera,
341    left_to_right: &SE3,
342    left_pixel: &Point2<f64>,
343    right_pixel: &Point2<f64>,
344    pixel_stddev_pixels: f64,
345) -> Option<Matrix3<f64>> {
346    if !pixel_stddev_pixels.is_finite() || pixel_stddev_pixels <= 0.0 {
347        return None;
348    }
349    let epsilon = (pixel_stddev_pixels * 1.0e-3).max(1.0e-4);
350    let mut jacobian = Matrix3x4::<f64>::zeros();
351    for coordinate in 0..4 {
352        let mut left_plus = *left_pixel;
353        let mut left_minus = *left_pixel;
354        let mut right_plus = *right_pixel;
355        let mut right_minus = *right_pixel;
356        match coordinate {
357            0 => {
358                left_plus.x += epsilon;
359                left_minus.x -= epsilon;
360            }
361            1 => {
362                left_plus.y += epsilon;
363                left_minus.y -= epsilon;
364            }
365            2 => {
366                right_plus.x += epsilon;
367                right_minus.x -= epsilon;
368            }
369            3 => {
370                right_plus.y += epsilon;
371                right_minus.y -= epsilon;
372            }
373            _ => unreachable!(),
374        }
375        let plus = triangulate_two_view_left_frame(
376            left_camera,
377            right_camera,
378            left_to_right,
379            &left_plus,
380            &right_plus,
381        )?;
382        let minus = triangulate_two_view_left_frame(
383            left_camera,
384            right_camera,
385            left_to_right,
386            &left_minus,
387            &right_minus,
388        )?;
389        jacobian.set_column(coordinate, &((plus - minus) / (2.0 * epsilon)));
390    }
391    let covariance = jacobian * jacobian.transpose() * pixel_stddev_pixels.powi(2);
392    if covariance.iter().all(|value| value.is_finite())
393        && covariance
394            .diagonal()
395            .iter()
396            .all(|variance| *variance >= 0.0)
397    {
398        Some((covariance + covariance.transpose()) * 0.5)
399    } else {
400        None
401    }
402}
403
404/// DLT triangulation for one (left, right) observation pair, returning the
405/// 3D point expressed in the **left** camera frame.
406///
407/// Left projection matrix is `[I | 0]` by construction; the right is
408/// `[R | t]` where `(R, t) = (left_to_right.rotation, left_to_right.translation)`.
409/// Two rows per camera give a 4x4 system whose smallest right-singular
410/// vector is the homogeneous solution. Returns `None` when either camera
411/// is non-pinhole, the homogeneous-component scale is degenerate, or the
412/// SVD fails to converge.
413pub fn triangulate_two_view_left_frame(
414    left_camera: &Camera,
415    right_camera: &Camera,
416    left_to_right: &SE3,
417    left_pixel: &Point2<f64>,
418    right_pixel: &Point2<f64>,
419) -> Option<Point3<f64>> {
420    let left_normalized = left_camera.normalize_pixel(left_pixel)?;
421    let right_normalized = right_camera.normalize_pixel(right_pixel)?;
422
423    let rotation = left_to_right.rotation.to_rotation_matrix().into_inner();
424    let t = left_to_right.translation;
425
426    // Right projection rows P1, P2, P3 ∈ R⁴.
427    let p1 = [rotation[(0, 0)], rotation[(0, 1)], rotation[(0, 2)], t.x];
428    let p2 = [rotation[(1, 0)], rotation[(1, 1)], rotation[(1, 2)], t.y];
429    let p3 = [rotation[(2, 0)], rotation[(2, 1)], rotation[(2, 2)], t.z];
430
431    // Stack constraints:
432    //   row 0: x_l e3 - e1   = (-1, 0, x_l, 0)
433    //   row 1: y_l e3 - e2   = (0, -1, y_l, 0)
434    //   row 2: x_r P3 - P1
435    //   row 3: y_r P3 - P2
436    let mut a = Matrix4::<f64>::zeros();
437    a[(0, 0)] = -1.0;
438    a[(0, 1)] = 0.0;
439    a[(0, 2)] = left_normalized.x;
440    a[(0, 3)] = 0.0;
441
442    a[(1, 0)] = 0.0;
443    a[(1, 1)] = -1.0;
444    a[(1, 2)] = left_normalized.y;
445    a[(1, 3)] = 0.0;
446
447    let x_r = right_normalized.x;
448    let y_r = right_normalized.y;
449    for column in 0..4 {
450        a[(2, column)] = x_r * p3[column] - p1[column];
451        a[(3, column)] = y_r * p3[column] - p2[column];
452    }
453
454    let svd = a.try_svd(false, true, f64::EPSILON * 5.0, 10_000)?;
455    let v_t = svd.v_t?;
456    let homogeneous = v_t.row(v_t.nrows() - 1);
457    let w = homogeneous[3];
458    if !w.is_finite() || w.abs() < 1.0e-12 {
459        return None;
460    }
461    Some(Point3::new(
462        homogeneous[0] / w,
463        homogeneous[1] / w,
464        homogeneous[2] / w,
465    ))
466}
467
468#[cfg(test)]
469mod tests {
470    use super::*;
471    use nalgebra::{UnitQuaternion, Vector3};
472
473    fn pinhole() -> Camera {
474        Camera::pinhole(1, 752, 480, 458.0, 457.0, 367.0, 248.0)
475    }
476
477    /// Project a left-frame point through `[I|0]` and `[R|t]` to produce
478    /// the synthetic left/right pixel pair. Used to seed round-trip tests.
479    fn project_left_and_right(
480        left_camera: &Camera,
481        right_camera: &Camera,
482        left_to_right: &SE3,
483        point_left: &Point3<f64>,
484    ) -> (Point2<f64>, Point2<f64>) {
485        let left_pixel = left_camera.project(point_left).expect("in front of left");
486        let point_right = left_to_right.transform_point(point_left);
487        let right_pixel = right_camera
488            .project(&point_right)
489            .expect("in front of right");
490        (left_pixel, right_pixel)
491    }
492
493    #[test]
494    fn dlt_triangulation_round_trips_pure_translation_baseline() {
495        let left = pinhole();
496        let right = pinhole();
497        // Pure-translation baseline along left +x (EuRoC-style nominal).
498        let left_to_right = SE3::new(UnitQuaternion::identity(), Vector3::new(-0.11, 0.0, 0.0));
499        let point = Point3::new(0.4, 0.2, 3.0);
500        let (l, r) = project_left_and_right(&left, &right, &left_to_right, &point);
501        let recovered = triangulate_two_view_left_frame(&left, &right, &left_to_right, &l, &r)
502            .expect("DLT succeeds for a valid in-front-of-both-cameras point");
503        assert!(
504            (recovered - point).norm() < 1.0e-9,
505            "round-trip error {} on {point:?}",
506            (recovered - point).norm()
507        );
508    }
509
510    #[test]
511    fn propagated_rectified_depth_stddev_matches_disparity_jacobian() {
512        let left = pinhole();
513        let right = pinhole();
514        let baseline = 0.11;
515        let left_to_right = SE3::new(
516            UnitQuaternion::identity(),
517            Vector3::new(-baseline, 0.0, 0.0),
518        );
519        let depth = 4.0;
520        let point = Point3::new(0.0, 0.0, depth);
521        let (left_pixel, right_pixel) =
522            project_left_and_right(&left, &right, &left_to_right, &point);
523        let sigma_pixels = 1.0;
524        let covariance = propagate_stereo_pixel_covariance(
525            &left,
526            &right,
527            &left_to_right,
528            &left_pixel,
529            &right_pixel,
530            sigma_pixels,
531        )
532        .expect("valid covariance");
533        let expected_depth_stddev =
534            2.0_f64.sqrt() * depth * depth * sigma_pixels / (458.0 * baseline);
535        let observed_depth_stddev = covariance[(2, 2)].sqrt();
536        assert!(
537            ((observed_depth_stddev - expected_depth_stddev) / expected_depth_stddev).abs() < 0.02,
538            "observed={observed_depth_stddev} expected={expected_depth_stddev}"
539        );
540    }
541
542    #[test]
543    fn propagated_stereo_depth_uncertainty_grows_quadratically_with_range() {
544        let left = pinhole();
545        let right = pinhole();
546        let left_to_right = SE3::new(UnitQuaternion::identity(), Vector3::new(-0.11, 0.0, 0.0));
547        let depth_stddev = |depth: f64| {
548            let point = Point3::new(0.1, 0.0, depth);
549            let (left_pixel, right_pixel) =
550                project_left_and_right(&left, &right, &left_to_right, &point);
551            propagate_stereo_pixel_covariance(
552                &left,
553                &right,
554                &left_to_right,
555                &left_pixel,
556                &right_pixel,
557                1.0,
558            )
559            .unwrap()[(2, 2)]
560                .sqrt()
561        };
562        let ratio = depth_stddev(8.0) / depth_stddev(4.0);
563        assert!((ratio - 4.0).abs() < 0.05, "observed ratio={ratio}");
564    }
565
566    #[test]
567    fn propagated_stereo_covariance_rejects_invalid_pixel_noise() {
568        let camera = pinhole();
569        let transform = SE3::new(UnitQuaternion::identity(), Vector3::new(-0.11, 0.0, 0.0));
570        assert!(propagate_stereo_pixel_covariance(
571            &camera,
572            &camera,
573            &transform,
574            &Point2::new(400.0, 240.0),
575            &Point2::new(380.0, 240.0),
576            0.0,
577        )
578        .is_none());
579    }
580
581    #[test]
582    fn dlt_triangulation_round_trips_with_rotated_right_camera() {
583        let left = pinhole();
584        let right = pinhole();
585        // Small yaw of the right camera plus a baseline offset — the
586        // unrectified EuRoC geometry has the right camera tilted by a
587        // few degrees relative to the left.
588        let yaw = 0.05_f64;
589        let rotation = UnitQuaternion::from_axis_angle(&nalgebra::Vector3::y_axis(), yaw);
590        let left_to_right = SE3::new(rotation, Vector3::new(-0.11, 0.0, 0.0));
591        let point = Point3::new(0.2, -0.1, 4.5);
592        let (l, r) = project_left_and_right(&left, &right, &left_to_right, &point);
593        let recovered = triangulate_two_view_left_frame(&left, &right, &left_to_right, &l, &r)
594            .expect("DLT succeeds");
595        assert!((recovered - point).norm() < 1.0e-8);
596    }
597
598    #[test]
599    fn bootstrap_recovers_metric_landmarks_under_known_correspondence() {
600        let left = pinhole();
601        let right = pinhole();
602        let left_to_right = SE3::new(UnitQuaternion::identity(), Vector3::new(-0.11, 0.0, 0.0));
603        // Three landmarks in front of both cameras. Descriptors are made
604        // distinctive (one-hot) so brute-force / cross-check matching is
605        // unambiguous.
606        let points = [
607            Point3::new(0.3, 0.1, 2.5),
608            Point3::new(-0.4, 0.2, 3.0),
609            Point3::new(0.1, -0.3, 4.0),
610        ];
611        let mut left_keypoints = Vec::new();
612        let mut right_keypoints = Vec::new();
613        let mut left_descriptors = Vec::new();
614        let mut right_descriptors = Vec::new();
615        for (i, point) in points.iter().enumerate() {
616            let (l, r) = project_left_and_right(&left, &right, &left_to_right, point);
617            left_keypoints.push(l);
618            right_keypoints.push(r);
619            let mut desc = vec![0.0_f32; points.len()];
620            desc[i] = 1.0;
621            left_descriptors.push(desc.clone());
622            right_descriptors.push(desc);
623        }
624        let left_features = FeatureSet::new(left_keypoints, left_descriptors).unwrap();
625        let right_features = FeatureSet::new(right_keypoints, right_descriptors).unwrap();
626        let survivors = bootstrap_stereo_landmarks(
627            &left,
628            &right,
629            &left_to_right,
630            &left_features,
631            &right_features,
632            &StereoBootstrapConfig::default(),
633        );
634        assert_eq!(survivors.len(), 3);
635        for survivor in &survivors {
636            let expected = points[survivor.left_keypoint_index];
637            assert!((survivor.point_left_camera_frame - expected).norm() < 1.0e-6);
638            assert_eq!(
639                survivor.left_keypoint_index, survivor.right_keypoint_index,
640                "one-hot descriptors must align query/train indices"
641            );
642            assert!(survivor.left_reprojection_error_pixels < 1.0e-6);
643            assert!(survivor.right_reprojection_error_pixels < 1.0e-6);
644        }
645    }
646
647    #[test]
648    fn bootstrap_drops_points_behind_either_camera() {
649        let left = pinhole();
650        let right = pinhole();
651        let left_to_right = SE3::new(UnitQuaternion::identity(), Vector3::new(-0.11, 0.0, 0.0));
652        // Two landmarks: one valid in front, one with a deliberately
653        // shifted right keypoint that will triangulate to either negative
654        // depth or large reprojection error.
655        let good_point = Point3::new(0.0, 0.0, 3.0);
656        let (good_l, good_r) = project_left_and_right(&left, &right, &left_to_right, &good_point);
657        // Add ~100 px to the right keypoint x — this corresponds to
658        // negative disparity (right > left in x) which the disparity-style
659        // geometry rules out as behind the camera.
660        let bad_l = Point2::new(380.0, 240.0);
661        let bad_r = Point2::new(380.0 + 200.0, 240.0);
662        let left_features = FeatureSet::new(
663            vec![good_l, bad_l],
664            vec![vec![1.0_f32, 0.0], vec![0.0, 1.0]],
665        )
666        .unwrap();
667        let right_features = FeatureSet::new(
668            vec![good_r, bad_r],
669            vec![vec![1.0_f32, 0.0], vec![0.0, 1.0]],
670        )
671        .unwrap();
672        let survivors = bootstrap_stereo_landmarks(
673            &left,
674            &right,
675            &left_to_right,
676            &left_features,
677            &right_features,
678            &StereoBootstrapConfig::default(),
679        );
680        assert_eq!(survivors.len(), 1);
681        assert_eq!(survivors[0].left_keypoint_index, 0);
682    }
683
684    #[test]
685    fn bootstrap_returns_empty_on_empty_input() {
686        let left = pinhole();
687        let right = pinhole();
688        let left_to_right = SE3::identity();
689        let empty = FeatureSet::new(Vec::new(), Vec::new()).unwrap();
690        let survivors = bootstrap_stereo_landmarks(
691            &left,
692            &right,
693            &left_to_right,
694            &empty,
695            &empty,
696            &StereoBootstrapConfig::default(),
697        );
698        assert!(survivors.is_empty());
699    }
700
701    #[test]
702    fn bootstrap_drops_matches_with_reprojection_above_threshold() {
703        let left = pinhole();
704        let right = pinhole();
705        let left_to_right = SE3::new(UnitQuaternion::identity(), Vector3::new(-0.11, 0.0, 0.0));
706        let point = Point3::new(0.0, 0.0, 3.0);
707        let (l, r) = project_left_and_right(&left, &right, &left_to_right, &point);
708        // Perturb the right keypoint by 5 px in y — that pulls the
709        // triangulated point off the epipolar line and the reprojection
710        // error blows past the 2-pixel default.
711        let perturbed_r = Point2::new(r.x, r.y + 5.0);
712        let left_features = FeatureSet::new(vec![l], vec![vec![1.0_f32]]).unwrap();
713        let right_features = FeatureSet::new(vec![perturbed_r], vec![vec![1.0_f32]]).unwrap();
714        let survivors = bootstrap_stereo_landmarks(
715            &left,
716            &right,
717            &left_to_right,
718            &left_features,
719            &right_features,
720            &StereoBootstrapConfig::default(),
721        );
722        assert!(
723            survivors.is_empty(),
724            "perturbed right keypoint must fail the reprojection gate"
725        );
726    }
727
728    #[test]
729    fn bootstrap_results_are_sorted_by_left_keypoint_index() {
730        let left = pinhole();
731        let right = pinhole();
732        let left_to_right = SE3::new(UnitQuaternion::identity(), Vector3::new(-0.11, 0.0, 0.0));
733        // Construct three matches whose train indices are deliberately
734        // reversed compared to the query order — the matcher would emit
735        // them in query order, but the post-sort must give us increasing
736        // left-keypoint indices regardless of how the matcher emitted them.
737        let points = [
738            Point3::new(0.3, 0.0, 2.0),
739            Point3::new(-0.2, 0.1, 3.0),
740            Point3::new(0.1, -0.2, 4.0),
741        ];
742        let mut left_keypoints = Vec::new();
743        let mut right_keypoints = Vec::new();
744        let mut left_descriptors = Vec::new();
745        let mut right_descriptors = Vec::new();
746        for (i, point) in points.iter().enumerate() {
747            let (l, r) = project_left_and_right(&left, &right, &left_to_right, point);
748            left_keypoints.push(l);
749            right_keypoints.push(r);
750            let mut desc = vec![0.0_f32; points.len()];
751            desc[i] = 1.0;
752            left_descriptors.push(desc.clone());
753            right_descriptors.push(desc);
754        }
755        let left_features = FeatureSet::new(left_keypoints, left_descriptors).unwrap();
756        let right_features = FeatureSet::new(right_keypoints, right_descriptors).unwrap();
757        let survivors = bootstrap_stereo_landmarks(
758            &left,
759            &right,
760            &left_to_right,
761            &left_features,
762            &right_features,
763            &StereoBootstrapConfig::default(),
764        );
765        assert_eq!(survivors.len(), 3);
766        let indices: Vec<usize> = survivors.iter().map(|s| s.left_keypoint_index).collect();
767        let mut sorted = indices.clone();
768        sorted.sort();
769        assert_eq!(indices, sorted);
770    }
771}