1use nalgebra::{Isometry3, Matrix3, Point3, Vector2, Vector3};
21
22#[derive(Debug, Clone, Copy, PartialEq)]
25pub struct BearingObservation {
26 pub camera_to_world: Isometry3<f64>,
27 pub bearing: Vector3<f64>,
28}
29
30#[derive(Debug, Clone, Copy, PartialEq)]
32pub struct TriangulationParams {
33 pub min_observations: usize,
35 pub min_parallax_rad: f64,
37 pub max_ray_error_rad: f64,
39 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
54pub 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#[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#[derive(Debug, Clone, Copy, PartialEq)]
111pub struct BoxFitParams {
112 pub min_points: usize,
114 pub outlier_mads: f64,
118 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
134pub 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
205pub enum ScaleSource {
206 Triangulated,
208 GroundContact,
211}
212
213#[derive(Debug, Clone, Copy, PartialEq)]
215pub struct ObjectEstimate {
216 pub object_id: u64,
217 pub class_id: u32,
218 pub upright_box: UprightBox,
219 pub points: usize,
221 pub scale_source: ScaleSource,
222}
223
224pub 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
246pub fn plausible_size(class_id: u32) -> Option<(f64, f64)> {
250 Some(match class_id {
251 0 => (0.9, 2.2), 1 => (1.2, 2.2), 2 => (3.0, 6.0), 3 => (1.5, 2.6), 5 => (8.0, 20.0), 7 => (4.0, 20.0), 16 => (0.3, 1.3), 39 => (0.15, 0.45), 41 => (0.06, 0.25), 56 => (0.5, 1.3), 57 => (1.2, 3.0), 58 => (0.2, 1.5), 60 => (0.7, 2.5), 62 => (0.3, 2.0), 63 => (0.25, 0.5), 66 => (0.25, 0.6), 73 => (0.12, 0.45), 74 => (0.15, 0.6), _ => return None,
270 })
271}
272
273fn median(values: Vec<f64>) -> Option<f64> {
274 quantile(values, 0.5)
275}
276
277fn 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 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 let still: Vec<_> = (0..4).map(|_| observe(&poses[0], &point)).collect();
325 assert!(triangulate(&still, &TriangulationParams::default()).is_none());
326 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 assert!(triangulate(&observations[..2], &TriangulationParams::default()).is_none());
332 }
333
334 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 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 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 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 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 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}