Skip to main content

visloc_rs/
two_view_vo.rs

1use std::collections::HashMap;
2use std::convert::Infallible;
3
4use nalgebra::{UnitQuaternion, Vector2, Vector3};
5use visloc_vision::two_view::{
6    EightPointEssentialMatrixEstimator, EssentialMatrixEstimator, EssentialRansac,
7    RelativePoseEstimator, TwoViewCorrespondence,
8};
9
10use crate::{
11    Camera, Frame, FrameId, TwoViewMatchSet, VisualOdometryEstimate, VisualOdometryFrontend, SE3,
12};
13
14#[derive(Debug, Clone, Copy, PartialEq)]
15pub struct TwoViewMatchVisualOdometryConfig {
16    pub min_matches: usize,
17    pub min_inliers: usize,
18    pub max_residual_pixels: f64,
19    pub pixel_translation_scale: f64,
20    pub forward_translation: f64,
21}
22
23impl Default for TwoViewMatchVisualOdometryConfig {
24    fn default() -> Self {
25        Self {
26            min_matches: 8,
27            min_inliers: 6,
28            max_residual_pixels: 3.0,
29            pixel_translation_scale: 0.01,
30            forward_translation: 0.0,
31        }
32    }
33}
34
35/// Lightweight two-view VO frontend that turns externally supplied
36/// correspondences into a translation-only relative-pose estimate.
37///
38/// Note: when this frontend produces a [`VisualOdometryEstimate`], the
39/// estimate's `mean_reprojection_error` field stores the mean inlier flow
40/// residual in pixels around the median two-view flow, not a 3D reprojection
41/// error. The field name is reused so callers and downstream
42/// `VisualOdometryPriorProvider` consumers do not need a separate diagnostic
43/// type; refer to the value as `mean_flow_residual_px` in user-facing logs and
44/// reports for the two-view-match case.
45#[derive(Debug, Clone, Default, PartialEq)]
46pub struct TwoViewMatchVisualOdometryFrontend {
47    config: TwoViewMatchVisualOdometryConfig,
48    matches_by_frame_pair: HashMap<(FrameId, FrameId), TwoViewMatchSet>,
49}
50
51impl TwoViewMatchVisualOdometryFrontend {
52    pub fn new(config: TwoViewMatchVisualOdometryConfig) -> Self {
53        Self {
54            config,
55            matches_by_frame_pair: HashMap::new(),
56        }
57    }
58
59    pub const fn config(&self) -> TwoViewMatchVisualOdometryConfig {
60        self.config
61    }
62
63    pub fn insert_matches(
64        &mut self,
65        previous_frame_id: FrameId,
66        current_frame_id: FrameId,
67        matches: TwoViewMatchSet,
68    ) {
69        self.matches_by_frame_pair
70            .insert((previous_frame_id, current_frame_id), matches);
71    }
72
73    pub fn with_matches(
74        mut self,
75        previous_frame_id: FrameId,
76        current_frame_id: FrameId,
77        matches: TwoViewMatchSet,
78    ) -> Self {
79        self.insert_matches(previous_frame_id, current_frame_id, matches);
80        self
81    }
82
83    pub fn matches_for(
84        &self,
85        previous_frame_id: FrameId,
86        current_frame_id: FrameId,
87    ) -> Option<&TwoViewMatchSet> {
88        self.matches_by_frame_pair
89            .get(&(previous_frame_id, current_frame_id))
90    }
91}
92
93impl VisualOdometryFrontend for TwoViewMatchVisualOdometryFrontend {
94    type Error = Infallible;
95
96    fn estimate_relative_pose(
97        &self,
98        previous_frame: &Frame,
99        current_frame: &Frame,
100    ) -> Result<Option<VisualOdometryEstimate>, Self::Error> {
101        let Some(matches) = self.matches_for(previous_frame.id, current_frame.id) else {
102            return Ok(None);
103        };
104
105        let Some((flow, inlier_count, mean_residual)) = estimate_translation_flow(
106            matches,
107            self.config.min_matches,
108            self.config.min_inliers,
109            self.config.max_residual_pixels,
110        ) else {
111            return Ok(None);
112        };
113
114        let previous_to_current = SE3::new(
115            UnitQuaternion::identity(),
116            Vector3::new(
117                flow.x * self.config.pixel_translation_scale,
118                flow.y * self.config.pixel_translation_scale,
119                self.config.forward_translation,
120            ),
121        );
122        let mut estimate =
123            VisualOdometryEstimate::new(previous_frame.id, current_frame.id, previous_to_current);
124        estimate.match_count = matches.len();
125        estimate.inlier_count = inlier_count;
126        estimate.mean_reprojection_error = Some(mean_residual);
127
128        Ok(Some(estimate))
129    }
130}
131
132fn estimate_translation_flow(
133    matches: &TwoViewMatchSet,
134    min_matches: usize,
135    min_inliers: usize,
136    max_residual_pixels: f64,
137) -> Option<(Vector2<f64>, usize, f64)> {
138    if matches.len() < min_matches {
139        return None;
140    }
141
142    let flows = matches
143        .matches()
144        .iter()
145        .map(|feature_match| feature_match.current_xy - feature_match.previous_xy)
146        .collect::<Vec<_>>();
147    let center = Vector2::new(
148        median(flows.iter().map(|flow| flow.x).collect()),
149        median(flows.iter().map(|flow| flow.y).collect()),
150    );
151
152    let inlier_flows = flows
153        .iter()
154        .copied()
155        .filter(|flow| (*flow - center).norm() <= max_residual_pixels)
156        .collect::<Vec<_>>();
157    if inlier_flows.len() < min_inliers {
158        return None;
159    }
160
161    let flow_sum = inlier_flows
162        .iter()
163        .fold(Vector2::zeros(), |sum, flow| sum + flow);
164    let flow = flow_sum / inlier_flows.len() as f64;
165    let mean_residual = inlier_flows
166        .iter()
167        .map(|inlier_flow| (*inlier_flow - flow).norm())
168        .sum::<f64>()
169        / inlier_flows.len() as f64;
170
171    Some((flow, inlier_flows.len(), mean_residual))
172}
173
174fn median(mut values: Vec<f64>) -> f64 {
175    values.sort_by(f64::total_cmp);
176    let mid = values.len() / 2;
177    if values.len().is_multiple_of(2) {
178        (values[mid - 1] + values[mid]) * 0.5
179    } else {
180        values[mid]
181    }
182}
183
184/// Configures the essential-matrix VO frontend. The Sampson threshold and
185/// RANSAC iteration count tune the inlier search; `default_translation_scale`
186/// is the scale applied when no per-pair scale is supplied.
187#[derive(Debug, Clone, Copy, PartialEq)]
188pub struct EssentialMatrixVisualOdometryConfig {
189    pub ransac_iterations: usize,
190    pub sampson_threshold: f64,
191    pub ransac_seed: u64,
192    pub default_translation_scale: f64,
193    pub min_inliers: usize,
194}
195
196impl Default for EssentialMatrixVisualOdometryConfig {
197    fn default() -> Self {
198        Self {
199            ransac_iterations: 256,
200            sampson_threshold: 5.0e-3,
201            ransac_seed: 7,
202            default_translation_scale: 1.0,
203            min_inliers: 8,
204        }
205    }
206}
207
208/// Two-view VO frontend backed by the classical essential-matrix RANSAC
209/// pipeline in `visloc-vision`. Compared to `TwoViewMatchVisualOdometryFrontend`
210/// — which estimates a translation-only flow — this frontend recovers a full
211/// SE3 relative pose (rotation + scaled translation) and reports inliers
212/// against the Sampson distance.
213///
214/// The translation is fundamentally up-to-scale. Callers can either:
215/// - Use `default_translation_scale` (a fixed metric scale, e.g., the typical
216///   inter-frame displacement);
217/// - Provide a per-pair scale through [`Self::insert_matches_with_scale`]
218///   sourced from GNSS displacement, the previous frame's translation, or
219///   another prior.
220///
221/// `VisualOdometryEstimate.mean_reprojection_error` stores the mean inlier
222/// Sampson distance in normalized image-plane units (i.e., divided by focal
223/// length). To convert to pixels, multiply by the camera's focal length.
224#[derive(Debug, Clone, PartialEq)]
225pub struct EssentialMatrixVisualOdometryFrontend {
226    estimator: RelativePoseEstimator,
227    camera: Camera,
228    matches_by_frame_pair: HashMap<(FrameId, FrameId), TwoViewMatchSet>,
229    scale_overrides: HashMap<(FrameId, FrameId), f64>,
230    min_inliers: usize,
231}
232
233impl EssentialMatrixVisualOdometryFrontend {
234    pub fn new(camera: Camera, config: EssentialMatrixVisualOdometryConfig) -> Self {
235        let estimator = RelativePoseEstimator {
236            ransac: EssentialRansac {
237                estimator: EightPointEssentialMatrixEstimator::default(),
238                config: visloc_vision::two_view::EssentialRansacConfig {
239                    iterations: config.ransac_iterations,
240                    sampson_threshold: config.sampson_threshold,
241                    seed: config.ransac_seed,
242                },
243            },
244            default_translation_scale: config.default_translation_scale,
245            ..RelativePoseEstimator::default()
246        };
247        Self {
248            estimator,
249            camera,
250            matches_by_frame_pair: HashMap::new(),
251            scale_overrides: HashMap::new(),
252            min_inliers: config.min_inliers,
253        }
254    }
255
256    pub const fn camera(&self) -> &Camera {
257        &self.camera
258    }
259
260    pub const fn min_inliers(&self) -> usize {
261        self.min_inliers
262    }
263
264    pub const fn default_translation_scale(&self) -> f64 {
265        self.estimator.default_translation_scale
266    }
267
268    pub fn insert_matches(
269        &mut self,
270        previous_frame_id: FrameId,
271        current_frame_id: FrameId,
272        matches: TwoViewMatchSet,
273    ) {
274        self.matches_by_frame_pair
275            .insert((previous_frame_id, current_frame_id), matches);
276    }
277
278    pub fn insert_matches_with_scale(
279        &mut self,
280        previous_frame_id: FrameId,
281        current_frame_id: FrameId,
282        matches: TwoViewMatchSet,
283        translation_scale: f64,
284    ) {
285        self.insert_matches(previous_frame_id, current_frame_id, matches);
286        self.scale_overrides
287            .insert((previous_frame_id, current_frame_id), translation_scale);
288    }
289
290    pub fn with_matches(
291        mut self,
292        previous_frame_id: FrameId,
293        current_frame_id: FrameId,
294        matches: TwoViewMatchSet,
295    ) -> Self {
296        self.insert_matches(previous_frame_id, current_frame_id, matches);
297        self
298    }
299
300    pub fn with_matches_and_scale(
301        mut self,
302        previous_frame_id: FrameId,
303        current_frame_id: FrameId,
304        matches: TwoViewMatchSet,
305        translation_scale: f64,
306    ) -> Self {
307        self.insert_matches_with_scale(
308            previous_frame_id,
309            current_frame_id,
310            matches,
311            translation_scale,
312        );
313        self
314    }
315
316    pub fn matches_for(
317        &self,
318        previous_frame_id: FrameId,
319        current_frame_id: FrameId,
320    ) -> Option<&TwoViewMatchSet> {
321        self.matches_by_frame_pair
322            .get(&(previous_frame_id, current_frame_id))
323    }
324
325    fn translation_scale_for(&self, previous_frame_id: FrameId, current_frame_id: FrameId) -> f64 {
326        self.scale_overrides
327            .get(&(previous_frame_id, current_frame_id))
328            .copied()
329            .unwrap_or(self.estimator.default_translation_scale)
330    }
331}
332
333impl VisualOdometryFrontend for EssentialMatrixVisualOdometryFrontend {
334    type Error = Infallible;
335
336    fn estimate_relative_pose(
337        &self,
338        previous_frame: &Frame,
339        current_frame: &Frame,
340    ) -> Result<Option<VisualOdometryEstimate>, Self::Error> {
341        let Some(matches) = self.matches_for(previous_frame.id, current_frame.id) else {
342            return Ok(None);
343        };
344        if matches.len()
345            < self
346                .estimator
347                .ransac
348                .estimator
349                .minimum_correspondences()
350                .max(self.min_inliers)
351        {
352            return Ok(None);
353        }
354        let correspondences: Vec<TwoViewCorrespondence> = matches
355            .matches()
356            .iter()
357            .map(|feature_match| TwoViewCorrespondence {
358                previous_xy: feature_match.previous_xy,
359                current_xy: feature_match.current_xy,
360            })
361            .collect();
362        let scale = self.translation_scale_for(previous_frame.id, current_frame.id);
363        let Some(relative_pose) =
364            self.estimator
365                .estimate_with_scale(&correspondences, &self.camera, scale)
366        else {
367            return Ok(None);
368        };
369        if relative_pose.inliers.len() < self.min_inliers {
370            return Ok(None);
371        }
372        let mut estimate = VisualOdometryEstimate::new(
373            previous_frame.id,
374            current_frame.id,
375            relative_pose.previous_to_current,
376        );
377        estimate.match_count = matches.len();
378        estimate.inlier_count = relative_pose.inliers.len();
379        estimate.mean_reprojection_error = Some(relative_pose.mean_sampson_error);
380        Ok(Some(estimate))
381    }
382}