Skip to main content

visloc_objects/
metric.rs

1//! Metric 3D objects from object tracks and metric camera poses (Phase 3 of
2//! `docs/object_metric_slam_plan.md`, static objects).
3//!
4//! The monocular-inertial VIO's poses are metric thanks to the IMU. So feature
5//! tracks triangulated with them are metric too, and so is an upright box
6//! fitted to those points. The pipeline:
7//!
8//! 1. Collect the feature tracks seen inside an object's 2D boxes.
9//! 2. Triangulate each one from its observations ([`triangulate`]): camera
10//!    poses (camera to world, from the VIO) and unit bearings (from the camera
11//!    model, which this module does not need to know).
12//! 3. Fit a gravity-aligned box to the points ([`fit_upright_box`]). The world
13//!    z axis is up, as in Basalt's gravity-aligned world frame.
14//!
15//! Every estimate records where its scale came from ([`ScaleSource`]). Class
16//! size priors ([`plausible_size`]) are used only to flag implausible
17//! results, never to set a scale: with a wrong scale, the sizes come out
18//! wrong.
19
20use nalgebra::{Isometry3, Matrix3, Point3, Vector2, Vector3};
21
22/// One observation of a feature: the camera pose (camera to world) and the
23/// unit bearing of the feature in the camera frame.
24#[derive(Debug, Clone, Copy, PartialEq)]
25pub struct BearingObservation {
26    pub camera_to_world: Isometry3<f64>,
27    pub bearing: Vector3<f64>,
28}
29
30/// Acceptance tests of [`triangulate`].
31#[derive(Debug, Clone, Copy, PartialEq)]
32pub struct TriangulationParams {
33    /// Observations a track needs (3).
34    pub min_observations: usize,
35    /// Largest angle between two of its world rays must exceed this (2°).
36    pub min_parallax_rad: f64,
37    /// Every ray must pass within this angle of the point (0.3°).
38    pub max_ray_error_rad: f64,
39    /// The point must be at least this far in front of every camera (0.1 m).
40    pub min_depth: f64,
41}
42
43impl Default for TriangulationParams {
44    fn default() -> Self {
45        Self {
46            min_observations: 3,
47            min_parallax_rad: 2f64.to_radians(),
48            max_ray_error_rad: 0.3f64.to_radians(),
49            min_depth: 0.1,
50        }
51    }
52}
53
54/// The point closest to all the observation rays (least squares), if the
55/// rays diverge enough and the point is in front of, and close to, every ray.
56pub fn triangulate(
57    observations: &[BearingObservation],
58    params: &TriangulationParams,
59) -> Option<Point3<f64>> {
60    if observations.len() < params.min_observations.max(2) {
61        return None;
62    }
63    let rays: Vec<(Vector3<f64>, Vector3<f64>)> = observations
64        .iter()
65        .map(|o| {
66            let direction = (o.camera_to_world.rotation * o.bearing).try_normalize(1e-12)?;
67            Some((o.camera_to_world.translation.vector, direction))
68        })
69        .collect::<Option<_>>()?;
70    let parallax = rays
71        .iter()
72        .enumerate()
73        .flat_map(|(i, a)| rays[i + 1..].iter().map(move |b| a.1.angle(&b.1)))
74        .fold(0.0, f64::max);
75    if parallax < params.min_parallax_rad {
76        return None;
77    }
78    let mut a = Matrix3::zeros();
79    let mut b = Vector3::zeros();
80    for (center, direction) in &rays {
81        let projector = Matrix3::identity() - direction * direction.transpose();
82        a += projector;
83        b += projector * center;
84    }
85    let point = a.cholesky()?.solve(&b);
86    for (center, direction) in &rays {
87        let offset = point - center;
88        if offset.dot(direction) < params.min_depth
89            || offset.angle(direction) > params.max_ray_error_rad
90        {
91            return None;
92        }
93    }
94    Some(Point3::from(point))
95}
96
97/// A gravity-aligned box. `length` (the longer side) runs along the heading
98/// `yaw` (radians from world x towards world y), `width` across it, `height`
99/// along world z.
100#[derive(Debug, Clone, Copy, PartialEq)]
101pub struct UprightBox {
102    pub center: Point3<f64>,
103    pub length: f64,
104    pub width: f64,
105    pub height: f64,
106    pub yaw: f64,
107}
108
109/// Robustness settings of [`fit_upright_box`].
110#[derive(Debug, Clone, Copy, PartialEq)]
111pub struct BoxFitParams {
112    /// Points needed after outlier removal (6).
113    pub min_points: usize,
114    /// Points farther from the median point than this many scaled median
115    /// absolute deviations are outliers, such as background seen through or
116    /// beside the object (3).
117    pub outlier_mads: f64,
118    /// Extents are taken between this fraction and one minus it of the
119    /// points along each axis (0.02), so a few stray points do not inflate
120    /// the box.
121    pub extent_quantile: f64,
122}
123
124impl Default for BoxFitParams {
125    fn default() -> Self {
126        Self {
127            min_points: 6,
128            outlier_mads: 3.0,
129            extent_quantile: 0.02,
130        }
131    }
132}
133
134/// Fit an upright box to `points` (world z up): drop outliers far from the
135/// median point, then take the heading whose quantile rectangle has the
136/// smallest area, and the quantile extents along it, across it and up. Points on an object's
137/// visible surfaces only cover part of it, so the box can be smaller than the
138/// object.
139pub fn fit_upright_box(points: &[Point3<f64>], params: &BoxFitParams) -> Option<UprightBox> {
140    let median_point = Point3::new(
141        median(points.iter().map(|p| p.x).collect())?,
142        median(points.iter().map(|p| p.y).collect())?,
143        median(points.iter().map(|p| p.z).collect())?,
144    );
145    let distances: Vec<f64> = points.iter().map(|p| (p - median_point).norm()).collect();
146    let spread = 1.4826 * median(distances.clone())?;
147    let inliers: Vec<Point3<f64>> = points
148        .iter()
149        .zip(&distances)
150        .filter(|(_, d)| spread == 0.0 || **d <= params.outlier_mads * spread)
151        .map(|(p, _)| *p)
152        .collect();
153    if inliers.len() < params.min_points {
154        return None;
155    }
156    // Heading: the yaw whose rectangle of quantile extents has the smallest
157    // area, searched in 0.5° steps over a quarter turn (the main axis of the
158    // scatter is unstable for near-square footprints).
159    let q = params.extent_quantile;
160    let extents = |axis: Vector2<f64>| -> Option<(f64, f64)> {
161        let values: Vec<f64> = inliers
162            .iter()
163            .map(|p| axis.dot(&Vector2::new(p.x, p.y)))
164            .collect();
165        Some((quantile(values.clone(), q)?, quantile(values, 1.0 - q)?))
166    };
167    let axes = |yaw: f64| {
168        (
169            Vector2::new(yaw.cos(), yaw.sin()),
170            Vector2::new(-yaw.sin(), yaw.cos()),
171        )
172    };
173    let area = |yaw: f64| -> Option<f64> {
174        let (heading, across) = axes(yaw);
175        let ((l0, l1), (w0, w1)) = (extents(heading)?, extents(across)?);
176        Some((l1 - l0) * (w1 - w0))
177    };
178    let mut yaw = (0..180)
179        .map(|step| (step as f64 * 0.5).to_radians())
180        .filter_map(|yaw| Some((yaw, area(yaw)?)))
181        .min_by(|a, b| a.1.total_cmp(&b.1))?
182        .0;
183    let (heading, across) = axes(yaw);
184    let ((l0, l1), (w0, w1)) = (extents(heading)?, extents(across)?);
185    let center_xy = heading * (0.5 * (l0 + l1)) + across * (0.5 * (w0 + w1));
186    let (mut length, mut width) = (l1 - l0, w1 - w0);
187    if width > length {
188        // Report the longer side as the length.
189        std::mem::swap(&mut length, &mut width);
190        yaw += std::f64::consts::FRAC_PI_2;
191    }
192    let heights: Vec<f64> = inliers.iter().map(|p| p.z).collect();
193    let (h0, h1) = (quantile(heights.clone(), q)?, quantile(heights, 1.0 - q)?);
194    Some(UprightBox {
195        center: Point3::new(center_xy.x, center_xy.y, 0.5 * (h0 + h1)),
196        length,
197        width,
198        height: h1 - h0,
199        yaw,
200    })
201}
202
203/// Where an estimate's metric scale comes from.
204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
205pub enum ScaleSource {
206    /// Feature tracks triangulated with the metric VIO poses (static objects).
207    Triangulated,
208    /// The camera's metric height above the ground, through the object's
209    /// ground contact (objects that move; [`crate::ground`]).
210    GroundContact,
211}
212
213/// A metric object estimate.
214#[derive(Debug, Clone, Copy, PartialEq)]
215pub struct ObjectEstimate {
216    pub object_id: u64,
217    pub class_id: u32,
218    pub upright_box: UprightBox,
219    /// Triangulated points that made it into the box fit.
220    pub points: usize,
221    pub scale_source: ScaleSource,
222}
223
224/// Triangulate an object's feature tracks and fit its upright box.
225pub fn estimate_static_object(
226    object_id: u64,
227    class_id: u32,
228    tracks: &[Vec<BearingObservation>],
229    triangulation: &TriangulationParams,
230    fit: &BoxFitParams,
231) -> Option<ObjectEstimate> {
232    let points: Vec<Point3<f64>> = tracks
233        .iter()
234        .filter_map(|track| triangulate(track, triangulation))
235        .collect();
236    let upright_box = fit_upright_box(&points, fit)?;
237    Some(ObjectEstimate {
238        object_id,
239        class_id,
240        upright_box,
241        points: points.len(),
242        scale_source: ScaleSource::Triangulated,
243    })
244}
245
246/// Rough size ranges of common COCO classes, in metres: the largest
247/// dimension (length, width or height) an object of the class should have.
248/// Only for flagging implausible estimates; see the module docs.
249pub fn plausible_size(class_id: u32) -> Option<(f64, f64)> {
250    Some(match class_id {
251        0 => (0.9, 2.2),    // person (height, or length when lying)
252        1 => (1.2, 2.2),    // bicycle
253        2 => (3.0, 6.0),    // car
254        3 => (1.5, 2.6),    // motorcycle
255        5 => (8.0, 20.0),   // bus
256        7 => (4.0, 20.0),   // truck
257        16 => (0.3, 1.3),   // dog
258        39 => (0.15, 0.45), // bottle
259        41 => (0.06, 0.25), // cup
260        56 => (0.5, 1.3),   // chair
261        57 => (1.2, 3.0),   // couch
262        58 => (0.2, 1.5),   // potted plant
263        60 => (0.7, 2.5),   // dining table
264        62 => (0.3, 2.0),   // tv / monitor
265        63 => (0.25, 0.5),  // laptop
266        66 => (0.25, 0.6),  // keyboard
267        73 => (0.12, 0.45), // book
268        74 => (0.15, 0.6),  // clock
269        _ => return None,
270    })
271}
272
273fn median(values: Vec<f64>) -> Option<f64> {
274    quantile(values, 0.5)
275}
276
277/// Linear-interpolated quantile of `values`, `q` in [0, 1].
278fn quantile(mut values: Vec<f64>, q: f64) -> Option<f64> {
279    if values.is_empty() || values.iter().any(|v| !v.is_finite()) {
280        return None;
281    }
282    values.sort_by(f64::total_cmp);
283    let position = q.clamp(0.0, 1.0) * (values.len() - 1) as f64;
284    let (low, high) = (position.floor() as usize, position.ceil() as usize);
285    Some(values[low] + (values[high] - values[low]) * (position - low as f64))
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291    use nalgebra::{Translation3, UnitQuaternion};
292    use rand::rngs::SmallRng;
293    use rand::{Rng, SeedableRng};
294
295    /// A camera at `position` looking at `target` (camera z forward, y down,
296    /// world z up), as camera-to-world.
297    fn look_at(position: Vector3<f64>, target: Vector3<f64>) -> Isometry3<f64> {
298        let z = (target - position).normalize();
299        let x = z.cross(&Vector3::z()).normalize();
300        let y = z.cross(&x);
301        let rotation = UnitQuaternion::from_rotation_matrix(
302            &nalgebra::Rotation3::from_matrix_unchecked(Matrix3::from_columns(&[x, y, z])),
303        );
304        Isometry3::from_parts(Translation3::from(position), rotation)
305    }
306
307    fn observe(pose: &Isometry3<f64>, point: &Point3<f64>) -> BearingObservation {
308        BearingObservation {
309            camera_to_world: *pose,
310            bearing: (pose.inverse() * point).coords.normalize(),
311        }
312    }
313
314    #[test]
315    fn triangulates_exact_rays_and_rejects_bad_geometry() {
316        let point = Point3::new(1.0, 3.0, 0.5);
317        let poses: Vec<_> = (0..4)
318            .map(|k| look_at(Vector3::new(0.2 * k as f64, 0.0, 1.0), point.coords))
319            .collect();
320        let observations: Vec<_> = poses.iter().map(|p| observe(p, &point)).collect();
321        let found = triangulate(&observations, &TriangulationParams::default()).unwrap();
322        assert!((found - point).norm() < 1e-9);
323        // The same camera position four times: no parallax.
324        let still: Vec<_> = (0..4).map(|_| observe(&poses[0], &point)).collect();
325        assert!(triangulate(&still, &TriangulationParams::default()).is_none());
326        // A ray pointing well away from the others.
327        let mut bent = observations.clone();
328        bent[2].bearing = (bent[2].bearing + Vector3::new(0.05, 0.0, 0.0)).normalize();
329        assert!(triangulate(&bent, &TriangulationParams::default()).is_none());
330        // Too few observations.
331        assert!(triangulate(&observations[..2], &TriangulationParams::default()).is_none());
332    }
333
334    /// Points spread over the faces of a `length × width × height` box
335    /// standing on the ground at `center_xy`, turned by `yaw`.
336    fn box_points(
337        rng: &mut SmallRng,
338        center_xy: (f64, f64),
339        size: (f64, f64, f64),
340        yaw: f64,
341        count: usize,
342    ) -> Vec<Point3<f64>> {
343        let (l, w, h) = size;
344        (0..count)
345            .map(|_| {
346                let mut local = Vector3::new(
347                    rng.gen_range(-0.5..0.5) * l,
348                    rng.gen_range(-0.5..0.5) * w,
349                    rng.gen_range(0.0..1.0) * h,
350                );
351                // Put each point on one of the four sides or the top.
352                match rng.gen_range(0..5) {
353                    0 => local.x = -0.5 * l,
354                    1 => local.x = 0.5 * l,
355                    2 => local.y = -0.5 * w,
356                    3 => local.y = 0.5 * w,
357                    _ => local.z = h,
358                }
359                let (s, c) = yaw.sin_cos();
360                Point3::new(
361                    center_xy.0 + c * local.x - s * local.y,
362                    center_xy.1 + s * local.x + c * local.y,
363                    local.z,
364                )
365            })
366            .collect()
367    }
368
369    #[test]
370    fn fits_a_turned_box_and_ignores_outliers() {
371        let mut rng = SmallRng::seed_from_u64(3);
372        let mut points = box_points(&mut rng, (2.0, 5.0), (1.2, 0.5, 0.8), 0.4, 400);
373        // Background seen beside the object.
374        points.extend((0..15).map(|i| Point3::new(8.0 + i as f64 * 0.1, 12.0, 1.0)));
375        let fitted = fit_upright_box(&points, &BoxFitParams::default()).unwrap();
376        assert!((fitted.length - 1.2).abs() < 0.06, "{fitted:?}");
377        assert!((fitted.width - 0.5).abs() < 0.04, "{fitted:?}");
378        assert!((fitted.height - 0.8).abs() < 0.04, "{fitted:?}");
379        let yaw_error = (fitted.yaw - 0.4).rem_euclid(std::f64::consts::PI);
380        assert!(
381            yaw_error.min(std::f64::consts::PI - yaw_error) < 0.05,
382            "{fitted:?}"
383        );
384        assert!(
385            (fitted.center - Point3::new(2.0, 5.0, 0.4)).norm() < 0.05,
386            "{fitted:?}"
387        );
388    }
389
390    /// A camera walks 1.5 m past a chair-sized box 3 m away and observes 80
391    /// surface points with 0.5 px noise (focal length 460 px).
392    fn walk_past(rng: &mut SmallRng, translation_scale: f64) -> Vec<Vec<BearingObservation>> {
393        let size = (0.5, 0.45, 0.9);
394        let points = box_points(rng, (0.0, 3.0), size, 0.3, 80);
395        let target = Vector3::new(0.0, 3.0, 0.45);
396        let poses: Vec<_> = (0..30)
397            .map(|k| {
398                let position = Vector3::new(-0.75 + 1.5 * k as f64 / 29.0, 0.0, 1.4);
399                let mut pose = look_at(position, target);
400                // A wrongly scaled trajectory: every position scaled about the origin.
401                pose.translation.vector *= translation_scale;
402                pose
403            })
404            .collect();
405        let true_poses: Vec<_> = (0..30)
406            .map(|k| {
407                look_at(
408                    Vector3::new(-0.75 + 1.5 * k as f64 / 29.0, 0.0, 1.4),
409                    target,
410                )
411            })
412            .collect();
413        let pixel_angle = 0.5 / 460.0;
414        points
415            .iter()
416            .map(|p| {
417                true_poses
418                    .iter()
419                    .zip(&poses)
420                    .map(|(truth, used)| {
421                        let mut o = observe(truth, p);
422                        o.bearing = (o.bearing
423                            + Vector3::new(
424                                rng.gen_range(-1.0..1.0),
425                                rng.gen_range(-1.0..1.0),
426                                0.0,
427                            ) * pixel_angle)
428                            .normalize();
429                        o.camera_to_world = *used;
430                        o
431                    })
432                    .collect()
433            })
434            .collect()
435    }
436
437    #[test]
438    fn a_static_object_comes_out_in_metres_with_metric_poses() {
439        let mut rng = SmallRng::seed_from_u64(11);
440        let tracks = walk_past(&mut rng, 1.0);
441        let estimate = estimate_static_object(
442            7,
443            56,
444            &tracks,
445            &TriangulationParams::default(),
446            &BoxFitParams::default(),
447        )
448        .unwrap();
449        let b = estimate.upright_box;
450        assert_eq!(estimate.scale_source, ScaleSource::Triangulated);
451        assert!(estimate.points > 60, "{estimate:?}");
452        assert!((b.height - 0.9).abs() < 0.05, "{b:?}");
453        let (long, short) = (b.length.max(b.width), b.length.min(b.width));
454        assert!(
455            (long - 0.5).abs() < 0.05 && (short - 0.45).abs() < 0.05,
456            "{b:?}"
457        );
458        assert!(
459            (b.center - Point3::new(0.0, 3.0, 0.45)).norm() < 0.05,
460            "{b:?}"
461        );
462        let (low, high) = plausible_size(56).unwrap();
463        assert!((low..=high).contains(&b.height.max(long)));
464    }
465
466    #[test]
467    fn a_wrong_trajectory_scale_gives_wrong_sizes() {
468        // The same walk with positions doubled, as a monocular VO without
469        // the IMU might report: the box comes out about twice as large.
470        let mut rng = SmallRng::seed_from_u64(11);
471        let tracks = walk_past(&mut rng, 2.0);
472        let b = estimate_static_object(
473            7,
474            56,
475            &tracks,
476            &TriangulationParams::default(),
477            &BoxFitParams::default(),
478        )
479        .unwrap()
480        .upright_box;
481        assert!((b.height / 0.9 - 2.0).abs() < 0.15, "{b:?}");
482        let (low, high) = plausible_size(56).unwrap();
483        assert!(
484            !(low..=high).contains(&b.height.max(b.length).max(b.width)),
485            "flagged by the prior"
486        );
487    }
488}