Skip to main content

visloc_objects/
ground.rs

1//! Metric size, position and speed of objects standing on the ground (Phase 3
2//! of `docs/object_metric_slam_plan.md`, moving objects).
3//!
4//! An object that moves while the camera moves cannot be triangulated: its
5//! rays do not meet. Ground contact places it anyway:
6//! - **The ground** is found from the VIO's static scene points in the
7//!   gravity-aligned world (z up). [`PathGround`] follows the camera's path:
8//!   the camera moves over the ground, so a point's height is measured from
9//!   the camera where it passed nearest, which keeps roads that climb or fall
10//!   sharp. [`estimate_ground_height`] is the flat-ground version.
11//! - **Each frame** ([`place_on_ground`]): the ray through the middle of the
12//!   2D box's bottom edge meets the ground at the object's foot. That fixes
13//!   its distance, and the box's rays cut at that distance give its height
14//!   and width. "Bottom" is the edge lowest in the world, so a camera
15//!   mounted sideways works as well as an upright one.
16//! - **The ground under the object** ([`place_on_local_ground`]): stairs, a
17//!   ramp or a kerb can put an object on another level than the camera's
18//!   ground, which makes it look small and near (a lower level) or large and
19//!   far (a higher one). The ground moves to the layer of scene points under
20//!   the object's placed foot until it settles.
21//! - **Over a track** ([`summarize_ground_track`]): the median size, the path
22//!   of the foot, and the velocity of a line fitted to it, weighted by how
23//!   far each foot can be off; a velocity within that noise is still.
24//!
25//! The scale comes from the camera's metric height above the ground, so it
26//! is as good as the VIO's. The object must touch the ground where the box
27//! ends: anything carried, stacked or seen over an edge breaks it.
28
29use nalgebra::{Matrix2, Matrix2x4, Matrix4, Point3, UnitQuaternion, Vector2, Vector3, Vector4};
30
31use crate::BBox;
32
33/// Settings of [`estimate_ground_height`], [`PathGround`] and
34/// [`place_on_local_ground`].
35#[derive(Debug, Clone, Copy, PartialEq)]
36pub struct GroundParams {
37    /// Height bin of the histogram (0.05 m).
38    pub bin: f64,
39    /// Only points this far below the lowest camera position count (0.3 m).
40    pub min_below_camera: f64,
41    /// Points the densest bin needs (20).
42    pub min_points: usize,
43    /// The ground under an object: the points horizontally nearest to its
44    /// foot (12)...
45    pub local_neighbours: usize,
46    /// ...within this distance (1.5 m)...
47    pub local_radius: f64,
48    /// ...of which its densest bin needs this many (3)...
49    pub local_min_points: usize,
50    /// ...and is taken if it is this much higher or lower (0.1 m).
51    pub local_min_shift: f64,
52    /// [`PathGround`]: the stretch of path, either way, whose points give the
53    /// camera's height above the ground (20 m).
54    pub path_stretch: f64,
55}
56
57impl Default for GroundParams {
58    fn default() -> Self {
59        Self {
60            bin: 0.05,
61            min_below_camera: 0.3,
62            min_points: 20,
63            local_neighbours: 12,
64            local_radius: 1.5,
65            local_min_points: 3,
66            local_min_shift: 0.1,
67            path_stretch: 20.0,
68        }
69    }
70}
71
72/// The ground's height (world z): the mean height of the points in the
73/// densest `bin`-high layer below `lowest_camera_z - min_below_camera`.
74pub fn estimate_ground_height(
75    points: &[Point3<f64>],
76    lowest_camera_z: f64,
77    params: &GroundParams,
78) -> Option<f64> {
79    densest_layer(
80        points.iter().map(|p| p.z),
81        lowest_camera_z - params.min_below_camera,
82        params.bin,
83        params.min_points,
84    )
85}
86
87/// The mean of the densest `bin`-high layer of the heights below `ceiling`,
88/// if it has `min_points`; ties go to the lower layer.
89fn densest_layer(
90    heights: impl Iterator<Item = f64>,
91    ceiling: f64,
92    bin: f64,
93    min_points: usize,
94) -> Option<f64> {
95    densest_band(heights, ceiling, bin, 0, min_points)
96}
97
98/// [`densest_layer`] over bands of `2 * spread + 1` neighbouring bins, for
99/// noisier heights.
100fn densest_band(
101    heights: impl Iterator<Item = f64>,
102    ceiling: f64,
103    bin: f64,
104    spread: i64,
105    min_points: usize,
106) -> Option<f64> {
107    let mut bins: std::collections::HashMap<i64, Vec<f64>> = std::collections::HashMap::new();
108    for z in heights.filter(|z| z.is_finite() && *z < ceiling) {
109        bins.entry((z / bin).floor() as i64).or_default().push(z);
110    }
111    let band = |k: i64| {
112        (k - spread..=k + spread)
113            .filter_map(|j| bins.get(&j))
114            .flatten()
115    };
116    let (best, count) = bins
117        .keys()
118        .map(|&k| (k, band(k).count()))
119        .filter(|(_, n)| *n >= min_points)
120        .max_by_key(|(k, n)| (*n, std::cmp::Reverse(*k)))?;
121    Some(band(best).sum::<f64>() / count as f64)
122}
123
124/// The ground along the camera's path. The camera moves over the ground, so
125/// a scene point's height is measured from the camera where it passed
126/// nearest: on a road that climbs or falls, the ground then lies at one
127/// depth below the path, the camera's height above it. That height is found
128/// for each stretch of the path (`path_stretch` metres either way), so a
129/// camera whose height changes (a hand lowering it) is followed too. The
130/// ground under any spot is the camera's height below the nearest point of
131/// the path.
132#[derive(Debug, Clone, PartialEq)]
133pub struct PathGround {
134    /// Camera centres along the path, in order.
135    pub path: Vec<Point3<f64>>,
136    /// The camera's height above the ground at each of them.
137    pub camera_heights: Vec<f64>,
138}
139
140impl PathGround {
141    /// For each point of the path, the densest band of three `bin`-high
142    /// layers of the heights of the scene `points` whose nearest path point
143    /// lies within `path_stretch` along the path, each measured from that
144    /// nearest point, at least `min_below_camera` down, with `min_points`. A stretch without
145    /// such a layer takes the nearest stretch's. `None` if none has one.
146    pub fn estimate(
147        path: &[Point3<f64>],
148        points: &[Point3<f64>],
149        params: &GroundParams,
150    ) -> Option<Self> {
151        path.first()?;
152        let mut along = vec![0.0];
153        for pair in path.windows(2) {
154            let step =
155                (Vector2::new(pair[1].x, pair[1].y) - Vector2::new(pair[0].x, pair[0].y)).norm();
156            along.push(along.last()? + step);
157        }
158        let ground = Self {
159            path: path.to_vec(),
160            camera_heights: Vec::new(),
161        };
162        let below: Vec<(usize, f64)> = points
163            .iter()
164            .map(|p| {
165                let i = ground.nearest(&Vector2::new(p.x, p.y));
166                (i, p.z - path[i].z)
167            })
168            .collect();
169        let found: Vec<Option<f64>> = along
170            .iter()
171            .map(|s| {
172                let heights = below
173                    .iter()
174                    .filter(|(i, _)| (along[*i] - s).abs() <= params.path_stretch)
175                    .map(|(_, z)| *z);
176                densest_band(
177                    heights,
178                    -params.min_below_camera,
179                    params.bin,
180                    1,
181                    params.min_points,
182                )
183                .map(|layer| -layer)
184            })
185            .collect();
186        let camera_heights = (0..found.len())
187            .map(|i| {
188                (0..found.len())
189                    .filter_map(|j| found[j].map(|h| ((along[i] - along[j]).abs(), h)))
190                    .min_by(|a, b| a.0.total_cmp(&b.0))
191                    .map(|(_, h)| h)
192            })
193            .collect::<Option<Vec<f64>>>()?;
194        Some(Self {
195            camera_heights,
196            ..ground
197        })
198    }
199
200    /// The ground's height under `xy`.
201    pub fn height_at(&self, xy: &Vector2<f64>) -> f64 {
202        let i = self.nearest(xy);
203        self.path[i].z - self.camera_heights[i]
204    }
205
206    /// The camera's height above the ground where it passed nearest to `xy`.
207    pub fn camera_height_at(&self, xy: &Vector2<f64>) -> f64 {
208        self.camera_heights[self.nearest(xy)]
209    }
210
211    fn nearest(&self, xy: &Vector2<f64>) -> usize {
212        let d = |i: &usize| (Vector2::new(self.path[*i].x, self.path[*i].y) - xy).norm_squared();
213        (0..self.path.len())
214            .min_by(|a, b| d(a).total_cmp(&d(b)))
215            .expect("a path")
216    }
217}
218
219/// An object placed on the ground in one frame.
220#[derive(Debug, Clone, Copy, PartialEq)]
221pub struct GroundObservation {
222    pub timestamp_ns: i64,
223    /// Where the object touches the ground.
224    pub contact: Point3<f64>,
225    /// The camera it was seen from.
226    pub camera: Point3<f64>,
227    pub height: f64,
228    pub width: f64,
229    /// Horizontal distance from the camera.
230    pub distance: f64,
231}
232
233/// World-frame rays through a 2D box: the middles of its four edges and its
234/// four corners.
235#[derive(Debug, Clone, Copy, PartialEq)]
236pub struct BoxRays {
237    pub edge_midpoints: [Vector3<f64>; 4],
238    pub corners: [Vector3<f64>; 4],
239}
240
241impl BoxRays {
242    /// The rays of `bbox`, unprojected by `unproject` (pixel to camera-frame
243    /// ray) and turned into the world by `camera_to_world`. `None` if a point
244    /// does not unproject.
245    pub fn from_box(
246        bbox: &BBox,
247        camera_to_world: &UnitQuaternion<f64>,
248        unproject: impl Fn(f64, f64) -> Option<Vector3<f64>>,
249    ) -> Option<Self> {
250        let (xm, ym) = bbox.center();
251        let ray = |x: f64, y: f64| unproject(x, y).map(|r| camera_to_world * r);
252        Some(Self {
253            edge_midpoints: [
254                ray(xm, bbox.y_min)?,
255                ray(bbox.x_max, ym)?,
256                ray(xm, bbox.y_max)?,
257                ray(bbox.x_min, ym)?,
258            ],
259            corners: [
260                ray(bbox.x_min, bbox.y_min)?,
261                ray(bbox.x_max, bbox.y_min)?,
262                ray(bbox.x_max, bbox.y_max)?,
263                ray(bbox.x_min, bbox.y_max)?,
264            ],
265        })
266    }
267}
268
269/// Place an upright object standing on the ground `z = ground_z`, seen from
270/// `camera_center` through the rays of its 2D box. `None` if the camera is
271/// not above the ground or the box's bottom edge does not point down.
272pub fn place_on_ground(
273    camera_center: &Point3<f64>,
274    rays: &BoxRays,
275    ground_z: f64,
276    timestamp_ns: i64,
277) -> Option<GroundObservation> {
278    let height_above = camera_center.z - ground_z;
279    if height_above <= 0.0 {
280        return None;
281    }
282    let unit = |r: &Vector3<f64>| r.try_normalize(1e-12);
283    let foot = rays
284        .edge_midpoints
285        .iter()
286        .filter_map(unit)
287        .min_by(|a, b| a.z.total_cmp(&b.z))?;
288    if foot.z >= -1e-6 {
289        return None;
290    }
291    let contact = camera_center + foot * (height_above / -foot.z);
292    // The object's "billboard": the vertical plane through the contact
293    // point, facing the camera.
294    let normal = Vector3::new(
295        contact.x - camera_center.x,
296        contact.y - camera_center.y,
297        0.0,
298    );
299    let distance = normal.norm();
300    let normal = normal.try_normalize(1e-9)?;
301    let across = Vector3::new(-normal.y, normal.x, 0.0);
302    let depth = normal.dot(&(contact - camera_center));
303    let hits: Vec<Point3<f64>> = rays
304        .corners
305        .iter()
306        .chain(&rays.edge_midpoints)
307        .filter_map(unit)
308        .filter(|r| normal.dot(r) > 1e-6)
309        .map(|r| camera_center + r * (depth / normal.dot(&r)))
310        .collect();
311    let top = hits.iter().map(|p| p.z).fold(f64::NEG_INFINITY, f64::max);
312    let sideways: Vec<f64> = hits.iter().map(|p| across.dot(&p.coords)).collect();
313    let width = sideways.iter().copied().fold(f64::NEG_INFINITY, f64::max)
314        - sideways.iter().copied().fold(f64::INFINITY, f64::min);
315    Some(GroundObservation {
316        timestamp_ns,
317        contact,
318        camera: *camera_center,
319        height: top - ground_z,
320        width,
321        distance,
322    })
323}
324
325/// Rough height ranges of COCO classes that stand on the ground, in metres.
326/// The height is what ground contact measures best (the width depends on
327/// the side the object is seen from). Only for flagging implausible
328/// estimates, never to set a scale.
329pub fn plausible_height(class_id: u32) -> Option<(f64, f64)> {
330    Some(match class_id {
331        0 => (1.0, 2.1),  // person, children included
332        1 => (0.8, 1.4),  // bicycle
333        2 => (1.2, 2.1),  // car, vans included
334        3 => (0.9, 1.6),  // motorcycle
335        5 => (2.7, 4.5),  // bus
336        6 => (2.8, 4.8),  // train or tram
337        7 => (2.0, 4.2),  // truck
338        16 => (0.2, 1.0), // dog
339        17 => (1.2, 2.0), // horse
340        _ => return None,
341    })
342}
343
344/// One view of an object: where the camera was and the rays of its box.
345#[derive(Debug, Clone, Copy, PartialEq)]
346pub struct GroundView {
347    pub timestamp_ns: i64,
348    pub camera_center: Point3<f64>,
349    pub rays: BoxRays,
350}
351
352/// Place an object's views on the ground under it. Starting from `ground_z`,
353/// the views are placed ([`place_on_ground`]), and the ground moves to the
354/// densest layer of the `local_neighbours` scene `points` horizontally
355/// nearest to the median foot (within `local_radius`, below the lowest
356/// camera), while that layer lies more than `local_min_shift` away (a few
357/// rounds at most). Nearest points rather than all within a radius, so that
358/// over steps the ground walks down (or up) one step at a time. Returns the ground used and
359/// the placed views; `None` if no view could be placed.
360pub fn place_on_local_ground(
361    views: &[GroundView],
362    points: &[Point3<f64>],
363    ground_z: f64,
364    params: &GroundParams,
365) -> Option<(f64, Vec<GroundObservation>)> {
366    const ROUNDS: usize = 5;
367    let ceiling = views
368        .iter()
369        .map(|v| v.camera_center.z)
370        .fold(f64::INFINITY, f64::min)
371        - params.min_below_camera;
372    let mut ground = ground_z;
373    for round in 0.. {
374        let placed: Vec<GroundObservation> = views
375            .iter()
376            .filter_map(|v| place_on_ground(&v.camera_center, &v.rays, ground, v.timestamp_ns))
377            .collect();
378        if placed.is_empty() {
379            return None;
380        }
381        let median = |f: fn(&Point3<f64>) -> f64| {
382            let mut v: Vec<f64> = placed.iter().map(|o| f(&o.contact)).collect();
383            v.sort_by(f64::total_cmp);
384            v[v.len() / 2]
385        };
386        let foot = Vector2::new(median(|p| p.x), median(|p| p.y));
387        let mut near: Vec<(f64, f64)> = points
388            .iter()
389            .filter(|p| p.z < ceiling)
390            .map(|p| ((Vector2::new(p.x, p.y) - foot).norm(), p.z))
391            .filter(|(d, _)| *d < params.local_radius)
392            .collect();
393        near.sort_by(|a, b| a.0.total_cmp(&b.0));
394        near.truncate(params.local_neighbours);
395        let local = densest_layer(
396            near.iter().map(|(_, z)| *z),
397            ceiling,
398            params.bin,
399            params.local_min_points,
400        );
401        match local {
402            Some(z) if (z - ground).abs() > params.local_min_shift && round + 1 < ROUNDS => {
403                ground = z
404            }
405            _ => return Some((ground, placed)),
406        }
407    }
408    unreachable!()
409}
410
411/// Settings of [`summarize_ground_track`].
412#[derive(Debug, Clone, Copy, PartialEq)]
413pub struct GroundTrackParams {
414    /// A track needs three frames over this long (1 s).
415    pub min_seconds: f64,
416    /// How far a box's bottom edge is off, as an angle (0.004 rad, about
417    /// 3 px at a focal length of 720 px): along the ray, the foot is off by
418    /// this times `(h² + d²) / h` for a camera `h` above the ground and `d`
419    /// from the foot, across it by this times `d`.
420    pub angular_noise: f64,
421    /// And by this share of the object's width more either way, for not
422    /// knowing which point of the object the box's bottom edge falls on
423    /// (0.5)...
424    pub extent_noise: f64,
425    /// ...but at least this much (0.2 m).
426    pub min_extent_noise: f64,
427    /// A fitted velocity this unlikely under the noise (chi-square, two
428    /// degrees of freedom) or more counts as moving (9.21: 1 %).
429    pub still_chi2: f64,
430    /// A foot this far off the fitted line (the same chi-square) is dropped
431    /// (9.21).
432    pub outlier_chi2: f64,
433}
434
435impl Default for GroundTrackParams {
436    fn default() -> Self {
437        Self {
438            min_seconds: 1.0,
439            angular_noise: 0.004,
440            extent_noise: 0.5,
441            min_extent_noise: 0.2,
442            still_chi2: 9.21,
443            outlier_chi2: 9.21,
444        }
445    }
446}
447
448/// An object's track on the ground.
449#[derive(Debug, Clone, PartialEq)]
450pub struct GroundTrack {
451    pub object_id: u64,
452    pub class_id: u32,
453    /// Median over the frames.
454    pub height: f64,
455    pub width: f64,
456    pub distance: f64,
457    /// The contact point per frame.
458    pub path: Vec<(i64, Point3<f64>)>,
459    /// Horizontal velocity of a straight line fitted to the path (m/s).
460    pub velocity: Vector2<f64>,
461    /// Its standard deviation along its direction (m/s).
462    pub speed_sigma: f64,
463    /// Whether the velocity stands out of the noise.
464    pub moving: bool,
465    /// The speed: `velocity`'s, or 0 if not `moving` (m/s).
466    pub speed: f64,
467}
468
469/// Median size, and the velocity of the path, from at least three frames
470/// spanning `min_seconds`.
471///
472/// The velocity is a straight line fitted by weighted least squares. Each
473/// foot is weighted by how far it can be off: little across the ray, a lot
474/// along it far away, where a pixel moves the foot by metres
475/// ([`GroundTrackParams`]). A camera driving towards a still car that is
476/// placed a few percent near at range would otherwise see it approach. Feet
477/// far off the line (a 2D track that jumped to a neighbour) are dropped. If
478/// the velocity does not stand out of the noise, the object is still.
479pub fn summarize_ground_track(
480    object_id: u64,
481    class_id: u32,
482    observations: &[GroundObservation],
483    params: &GroundTrackParams,
484) -> Option<GroundTrack> {
485    if observations.len() < 3 {
486        return None;
487    }
488    let t0 = observations.iter().map(|o| o.timestamp_ns).min()?;
489    let times: Vec<f64> = observations
490        .iter()
491        .map(|o| (o.timestamp_ns - t0) as f64 * 1e-9)
492        .collect();
493    if times.iter().copied().fold(0.0, f64::max) < params.min_seconds {
494        return None;
495    }
496    let mut widths: Vec<f64> = observations.iter().map(|o| o.width).collect();
497    widths.sort_by(f64::total_cmp);
498    let extent = (params.extent_noise * widths[widths.len() / 2]).max(params.min_extent_noise);
499    // Each foot's position and 2x2 information.
500    let feet: Vec<(Vector2<f64>, Matrix2<f64>)> = observations
501        .iter()
502        .map(|o| {
503            let foot = Vector2::new(o.contact.x, o.contact.y);
504            let ray = foot - Vector2::new(o.camera.x, o.camera.y);
505            let d = ray.norm();
506            let along = ray.try_normalize(1e-9).unwrap_or_else(Vector2::x);
507            let across = Vector2::new(-along.y, along.x);
508            let h = (o.camera.z - o.contact.z).max(0.3);
509            let sigma_along = params.angular_noise * (h * h + d * d) / h + extent;
510            let sigma_across = params.angular_noise * d + extent;
511            let information = along * along.transpose() / (sigma_along * sigma_along)
512                + across * across.transpose() / (sigma_across * sigma_across);
513            (foot, information)
514        })
515        .collect();
516    // p_i = p0 + v (t_i - mean_t) by weighted least squares; feet beyond
517    // `outlier_chi2` of the line (a 2D track that jumped to a neighbour) are
518    // dropped and the line fitted again, a few times.
519    let mut keep = vec![true; feet.len()];
520    let mut fit = None;
521    for _ in 0..4 {
522        let kept: Vec<usize> = (0..feet.len()).filter(|&i| keep[i]).collect();
523        let mean_t = kept.iter().map(|&i| times[i]).sum::<f64>() / kept.len() as f64;
524        let mut normal = Matrix4::<f64>::zeros();
525        let mut rhs = Vector4::<f64>::zeros();
526        for &i in &kept {
527            let (foot, information) = &feet[i];
528            let mut jacobian = Matrix2x4::<f64>::zeros();
529            jacobian
530                .fixed_view_mut::<2, 2>(0, 0)
531                .copy_from(&Matrix2::identity());
532            jacobian
533                .fixed_view_mut::<2, 2>(0, 2)
534                .copy_from(&(Matrix2::identity() * (times[i] - mean_t)));
535            normal += jacobian.transpose() * information * jacobian;
536            rhs += jacobian.transpose() * information * foot;
537        }
538        let covariance = normal.try_inverse()?;
539        let solution = covariance * rhs;
540        let inliers: Vec<bool> = (0..feet.len())
541            .map(|i| {
542                let (foot, information) = &feet[i];
543                let r = foot
544                    - Vector2::new(solution[0], solution[1])
545                    - Vector2::new(solution[2], solution[3]) * (times[i] - mean_t);
546                r.dot(&(information * r)) < params.outlier_chi2
547            })
548            .collect();
549        fit = Some((covariance, solution));
550        if inliers == keep || inliers.iter().filter(|&&k| k).count() < 3 {
551            break;
552        }
553        keep = inliers;
554    }
555    let (covariance, solution) = fit?;
556    let velocity = Vector2::new(solution[2], solution[3]);
557    let velocity_covariance: Matrix2<f64> = covariance.fixed_view::<2, 2>(2, 2).into();
558    let chi2 = velocity.dot(&(velocity_covariance.try_inverse()? * velocity));
559    let direction = velocity.try_normalize(1e-12).unwrap_or_else(Vector2::x);
560    let speed_sigma = direction
561        .dot(&(velocity_covariance * direction))
562        .max(0.0)
563        .sqrt();
564    let moving = chi2 > params.still_chi2;
565    let median = |f: fn(&GroundObservation) -> f64| {
566        let mut v: Vec<f64> = observations.iter().map(f).collect();
567        v.sort_by(f64::total_cmp);
568        v[v.len() / 2]
569    };
570    Some(GroundTrack {
571        object_id,
572        class_id,
573        height: median(|o| o.height),
574        width: median(|o| o.width),
575        distance: median(|o| o.distance),
576        path: observations
577            .iter()
578            .map(|o| (o.timestamp_ns, o.contact))
579            .collect(),
580        velocity,
581        speed_sigma,
582        moving,
583        speed: if moving { velocity.norm() } else { 0.0 },
584    })
585}
586
587#[cfg(test)]
588mod tests {
589    use super::*;
590    use nalgebra::{Isometry3, Matrix3, Point2, Rotation3, Translation3, UnitQuaternion};
591
592    const F: f64 = 400.0;
593    const C: (f64, f64) = (320.0, 240.0);
594
595    /// Camera-to-world looking along `forward` (horizontal), z up, rolled
596    /// by `roll` about its optical axis (a sideways-mounted camera is 90°).
597    fn camera(position: Vector3<f64>, forward: Vector3<f64>, roll: f64) -> Isometry3<f64> {
598        let z = forward.normalize();
599        let x = z.cross(&Vector3::z()).normalize();
600        let y = z.cross(&x);
601        let base = Rotation3::from_matrix_unchecked(Matrix3::from_columns(&[x, y, z]));
602        let rolled = base * Rotation3::from_axis_angle(&Vector3::z_axis(), roll);
603        Isometry3::from_parts(
604            Translation3::from(position),
605            UnitQuaternion::from_rotation_matrix(&rolled),
606        )
607    }
608
609    fn project(pose: &Isometry3<f64>, p: &Point3<f64>) -> Point2<f64> {
610        let c = pose.inverse() * p;
611        Point2::new(F * c.x / c.z + C.0, F * c.y / c.z + C.1)
612    }
613
614    /// The rays of the 2D box of an upright `width × depth × height` cuboid
615    /// standing at `foot`.
616    fn outline(pose: &Isometry3<f64>, foot: Point3<f64>, size: (f64, f64, f64)) -> BoxRays {
617        padded_outline(pose, foot, size, 0.0)
618    }
619
620    /// [`outline`] with the box's bottom edge `pad` pixels low, as a loose
621    /// detector box has it (upright camera).
622    fn padded_outline(
623        pose: &Isometry3<f64>,
624        foot: Point3<f64>,
625        size: (f64, f64, f64),
626        pad: f64,
627    ) -> BoxRays {
628        let (w, d, h) = size;
629        let corners: Vec<Point2<f64>> = [-0.5, 0.5]
630            .iter()
631            .flat_map(|&a| {
632                [-0.5, 0.5]
633                    .iter()
634                    .flat_map(move |&b| [0.0, 1.0].iter().map(move |&c| (a, b, c)))
635            })
636            .map(|(a, b, c)| project(pose, &(foot + Vector3::new(a * w, b * d, c * h))))
637            .collect();
638        let (x0, x1) = corners.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| {
639            (lo.min(p.x), hi.max(p.x))
640        });
641        let (y0, y1) = corners.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| {
642            (lo.min(p.y), hi.max(p.y))
643        });
644        BoxRays::from_box(&BBox::new(x0, y0, x1, y1 + pad), &pose.rotation, |x, y| {
645            Some(Vector3::new((x - C.0) / F, (y - C.1) / F, 1.0))
646        })
647        .unwrap()
648    }
649
650    const SPEED: f64 = 1.442_220_510_185_596; // |(1.2, 0.8)|
651
652    /// A person 1.75 m tall (0.5 m wide, 0.3 m deep) walks diagonally at
653    /// (1.2, 0.8) m/s, about 5 m from a camera 1.5 m above the ground that
654    /// itself walks forward. Returns the summarized track, with every camera
655    /// position and the ground scaled by `scale` (a wrongly scaled
656    /// trajectory).
657    fn walk(roll: f64, scale: f64) -> GroundTrack {
658        let observations: Vec<GroundObservation> = (0..30)
659            .map(|k| {
660                let t = k as f64 / 10.0;
661                let camera_position = Vector3::new(0.0, 0.8 * t, 1.5);
662                let true_pose = camera(camera_position, Vector3::new(0.3, 1.0, 0.0), roll);
663                let foot = Point3::new(-1.8 + 1.2 * t, 5.0 + 0.8 * t, 0.0);
664                let rays = outline(&true_pose, foot, (0.5, 0.3, 1.75));
665                place_on_ground(
666                    &Point3::from(camera_position * scale),
667                    &rays,
668                    0.0,
669                    (t * 1e9) as i64,
670                )
671                .unwrap()
672            })
673            .collect();
674        summarize_ground_track(1, 0, &observations, &GroundTrackParams::default()).unwrap()
675    }
676
677    #[test]
678    fn a_walking_person_comes_out_in_metres_and_metres_per_second() {
679        for roll in [0.0, std::f64::consts::FRAC_PI_2] {
680            let track = walk(roll, 1.0);
681            // The 2D box of a cuboid is a little larger than its silhouette.
682            assert!((track.height - 1.75).abs() < 0.1, "roll {roll}: {track:?}");
683            assert!((track.width - 0.5).abs() < 0.15, "roll {roll}: {track:?}");
684            assert!((track.speed - SPEED).abs() < 0.05, "roll {roll}: {track:?}");
685            // The foot is the near edge of the footprint, not its centre.
686            let (start, end) = (track.path[0].1, track.path[29].1);
687            assert!(
688                (start - Point3::new(-1.8, 5.0, 0.0)).norm() < 0.35,
689                "{start}"
690            );
691            assert!(
692                (end - Point3::new(-1.8 + 3.48, 7.32, 0.0)).norm() < 0.35,
693                "{end}"
694            );
695        }
696    }
697
698    /// A car 4.5 x 1.8 x 1.5 m, its box 1.5 px low (the angular noise at this
699    /// focal length), seen for 3 s from a camera
700    /// 1.6 m up driving at 10 m/s, from 40 m to 10 m, 3 m to the side; the
701    /// car drives at `velocity` (m/s, along x, across the camera's path).
702    fn drive_past(velocity: f64) -> GroundTrack {
703        let observations: Vec<GroundObservation> = (0..30)
704            .map(|k| {
705                let t = k as f64 / 10.0;
706                let position = Vector3::new(0.0, 10.0 * t, 1.6);
707                let pose = camera(position, Vector3::new(0.0, 1.0, 0.0), 0.0);
708                let foot = Point3::new(3.0 + velocity * t, 40.0, 0.0);
709                let rays = padded_outline(&pose, foot, (1.8, 4.5, 1.5), 1.5);
710                place_on_ground(&Point3::from(position), &rays, 0.0, (t * 1e9) as i64).unwrap()
711            })
712            .collect();
713        summarize_ground_track(1, 2, &observations, &GroundTrackParams::default()).unwrap()
714    }
715
716    #[test]
717    fn a_parked_car_driven_past_stands_still() {
718        let track = drive_past(0.0);
719        // The loose box puts it near at range: a plain line fit would see it
720        // approach.
721        assert!(track.velocity.norm() > 0.5, "{track:?}");
722        assert!(!track.moving, "{track:?}");
723        assert_eq!(track.speed, 0.0);
724    }
725
726    #[test]
727    fn a_car_crossing_ahead_moves() {
728        let track = drive_past(5.0);
729        assert!(track.moving, "{track:?}");
730        assert!((track.speed - 5.0).abs() < 1.0, "{track:?}");
731        assert!(track.speed_sigma < 1.0, "{track:?}");
732    }
733
734    #[test]
735    fn a_track_that_jumps_to_a_neighbour_stays_still() {
736        // A person stands 8 m ahead for 3 s; for 6 frames the 2D track takes
737        // the person next to them, 2 m to the side.
738        let position = Vector3::new(0.0, 0.0, 1.5);
739        let pose = camera(position, Vector3::new(0.0, 1.0, 0.0), 0.0);
740        let observations: Vec<GroundObservation> = (0..30)
741            .map(|k| {
742                let x = if (12..18).contains(&k) { 2.5 } else { 0.5 };
743                let rays = outline(&pose, Point3::new(x, 8.0, 0.0), (0.5, 0.3, 1.75));
744                place_on_ground(&Point3::from(position), &rays, 0.0, k * 100_000_000).unwrap()
745            })
746            .collect();
747        let track =
748            summarize_ground_track(1, 0, &observations, &GroundTrackParams::default()).unwrap();
749        assert!(!track.moving, "{track:?}");
750        let plain = GroundTrackParams {
751            outlier_chi2: f64::INFINITY,
752            ..GroundTrackParams::default()
753        };
754        let jumped = summarize_ground_track(1, 0, &observations, &plain).unwrap();
755        assert!(jumped.velocity.norm() > track.velocity.norm(), "{jumped:?}");
756    }
757
758    #[test]
759    fn a_wrong_scale_makes_the_person_a_giant() {
760        let track = walk(0.0, 2.0);
761        assert!((track.height / 1.75 - 2.0).abs() < 0.1, "{track:?}");
762        assert!((track.speed / SPEED - 2.0).abs() < 0.1, "{track:?}");
763        let (low, high) = plausible_height(0).unwrap();
764        assert!((low..=high).contains(&1.75) && !(low..=high).contains(&track.height));
765    }
766
767    #[test]
768    fn rejects_a_camera_below_ground_and_rays_that_do_not_go_down() {
769        let rays = |z: f64| BoxRays {
770            edge_midpoints: [Vector3::new(0.0, 1.0, z); 4],
771            corners: [Vector3::new(0.1, 1.0, z); 4],
772        };
773        assert!(place_on_ground(&Point3::new(0.0, 0.0, 1.5), &rays(0.1), 0.0, 0).is_none());
774        assert!(place_on_ground(&Point3::new(0.0, 0.0, -0.5), &rays(-0.3), 0.0, 0).is_none());
775        assert!(place_on_ground(&Point3::new(0.0, 0.0, 1.5), &rays(-0.3), 0.0, 0).is_some());
776    }
777
778    /// Views of a person 1.75 m tall walking across on a level `level` m
779    /// below the camera's ground (above it if negative), 6 m ahead of a
780    /// camera 1.5 m above that ground; and scene points: the camera's ground
781    /// up to 3 m ahead, a flight of steps to the other level and the other
782    /// level beyond, up to 8.5 m ahead.
783    fn below_the_steps(level: f64) -> (Vec<GroundView>, Vec<Point3<f64>>) {
784        let views = (0..20)
785            .map(|k| {
786                let t = k as f64 / 10.0;
787                let position = Vector3::new(0.0, 0.0, 1.5);
788                let pose = camera(position, Vector3::new(0.0, 1.0, -0.2), 0.0);
789                let foot = Point3::new(-1.0 + t, 6.0, -level);
790                GroundView {
791                    timestamp_ns: (t * 1e9) as i64,
792                    camera_center: Point3::from(position),
793                    rays: outline(&pose, foot, (0.5, 0.3, 1.75)),
794                }
795            })
796            .collect();
797        let mut points = Vec::new();
798        for i in 0..40 {
799            for j in 0..30 {
800                let (x, y) = (-2.0 + i as f64 * 0.1, j as f64 * 0.1);
801                points.push(Point3::new(x, y, 0.0));
802            }
803            for step in 0..5 {
804                let y = 3.0 + step as f64 * 0.2;
805                points.push(Point3::new(
806                    -2.0 + i as f64 * 0.1,
807                    y,
808                    -level * (step as f64 + 1.0) / 5.0,
809                ));
810            }
811            for j in 0..30 {
812                let (x, y) = (-2.0 + i as f64 * 0.1, 4.0 + j as f64 * 0.15);
813                points.push(Point3::new(x, y, -level));
814            }
815        }
816        (views, points)
817    }
818
819    #[test]
820    fn a_person_below_the_steps_stands_on_the_lower_level() {
821        let (views, points) = below_the_steps(1.0);
822        let params = GroundParams::default();
823        // On the camera's ground, the person comes out small and near.
824        let flat: Vec<GroundObservation> = views
825            .iter()
826            .filter_map(|v| place_on_ground(&v.camera_center, &v.rays, 0.0, v.timestamp_ns))
827            .collect();
828        let flat = summarize_ground_track(1, 0, &flat, &GroundTrackParams::default()).unwrap();
829        assert!(flat.height < 1.2, "{flat:?}");
830        // On the ground under it, it stands 1 m lower and comes out right.
831        let (ground, placed) = place_on_local_ground(&views, &points, 0.0, &params).unwrap();
832        assert!((ground + 1.0).abs() < 0.05, "{ground}");
833        let track = summarize_ground_track(1, 0, &placed, &GroundTrackParams::default()).unwrap();
834        assert!((track.height - 1.75).abs() < 0.1, "{track:?}");
835        assert!((track.distance - 6.0).abs() < 0.3, "{track:?}");
836    }
837
838    #[test]
839    fn a_person_up_the_steps_stands_on_the_upper_level() {
840        let (views, points) = below_the_steps(-0.5);
841        let (ground, placed) =
842            place_on_local_ground(&views, &points, 0.0, &GroundParams::default()).unwrap();
843        assert!((ground - 0.5).abs() < 0.05, "{ground}");
844        let track = summarize_ground_track(1, 0, &placed, &GroundTrackParams::default()).unwrap();
845        assert!((track.height - 1.75).abs() < 0.1, "{track:?}");
846        assert!((track.distance - 6.0).abs() < 0.3, "{track:?}");
847    }
848
849    #[test]
850    fn a_person_on_the_camera_ground_stays_there() {
851        let (views, points) = below_the_steps(0.0);
852        let (ground, placed) =
853            place_on_local_ground(&views, &points, 0.0, &GroundParams::default()).unwrap();
854        assert_eq!(ground, 0.0);
855        let track = summarize_ground_track(1, 0, &placed, &GroundTrackParams::default()).unwrap();
856        assert!((track.height - 1.75).abs() < 0.1, "{track:?}");
857    }
858
859    #[test]
860    fn the_path_ground_follows_a_falling_road() {
861        // A camera 1.6 m above a road that falls 5 % along x; the road's
862        // points 0-30 m ahead and 2 m to the sides, and car bodies 0.8 m up.
863        let road = |x: f64| -0.05 * x;
864        let path: Vec<Point3<f64>> = (0..100)
865            .map(|i| Point3::new(i as f64, 0.0, road(i as f64) + 1.6))
866            .collect();
867        let mut points = Vec::new();
868        for i in 0..400 {
869            let x = i as f64 * 0.25;
870            points.push(Point3::new(x, -2.0 + (i % 5) as f64, road(x)));
871            if i % 3 == 0 {
872                points.push(Point3::new(
873                    x,
874                    3.0,
875                    road(x) + 0.8 + 0.1 * ((i / 3) % 4) as f64,
876                ));
877            }
878        }
879        let ground = PathGround::estimate(&path, &points, &GroundParams::default()).unwrap();
880        let height = ground.camera_height_at(&Vector2::new(50.0, 0.0));
881        assert!((height - 1.6).abs() < 0.05, "{height}");
882        assert!((ground.height_at(&Vector2::new(60.0, 2.5)) - road(60.0)).abs() < 0.1);
883        // A flat ground smears the 5 m drop over many layers.
884        let flat = estimate_ground_height(&points, path[0].z, &GroundParams::default());
885        assert!(
886            flat.is_none_or(|z| (z - road(60.0)).abs() > 0.5),
887            "{flat:?}"
888        );
889    }
890
891    #[test]
892    fn finds_the_floor_under_clutter() {
893        let mut points = Vec::new();
894        for i in 0..200 {
895            let a = i as f64 * 0.37;
896            points.push(Point3::new(
897                a.sin() * 4.0,
898                a.cos() * 4.0,
899                -1.52 + 0.01 * (a * 7.0).sin(),
900            ));
901        }
902        // A table top and some walls: fewer points per layer.
903        points.extend((0..60).map(|i| Point3::new(i as f64 * 0.05, 2.0, -0.78)));
904        points.extend((0..300).map(|i| Point3::new(3.0, i as f64 * 0.01, -1.4 + i as f64 * 0.01)));
905        let ground = estimate_ground_height(&points, 0.0, &GroundParams::default()).unwrap();
906        assert!((ground + 1.52).abs() < 0.02, "{ground}");
907    }
908}