measure: add measure_cv Rust tests and fix RANSAC inlier floor
- Commit
f92e612962228b835b0cc2a4dfb55cc37a625173- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-17 21:46 UTC (18 days ago)
- Parents
0f64c6d
64 new tests (14 -> 85): epipolar geometry (normalization, 8-point, Sampson, triangulation, cheirality), KLT pyramids and sub-pixel tracking, Shi-Tomasi corners, and the session diagnostics contract on synthetic frames. Fix found by the tests: find_essential_ransac returned a successful essential matrix backed by as few as 1 inlier, letting pose recovery run on almost no evidence; it now reports failure below 8 inliers. cargo test -p measure_cv green.
Diff
measure/src/main/rust/src/corners.rs
diff --git a/measure/src/main/rust/src/corners.rs b/measure/src/main/rust/src/corners.rsindex b47a60c312..11037ee26e 100644--- a/measure/src/main/rust/src/corners.rs+++ b/measure/src/main/rust/src/corners.rs@@ -142,6 +142,8 @@ fn refine_subpixel(gray: &Gray, ix: &[f32], iy: &[f32], x: f32, y: f32) -> (f32, (px, py) } +#[cfg(test)] #[path = "corners_tests.rs"] mod corners_tests;+ #[cfg(test)] mod tests { use super::*;
measure/src/main/rust/src/corners_tests.rs
diff --git a/measure/src/main/rust/src/corners_tests.rs b/measure/src/main/rust/src/corners_tests.rsnew file mode 100644index 0000000000..036fce5c9f--- /dev/null+++ b/measure/src/main/rust/src/corners_tests.rs@@ -0,0 +1,193 @@+//! Additional tests for `corners`: size guards, the corner cap, strongest-first+//! ordering, border exclusion and sub-pixel refinement accuracy. Basic+//! detection quality is covered by the inline test module.++use super::*;++/// White rectangle on black, `value` bright, spanning (x0..x1, y0..y1).+fn rect(w: usize, h: usize, x0: usize, x1: usize, y0: usize, y1: usize, value: u8) -> Gray {+ let mut g = Gray::new(w, h);+ for y in y0..y1 {+ for x in x0..x1 {+ g.px[y * w + x] = value;+ }+ }+ g+}++fn textured(w: usize, h: usize) -> Gray {+ let mut g = Gray::new(w, h);+ for y in 0..h {+ for x in 0..w {+ let v = ((x as f32 * 0.31).sin() * (y as f32 * 0.23).cos()+ + (x as f32 * 0.11 + y as f32 * 0.17).sin())+ * 60.0+ + 128.0;+ g.px[y * w + x] = v.clamp(0.0, 255.0) as u8;+ }+ }+ g+}++#[test]+fn frames_too_small_for_the_border_have_no_corners() {+ // BORDER is 10 per side plus the structure-tensor window: anything under+ // 2*BORDER+8 in either dimension must yield nothing (and not panic).+ assert!(detect(&Gray::new(27, 100)).is_empty());+ assert!(detect(&Gray::new(100, 27)).is_empty());+ assert!(detect(&Gray::new(0, 0)).is_empty());+ assert!(detect(&Gray::new(10, 10)).is_empty());+ // Just above the guard bound, detection runs and finds texture corners.+ assert!(!detect(&textured(64, 64)).is_empty());+}++#[test]+fn detection_is_capped_at_max_corners_on_dense_texture() {+ let pts = detect(&textured(800, 600));+ assert_eq!(pts.len(), MAX_CORNERS, "dense texture should saturate the cap");+}++#[test]+fn detection_is_deterministic() {+ let g = textured(320, 240);+ assert_eq!(detect(&g), detect(&g));+}++#[test]+fn strongest_corners_come_first() {+ // Two squares, one full-contrast and one faint. The structure-tensor score+ // scales with contrast squared, so the bright square's corners must be+ // accepted (and therefore returned) before the faint square's.+ let mut g = rect(320, 200, 40, 110, 40, 110, 255);+ for y in 40..110 {+ for x in 200..270 {+ g.px[y * 320 + x] = 60;+ }+ }+ let pts = detect(&g);+ assert!(pts.len() >= 8, "got {}", pts.len());+ let (fx, fy) = pts[0];+ assert!(+ (37.0..=113.0).contains(&fx) && (37.0..=113.0).contains(&fy),+ "strongest corner should belong to the bright square, got ({fx},{fy})"+ );+}++#[test]+fn corners_stay_out_of_the_border_band() {+ // A square whose corner sits inside the border band must not be reported+ // there: the LK window around a seeded point has to fit in the frame.+ let g = rect(200, 200, 2, 60, 2, 60, 255);+ let pts = detect(&g);+ for &(x, y) in &pts {+ assert!(x >= 8.0 && y >= 8.0, "corner in border band at ({x},{y})");+ }+ // The far corners (59,59) are outside the band and should still be found.+ assert!(pts.iter().any(|&(x, y)| (x - 59.0).abs() < 3.0 && (y - 59.0).abs() < 3.0));+}++#[test]+fn corners_respect_minimum_separation() {+ let pts = detect(&textured(400, 300));+ assert!(pts.len() > 20);+ for i in 0..pts.len() {+ for j in i + 1..pts.len() {+ let dx = pts[i].0 - pts[j].0;+ let dy = pts[i].1 - pts[j].1;+ // 10 px at detection; refinement may close at most ~2 px of that.+ assert!(dx * dx + dy * dy >= 64.0, "points {i},{j} too close");+ }+ }+}++#[test]+fn subpixel_refinement_locates_an_antialiased_corner() {+ // Square with a half-grey leading column/row: the true corner sits at the+ // half-pixel position (70.5, 60.5), and refinement must find it there+ // rather than snapping to a neighbouring integer pixel.+ let mut g = Gray::new(200, 200);+ for y in 61..140 {+ g.px[y * 200 + 70] = 128;+ for x in 71..150 {+ g.px[y * 200 + x] = 255;+ }+ }+ for x in 71..150 {+ g.px[60 * 200 + x] = 255;+ }+ g.px[60 * 200 + 70] = 128;+ // Top edge AA row.+ for x in 71..150 {+ g.px[59 * 200 + x] = 0;+ }+ let pts = detect(&g);+ let near: Vec<(f32, f32)> = pts+ .iter()+ .copied()+ .filter(|&(x, y)| (x - 70.5).abs() < 2.5 && (y - 60.5).abs() < 2.5)+ .collect();+ assert!(!near.is_empty(), "no corner near (70.5,60.5); got {pts:?}");+ let (x, y) = near[0];+ assert!((x - 70.5).abs() < 1.5 && (y - 60.5).abs() < 1.5, "refined to ({x},{y})");+ assert!(x.fract() != 0.0 || y.fract() != 0.0, "expected a sub-pixel position");+}++#[test]+fn a_checkerboard_yields_corners_at_square_junctions() {+ // Alternating 20 px squares: interior T-junctions are true corners with+ // gradients in both axes, unlike the straight edges between squares.+ let mut g = Gray::new(200, 200);+ for y in 0..200 {+ for x in 0..200 {+ if (x / 20 + y / 20) % 2 == 0 {+ g.px[y * 200 + x] = 255;+ }+ }+ }+ let pts = detect(&g);+ assert!(pts.len() >= 10, "got {}", pts.len());+ // A junction, e.g. near (40,40), should be among them.+ assert!(+ pts.iter().any(|&(x, y)| (x - 40.0).abs() < 3.0 && (y - 40.0).abs() < 3.0),+ "no corner near junction (40,40); got {pts:?}"+ );+}++#[test]+fn low_contrast_texture_still_detects_against_its_own_best() {+ // Quality level is relative to the frame's best score, so a faint but+ // structured pattern (amplitude +/-6 grey levels) still yields corners.+ let mut g = Gray::new(240, 180);+ for y in 0..180 {+ for x in 0..240 {+ let v = ((x as f32 * 0.31).sin() * (y as f32 * 0.23).cos()) * 6.0 + 128.0;+ g.px[y * 240 + x] = v.clamp(0.0, 255.0) as u8;+ }+ }+ let pts = detect(&g);+ assert!(pts.len() >= 10, "faint texture gave {}", pts.len());+}++#[test]+fn refine_subpixel_keeps_a_well_defined_corner_near_its_start() {+ // Build gradients exactly as detect does and refine the corner of a square.+ let g = rect(200, 200, 70, 150, 60, 140, 255);+ let (w, h) = (g.w, g.h);+ let mut ix = vec![0f32; w * h];+ let mut iy = vec![0f32; w * h];+ for y in 1..h - 1 {+ for x in 1..w - 1 {+ let i = y * w + x;+ ix[i] = (g.px[i + 1] as f32 - g.px[i - 1] as f32) * 0.5;+ iy[i] = (g.px[i + w] as f32 - g.px[i - w] as f32) * 0.5;+ }+ }+ // Integer corner candidates: the exact edge pixels are (70,60) etc.+ let (x, y) = refine_subpixel(&g, &ix, &iy, 70.0, 60.0);+ assert!((x - 70.0).abs() <= 2.0 && (y - 60.0).abs() <= 2.0, "refined to ({x},{y})");+ // On a flat region the system is singular: refinement must give up and+ // return the starting point unchanged.+ let flat = Gray::new(100, 100);+ let zeros = vec![0f32; 100 * 100];+ assert_eq!(refine_subpixel(&flat, &zeros, &zeros, 50.0, 50.0), (50.0, 50.0));+}
measure/src/main/rust/src/epipolar.rs
diff --git a/measure/src/main/rust/src/epipolar.rs b/measure/src/main/rust/src/epipolar.rsindex 73fabee6aa..3153d468bd 100644--- a/measure/src/main/rust/src/epipolar.rs+++ b/measure/src/main/rust/src/epipolar.rs@@ -165,7 +165,11 @@ pub fn find_essential_ransac( } if best_inliers.len() < 8 {- return best.map(|e| (e, best_inliers));+ // A model backed by fewer points than the minimal 8-point sample is+ // not a RANSAC result (its "inliers" may be a handful of points the+ // projected sample happens to fit). Report failure instead of handing+ // callers an unsupported matrix and pose.+ return None; } let ia: Vec<NPt> = best_inliers.iter().map(|&i| a[i]).collect(); let ib: Vec<NPt> = best_inliers.iter().map(|&i| b[i]).collect();@@ -271,6 +275,8 @@ pub fn recover_pose( Some((pose, inliers)) } +#[cfg(test)] #[path = "epipolar_tests.rs"] mod epipolar_tests;+ #[cfg(test)] mod tests { use super::*;@@ -410,3 +416,4 @@ mod tests { } } }+
measure/src/main/rust/src/epipolar_tests.rs
diff --git a/measure/src/main/rust/src/epipolar_tests.rs b/measure/src/main/rust/src/epipolar_tests.rsnew file mode 100644index 0000000000..db1def59dd--- /dev/null+++ b/measure/src/main/rust/src/epipolar_tests.rs@@ -0,0 +1,383 @@+//! Additional tests for `epipolar`: normalization, constraint enforcement,+//! Sampson scoring, RANSAC support rules, candidate poses, triangulation and+//! cheirality. The happy-path pose recovery lives in the inline test module;+//! these pin the edge cases and invariants those paths rely on.++use super::*;+use vision_core::camera::rodrigues_to_mat;++/// Project a world point into a camera at (R, t) as a calibrated bearing.+fn project(r: &Matrix3<f64>, t: &Vector3<f64>, p: Vector3<f64>) -> NPt {+ let c = r * p + *t;+ (c[0] / c[2], c[1] / c[2])+}++/// Deterministic pseudo-random scene in front of the first camera.+fn scene(n: usize, seed0: u64) -> Vec<Vector3<f64>> {+ let mut pts = Vec::new();+ let mut seed = seed0;+ let mut next = || {+ seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);+ ((seed >> 33) as f64 / (1u64 << 31) as f64) - 0.5+ };+ for _ in 0..n {+ pts.push(Vector3::new(next() * 2.0, next() * 2.0, 3.0 + next() * 2.0));+ }+ pts+}++fn bearings(+ pts: &[Vector3<f64>],+ r: &Matrix3<f64>,+ t: &Vector3<f64>,+) -> (Vec<NPt>, Vec<NPt>) {+ let a = pts+ .iter()+ .map(|&p| project(&Matrix3::identity(), &Vector3::zeros(), p))+ .collect();+ let b = pts.iter().map(|&p| project(r, t, p)).collect();+ (a, b)+}++/// Fixed-seed Gaussian-ish noise (sum of uniforms) added to `b`.+fn add_noise(b: &[NPt], seed0: u64, amp: f64) -> Vec<NPt> {+ let mut seed = seed0;+ let mut u = || {+ seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);+ ((seed >> 33) as f64 / (1u64 << 31) as f64) - 0.5+ };+ b.iter()+ .map(|&(x, y)| (x + (u() + u()) * amp, y + (u() + u()) * amp))+ .collect()+}++fn t_dir_dot(t1: &Vector3<f64>, t2: &Vector3<f64>) -> f64 {+ ((t1[0] / t1.norm()) * (t2[0] / t2.norm())+ + (t1[1] / t1.norm()) * (t2[1] / t2.norm())+ + (t1[2] / t1.norm()) * (t2[2] / t2.norm()))+ .abs()+}++fn max_r_err(r: &Matrix3<f64>, want: &Matrix3<f64>) -> f64 {+ (0..3)+ .map(|i| (0..3).map(move |j| (r[(i, j)] - want[(i, j)]).abs()))+ .flatten()+ .fold(0.0f64, f64::max)+}++// --- Hartley normalization -------------------------------------------------++#[test]+fn normalize_centers_points_and_scales_mean_distance_to_sqrt2() {+ let pts = vec![(1.0, 2.0), (3.0, 2.0), (1.0, 4.0), (3.0, 4.0), (-2.0, 0.5)];+ let (_, n) = normalize(&pts);+ let mx = n.iter().map(|p| p.0).sum::<f64>() / n.len() as f64;+ let my = n.iter().map(|p| p.1).sum::<f64>() / n.len() as f64;+ assert!(mx.abs() < 1e-12 && my.abs() < 1e-12, "centroid ({mx},{my})");+ let md = n.iter().map(|p| (p.0 * p.0 + p.1 * p.1).sqrt()).sum::<f64>() / n.len() as f64;+ assert!((md - (2.0f64).sqrt()).abs() < 1e-12, "mean dist {md}");+}++#[test]+fn normalize_transform_maps_original_points_to_normalized_ones() {+ let pts = vec![(0.3, -0.7), (1.2, 0.4), (-0.5, 0.9), (0.8, -1.1), (0.0, 0.2)];+ let (t, n) = normalize(&pts);+ for (i, &(x, y)) in pts.iter().enumerate() {+ let v = t * Vector3::new(x, y, 1.0);+ assert!((v[0] - n[i].0).abs() < 1e-12, "x mismatch at {i}");+ assert!((v[1] - n[i].1).abs() < 1e-12, "y mismatch at {i}");+ assert!((v[2] - 1.0).abs() < 1e-12);+ }+}++#[test]+fn normalize_a_single_point_lands_on_the_origin() {+ let (t, n) = normalize(&[(5.0, -3.0)]);+ assert_eq!(n, vec![(0.0, 0.0)]);+ // With zero spread the scale falls back to 1 rather than dividing by zero.+ assert!((t[(0, 0)] - 1.0).abs() < 1e-12 && (t[(1, 1)] - 1.0).abs() < 1e-12);+}++#[test]+fn normalize_identical_points_collapse_to_the_origin() {+ let (_, n) = normalize(&[(0.4, 0.4); 6]);+ assert!(n.iter().all(|&p| p.0.abs() < 1e-12 && p.1.abs() < 1e-12));+}++#[test]+fn normalize_empty_input_is_empty() {+ let (_, n) = normalize(&[]);+ assert!(n.is_empty());+}++// --- Eight-point algorithm ---------------------------------------------------++#[test]+fn eight_point_rejects_too_few_and_mismatched_inputs() {+ let pts = scene(10, 7);+ let (a, b) = bearings(&pts, &Matrix3::identity(), &Vector3::new(-0.3, 0.0, 0.0));+ assert!(essential_eight_point(&a[..7], &b[..7]).is_none());+ assert!(essential_eight_point(&a[..9], &b[..8]).is_none());+ assert!(essential_eight_point(&[], &[]).is_none());+}++#[test]+fn eight_point_with_exactly_eight_points_satisfies_the_epipolar_constraint() {+ let pts = scene(8, 11);+ let r = rodrigues_to_mat(Vector3::new(0.01, 0.04, -0.02));+ let t = Vector3::new(-0.3, 0.05, 0.0);+ let (a, b) = bearings(&pts, &r, &t);+ let e = essential_eight_point(&a, &b).expect("E from 8 points");+ for i in 0..8 {+ let x1 = Vector3::new(a[i].0, a[i].1, 1.0);+ let x2 = Vector3::new(b[i].0, b[i].1, 1.0);+ assert!(x2.dot(&(e * x1)).abs() < 1e-9, "residual at {i}");+ }+}++#[test]+fn eight_point_output_has_essential_singular_values() {+ let pts = scene(50, 21);+ let (a, b) = bearings(&pts, &Matrix3::identity(), &Vector3::new(-0.3, 0.02, 0.0));+ let e = essential_eight_point(&a, &b).expect("E");+ let s = e.svd_sorted().singular_values;+ assert!((s[0] - 1.0).abs() < 1e-9, "s0 {s:?}");+ assert!((s[1] - 1.0).abs() < 1e-9, "s1 {s:?}");+ assert!(s[2].abs() < 1e-9, "s2 {s:?}");+}++// --- Constraint enforcement --------------------------------------------------++#[test]+fn enforce_constraints_forces_singular_values_to_one_one_zero() {+ let m = Matrix3::new(0.3, -0.5, 0.8, 1.2, 0.1, -0.4, 0.6, 0.9, 0.2);+ let p = enforce_essential_constraints(&m);+ let s = p.svd_sorted().singular_values;+ assert!((s[0] - 1.0).abs() < 1e-9, "s {s:?}");+ assert!((s[1] - 1.0).abs() < 1e-9, "s {s:?}");+ assert!(s[2].abs() < 1e-9, "s {s:?}");+}++#[test]+fn enforce_constraints_is_idempotent_and_ignores_positive_scale() {+ let pts = scene(40, 31);+ let (a, b) = bearings(&pts, &Matrix3::identity(), &Vector3::new(-0.25, 0.0, 0.0));+ let e = essential_eight_point(&a, &b).expect("E");+ let once = enforce_essential_constraints(&e);+ let twice = enforce_essential_constraints(&once);+ let scaled = enforce_essential_constraints(&Matrix3::new(+ 7.0 * e[(0, 0)], 7.0 * e[(0, 1)], 7.0 * e[(0, 2)],+ 7.0 * e[(1, 0)], 7.0 * e[(1, 1)], 7.0 * e[(1, 2)],+ 7.0 * e[(2, 0)], 7.0 * e[(2, 1)], 7.0 * e[(2, 2)],+ ));+ for i in 0..3 {+ for j in 0..3 {+ assert!((once[(i, j)] - twice[(i, j)]).abs() < 1e-12, "not idempotent");+ assert!((once[(i, j)] - scaled[(i, j)]).abs() < 1e-9, "scale changed result");+ }+ }+ // An essential matrix is a fixed point of the projection.+ assert!(max_r_err(&once, &e) < 1e-9);+}++// --- Sampson distance --------------------------------------------------------++#[test]+fn sampson_distance_grows_for_a_perturbed_correspondence() {+ let pts = scene(40, 41);+ let (a, b) = bearings(&pts, &Matrix3::identity(), &Vector3::new(-0.3, 0.0, 0.0));+ let e = essential_eight_point(&a, &b).expect("E");+ let exact = sampson_distance(&e, a[0], b[0]);+ // This motion (sideways translation, no rotation) has horizontal epipolar+ // lines: sliding b along x stays on the line and must not raise the error,+ // while any vertical step off the line must.+ let along = sampson_distance(&e, a[0], (b[0].0 + 0.05, b[0].1));+ let shifted = sampson_distance(&e, a[0], (b[0].0, b[0].1 + 0.05));+ let gross = sampson_distance(&e, a[0], (b[0].0 + 0.5, b[0].1 - 0.4));+ assert!(exact < 1e-12, "exact {exact}");+ assert!(along < 1e-12, "along-line shift should stay ~zero, got {along}");+ assert!(shifted > 1e-4, "off-line shift {shifted}");+ assert!(gross > 0.01, "gross {gross}");+}++#[test]+fn sampson_distance_is_symmetric_under_transpose_and_swap() {+ let pts = scene(40, 43);+ let (a, b) = bearings(&pts, &Matrix3::identity(), &Vector3::new(-0.3, 0.0, 0.0));+ let e = essential_eight_point(&a, &b).expect("E");+ let d1 = sampson_distance(&e, a[3], b[3]);+ let d2 = sampson_distance(&e.transpose(), b[3], a[3]);+ assert!((d1 - d2).abs() < 1e-15, "{d1} vs {d2}");+}++#[test]+fn sampson_distance_of_a_zero_matrix_is_max() {+ // No epipolar lines exist, so every correspondence is infinitely wrong.+ assert_eq!(sampson_distance(&Matrix3::zeros(), (0.1, 0.2), (0.3, 0.4)), f64::MAX);+}++// --- RANSAC -------------------------------------------------------------------++#[test]+fn ransac_rejects_too_few_mismatched_and_zero_iterations() {+ let pts = scene(20, 51);+ let (a, b) = bearings(&pts, &Matrix3::identity(), &Vector3::new(-0.3, 0.0, 0.0));+ assert!(find_essential_ransac(&a[..7], &b[..7], 100, 1e-4).is_none());+ assert!(find_essential_ransac(&a[..9], &b[..8], 100, 1e-4).is_none());+ assert!(find_essential_ransac(&a, &b, 0, 1e-4).is_none());+}++#[test]+fn ransac_is_deterministic_for_fixed_inputs() {+ let pts = scene(40, 53);+ let (a, b) = bearings(&pts, &Matrix3::identity(), &Vector3::new(-0.3, 0.02, 0.0));+ let r1 = find_essential_ransac(&a, &b, 150, 1e-5).expect("ransac 1");+ let r2 = find_essential_ransac(&a, &b, 150, 1e-5).expect("ransac 2");+ assert_eq!(r1.1, r2.1, "same seed must reproduce the same inliers");+ for i in 0..3 {+ for j in 0..3 {+ assert!((r1.0[(i, j)] - r2.0[(i, j)]).abs() < 1e-12);+ }+ }+}++#[test]+fn ransac_reports_failure_when_no_model_has_eight_inliers() {+ // Regression: with bearing noise and a threshold far below the noise, the+ // best sample fits only a handful of points. Returning that unsupported+ // model (an earlier version returned Some with as few as 1 inlier) lets+ // callers decompose a pose from almost no evidence.+ let pts = scene(40, 4242);+ let r = rodrigues_to_mat(Vector3::new(0.01, 0.04, 0.0));+ let t = Vector3::new(-0.3, 0.02, 0.0);+ let (a, b) = bearings(&pts, &r, &t);+ let noisy = add_noise(&b, 777, 1e-3);+ assert!(find_essential_ransac(&a, &noisy, 200, 3e-6).is_none());+ assert!(recover_pose(&a, &noisy, 200, 3e-6).is_none());+}++#[test]+fn ransac_excludes_gross_outliers_from_the_inlier_set() {+ let pts = scene(40, 61);+ let (mut a, mut b) = bearings(&pts, &Matrix3::identity(), &Vector3::new(-0.3, 0.02, 0.0));+ for i in 0..15 {+ a.push((0.9 - i as f64 * 0.05, -0.8 + i as f64 * 0.07));+ b.push((-0.9 + i as f64 * 0.06, 0.85 - i as f64 * 0.05));+ }+ let (_, inliers) = find_essential_ransac(&a, &b, 300, 1e-4).expect("ransac");+ assert!(inliers.len() >= 38, "kept {} of 40 good points", inliers.len());+ assert!(inliers.iter().all(|&i| i < 40), "an outlier was kept: {inliers:?}");+}++// --- Candidate poses & triangulation ------------------------------------------++#[test]+fn candidate_poses_are_four_orthonormal_poses_with_paired_translations() {+ let m = Matrix3::new(0.3, -0.5, 0.8, 1.2, 0.1, -0.4, 0.6, 0.9, 0.2);+ let e = enforce_essential_constraints(&m);+ let cands = candidate_poses(&e);+ assert_eq!(cands.len(), 4);+ for c in &cands {+ assert!((c.r.determinant() - 1.0).abs() < 1e-9, "not a rotation");+ let rr = c.r * c.r.transpose();+ for i in 0..3 {+ assert!((rr[(i, i)] - 1.0).abs() < 1e-9, "not orthonormal");+ }+ assert!((c.t.norm() - 1.0).abs() < 1e-9, "t not unit");+ }+ // Poses pair up as (R1, +/-t) and (R2, +/-t) with R1 != R2.+ assert!(max_r_err(&cands[0].r, &cands[1].r) < 1e-12);+ assert!(max_r_err(&cands[2].r, &cands[3].r) < 1e-12);+ assert!((cands[0].t[0] + cands[1].t[0]).abs() < 1e-12);+ assert!(max_r_err(&cands[0].r, &cands[2].r) > 0.1, "twisted pair must differ");+}++#[test]+fn triangulate_recovers_a_known_point() {+ let r = rodrigues_to_mat(Vector3::new(0.02, -0.03, 0.01));+ let t = Vector3::new(-0.4, 0.1, 0.05);+ let pose = RelPose { r, t };+ let p = Vector3::new(0.5, -0.3, 4.0);+ let a = project(&Matrix3::identity(), &Vector3::zeros(), p);+ let b = project(&r, &t, p);+ let got = triangulate_pair(&pose, a, b).expect("triangulation");+ for i in 0..3 {+ assert!((got[i] - p[i]).abs() < 1e-9, "coord {i}: {} vs {}", got[i], p[i]);+ }+ // Depth is also positive in the second camera.+ let p2 = r * got + t;+ assert!(p2[2] > 0.0);+}++#[test]+fn triangulate_parallel_rays_returns_none() {+ // Same bearing, camera shifted sideways: the rays never meet.+ let pose = RelPose { r: Matrix3::identity(), t: Vector3::new(1.0, 0.0, 0.0) };+ assert!(triangulate_pair(&pose, (0.0, 0.0), (0.0, 0.0)).is_none());+}++#[test]+fn triangulate_a_point_behind_the_first_camera_keeps_its_negative_depth() {+ // Triangulation itself does not judge cheirality; decompose_essential does.+ let r = rodrigues_to_mat(Vector3::new(0.02, -0.03, 0.01));+ let t = Vector3::new(-0.4, 0.1, 0.05);+ let pose = RelPose { r, t };+ let p = Vector3::new(0.2, 0.1, -3.0);+ let a = project(&Matrix3::identity(), &Vector3::zeros(), p);+ let b = project(&r, &t, p);+ let got = triangulate_pair(&pose, a, b).expect("triangulation");+ assert!(got[2] < 0.0, "expected negative depth, got {}", got[2]);+ assert!((got[2] - p[2]).abs() < 1e-9);+}++// --- Decomposition & full recovery --------------------------------------------++#[test]+fn decompose_selects_the_pose_matching_the_true_motion() {+ let pts = scene(60, 71);+ let r_true = rodrigues_to_mat(Vector3::new(-0.02, 0.06, 0.01));+ let t_true = Vector3::new(0.28, -0.04, 0.03);+ let (a, b) = bearings(&pts, &r_true, &t_true);+ let e = essential_eight_point(&a, &b).expect("E");+ let pose = decompose_essential(&e, &a, &b).expect("pose");+ assert!(max_r_err(&pose.r, &r_true) < 1e-6);+ assert!(t_dir_dot(&pose.t, &t_true) > 0.999);+}++#[test]+fn decompose_returns_none_for_empty_input_and_zero_matrix() {+ assert!(decompose_essential(&Matrix3::identity(), &[], &[]).is_none());+ assert!(decompose_essential(&Matrix3::zeros(), &[(0.1, 0.2)], &[(0.1, 0.2)]).is_none());+}++#[test]+fn recover_pose_tolerates_small_bearing_noise() {+ let pts = scene(50, 83);+ let r_true = rodrigues_to_mat(Vector3::new(0.01, 0.04, 0.0));+ let t_true = Vector3::new(-0.3, 0.02, 0.0);+ let (a, b) = bearings(&pts, &r_true, &t_true);+ let noisy = add_noise(&b, 99, 5e-4);+ let (pose, inliers) = recover_pose(&a, &noisy, 300, 2e-3).expect("pose");+ assert!(inliers.len() >= 40, "inliers {}", inliers.len());+ assert!(t_dir_dot(&pose.t, &t_true) > 0.98);+ assert!(max_r_err(&pose.r, &r_true) < 0.02);+}++#[test]+fn recover_pose_recovers_forward_motion() {+ let pts = scene(60, 97);+ let r_true = Matrix3::identity();+ let t_true = Vector3::new(0.02, -0.01, -0.35);+ let (a, b) = bearings(&pts, &r_true, &t_true);+ let (pose, inliers) = recover_pose(&a, &b, 300, 1e-6).expect("pose");+ assert!(inliers.len() > 50);+ assert!(t_dir_dot(&pose.t, &t_true) > 0.99);+}++#[test]+fn recover_pose_rejects_too_few_and_mismatched_inputs() {+ let pts = scene(10, 101);+ let (a, b) = bearings(&pts, &Matrix3::identity(), &Vector3::new(-0.3, 0.0, 0.0));+ assert!(recover_pose(&a[..5], &b[..5], 100, 1e-4).is_none());+ assert!(recover_pose(&a[..9], &b[..8], 100, 1e-4).is_none());+}
measure/src/main/rust/src/klt.rs
diff --git a/measure/src/main/rust/src/klt.rs b/measure/src/main/rust/src/klt.rsindex 777f6fe9f8..da575850e7 100644--- a/measure/src/main/rust/src/klt.rs+++ b/measure/src/main/rust/src/klt.rs@@ -171,6 +171,8 @@ pub fn track(prev: &Pyramid, next: &Pyramid, points: &[(f32, f32)]) -> Vec<Track .collect() } +#[cfg(test)] #[path = "klt_tests.rs"] mod klt_tests;+ #[cfg(test)] mod tests { use super::*;
measure/src/main/rust/src/klt_tests.rs
diff --git a/measure/src/main/rust/src/klt_tests.rs b/measure/src/main/rust/src/klt_tests.rsnew file mode 100644index 0000000000..bb60c6312b--- /dev/null+++ b/measure/src/main/rust/src/klt_tests.rs@@ -0,0 +1,248 @@+//! Additional tests for `klt`: bilinear sampling, single-level tracking,+//! pyramid construction edges, and the coarse-to-fine advantage on large+//! displacements. Basic translation tracking is covered inline.++use super::*;++/// Smooth sinusoid texture at a (possibly fractional) shift.+fn checker_f(w: usize, h: usize, sx: f32, sy: f32) -> Gray {+ let mut g = Gray::new(w, h);+ for y in 0..h {+ for x in 0..w {+ let v = (((x as f32 - sx) * 0.35).sin() * ((y as f32 - sy) * 0.27).cos() + 1.0)+ * 110.0;+ g.px[y * w + x] = v as u8;+ }+ }+ g+}++/// Smooth aperiodic texture: seeded random coarse grid, bilinear-upsampled.+/// Unlike a pure sinusoid it has no period for the tracker to alias onto.+fn aperiodic(w: usize, h: usize, shift_x: i32, shift_y: i32) -> Gray {+ let mut seed = 20240u64;+ let mut rnd = || {+ seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);+ ((seed >> 40) & 0xff) as f32+ };+ let gw = w / 4 + 8;+ let gh = h / 4 + 8;+ let grid: Vec<f32> = (0..gw * gh).map(|_| rnd()).collect();+ let mut g = Gray::new(w, h);+ for y in 0..h {+ for x in 0..w {+ let gx = (x as i32 - shift_x) as f32 / 4.0 + 4.0;+ let gy = (y as i32 - shift_y) as f32 / 4.0 + 4.0;+ let (x0, y0) = (gx.floor() as usize, gy.floor() as usize);+ let (fx, fy) = (gx - x0 as f32, gy - y0 as f32);+ let v = grid[y0 * gw + x0] * (1.0 - fx) * (1.0 - fy)+ + grid[y0 * gw + x0 + 1] * fx * (1.0 - fy)+ + grid[(y0 + 1) * gw + x0] * (1.0 - fx) * fy+ + grid[(y0 + 1) * gw + x0 + 1] * fx * fy;+ g.px[y * w + x] = v.clamp(0.0, 255.0) as u8;+ }+ }+ g.gaussian_blur_3x3()+}++// --- Bilinear sampling --------------------------------------------------------++#[test]+fn sample_at_integer_coordinates_returns_the_exact_pixel() {+ let mut g = Gray::new(8, 8);+ for y in 0..8 {+ for x in 0..8 {+ g.px[y * 8 + x] = (y * 8 + x) as u8;+ }+ }+ assert_eq!(sample(&g, 3.0, 2.0), Some(2.0 * 8.0 + 3.0));+ assert_eq!(sample(&g, 0.0, 0.0), Some(0.0));+}++#[test]+fn sample_interpolates_linearly_between_pixels() {+ // A horizontal ramp: value == x * 10 everywhere.+ let mut g = Gray::new(16, 4);+ for y in 0..4 {+ for x in 0..16 {+ g.px[y * 16 + x] = (x * 10) as u8;+ }+ }+ assert_eq!(sample(&g, 2.5, 1.0), Some(25.0));+ assert_eq!(sample(&g, 2.25, 1.0), Some(22.5));+ // Vertical interpolation on the same ramp changes nothing.+ assert_eq!(sample(&g, 2.5, 1.5), Some(25.0));+}++#[test]+fn sample_rejects_points_outside_the_valid_interior() {+ let g = Gray::new(16, 16);+ assert_eq!(sample(&g, -0.5, 5.0), None);+ assert_eq!(sample(&g, 5.0, -1.0), None);+ // The last valid coordinate is just under w-1 / h-1: bilinear needs the+ // (x+1, y+1) neighbours to exist.+ assert_eq!(sample(&g, 15.0, 5.0), None);+ assert_eq!(sample(&g, 5.0, 15.0), None);+ assert!(sample(&g, 14.9, 14.9).is_some());+}++// --- Pyramid construction ------------------------------------------------------++#[test]+fn pyramid_with_one_level_is_just_the_base_image() {+ let a = checker_f(128, 96, 0.0, 0.0);+ let p = Pyramid::build(&a, 1);+ assert_eq!(p.levels.len(), 1);+ assert_eq!((p.levels[0].w, p.levels[0].h), (128, 96));+ assert_eq!(p.levels[0].px, a.px);+}++#[test]+fn pyramid_levels_keep_the_same_content_at_half_resolution() {+ // Downsampled level of a smooth image should roughly preserve local means:+ // compare the centre pixel against the corresponding base neighbourhood.+ let a = checker_f(160, 160, 0.0, 0.0);+ let p = Pyramid::build(&a, 3);+ let base_mean = {+ let mut s = 0f32;+ for y in 78..83 {+ for x in 78..83 {+ s += a.at(x, y) as f32;+ }+ }+ s / 25.0+ };+ let coarse = p.levels[1].at(40, 40) as f32;+ assert!((coarse - base_mean).abs() < 20.0, "coarse {coarse} vs base {base_mean}");+}++#[test]+fn pyramid_of_a_tiny_image_stays_a_single_level() {+ let a = checker_f(20, 20, 0.0, 0.0);+ let p = Pyramid::build(&a, 4);+ assert_eq!(p.levels.len(), 1);+}++// --- Single-level tracking -------------------------------------------------------++#[test]+fn track_level_on_identical_images_finds_zero_displacement() {+ let a = checker_f(128, 128, 0.0, 0.0);+ let v = track_level(&a, &a, 64.0, 64.0, (0.0, 0.0)).expect("track");+ assert!(v.0.abs() < 0.02 && v.1.abs() < 0.02, "got {v:?}");+}++#[test]+fn track_level_recovers_a_small_subpixel_shift() {+ let a = checker_f(128, 128, 0.0, 0.0);+ let b = checker_f(128, 128, 1.3, -0.7);+ let v = track_level(&a, &b, 64.0, 64.0, (0.0, 0.0)).expect("track");+ assert!((v.0 - 1.3).abs() < 0.15, "dx {}", v.0);+ assert!((v.1 + 0.7).abs() < 0.15, "dy {}", v.1);+}++#[test]+fn track_level_rejects_a_flat_patch() {+ let mut a = Gray::new(128, 128);+ for v in a.px.iter_mut() {+ *v = 200;+ }+ assert!(track_level(&a, &a, 64.0, 64.0, (0.0, 0.0)).is_none());+}++#[test]+fn track_level_rejects_a_pure_edge_patch() {+ // Vertical step edge: gradient only along x, so the 2x2 structure tensor+ // is (near-)singular and y displacement is unobservable.+ let mut a = Gray::new(128, 128);+ for y in 0..128 {+ for x in 64..128 {+ a.px[y * 128 + x] = 255;+ }+ }+ assert!(track_level(&a, &a, 64.0, 64.0, (0.0, 0.0)).is_none());+}++#[test]+fn track_level_rejects_a_window_centred_outside_the_frame() {+ let a = checker_f(128, 128, 0.0, 0.0);+ assert!(track_level(&a, &a, 2.0, 2.0, (0.0, 0.0)).is_none());+ assert!(track_level(&a, &a, 126.0, 64.0, (0.0, 0.0)).is_none());+}++// --- Full pyramidal tracking ------------------------------------------------------++#[test]+fn tracks_a_fractional_pixel_shift() {+ let a = checker_f(160, 160, 0.0, 0.0);+ let b = checker_f(160, 160, 2.5, 1.5);+ let res = track(&Pyramid::build(&a, 3), &Pyramid::build(&b, 3), &[(80.0, 80.0)]);+ assert!(res[0].ok);+ assert!((res[0].x - 82.5).abs() < 0.25, "x {}", res[0].x);+ assert!((res[0].y - 81.5).abs() < 0.25, "y {}", res[0].y);+}++#[test]+fn the_pyramid_tracks_large_shifts_a_single_level_cannot() {+ // 11 px exceeds the useful convergence radius of a 15x15 single-level+ // window; coarse-to-fine tracking shrinks it to ~3 px at the top level.+ let a = aperiodic(240, 240, 0, 0);+ let b = aperiodic(240, 240, 11, -6);+ let pts = vec![(90.0f32, 150.0f32), (150.0, 90.0)];+ let pyr = track(&Pyramid::build(&a, 3), &Pyramid::build(&b, 3), &pts);+ let single = track(&Pyramid::build(&a, 1), &Pyramid::build(&b, 1), &pts);+ for i in 0..pts.len() {+ assert!(pyr[i].ok, "pyramidal track failed for point {i}");+ assert!((pyr[i].x - (pts[i].0 + 11.0)).abs() < 0.75, "pyr x {}", pyr[i].x);+ assert!((pyr[i].y - (pts[i].1 - 6.0)).abs() < 0.75, "pyr y {}", pyr[i].y);+ let single_err = ((single[i].x - (pts[i].0 + 11.0)).powi(2)+ + (single[i].y - (pts[i].1 - 6.0)).powi(2))+ .sqrt();+ assert!(+ !single[i].ok || single_err > 2.0,+ "single level unexpectedly accurate for point {i}: err {single_err}"+ );+ }+}++#[test]+fn tracking_an_empty_point_list_returns_empty() {+ let a = checker_f(64, 64, 0.0, 0.0);+ let res = track(&Pyramid::build(&a, 3), &Pyramid::build(&a, 3), &[]);+ assert!(res.is_empty());+}++#[test]+fn mismatched_pyramid_depths_still_track_small_shifts() {+ let a = checker_f(160, 160, 0.0, 0.0);+ let b = checker_f(160, 160, 2.0, 1.0);+ let res = track(&Pyramid::build(&a, 3), &Pyramid::build(&b, 2), &[(80.0, 80.0)]);+ assert!(res[0].ok);+ assert!((res[0].x - 82.0).abs() < 0.5 && (res[0].y - 81.0).abs() < 0.5);+}++#[test]+fn a_point_whose_window_leaves_the_frame_is_dropped_not_clamped() {+ let a = checker_f(128, 128, 0.0, 0.0);+ let b = checker_f(128, 128, 3.0, 0.0);+ let res = track(&Pyramid::build(&a, 3), &Pyramid::build(&b, 3), &[(5.0, 64.0)]);+ assert!(!res[0].ok);+ // On failure the result reports the original position, un-displaced.+ assert_eq!((res[0].x, res[0].y), (5.0, 64.0));+}++#[test]+fn tracking_from_a_blank_frame_is_rejected() {+ // The reverse direction of an occlusion: with a flat source patch the+ // displacement is unobservable, whatever the target holds. This is what+ // makes the session's forward-backward check reject points that were+ // "tracked" into a featureless region.+ let a = aperiodic(200, 200, 0, 0);+ let mut blank = Gray::new(200, 200);+ for v in blank.px.iter_mut() {+ *v = 128;+ }+ let pts: Vec<(f32, f32)> = (0..5).map(|i| (60.0 + i as f32 * 20.0, 100.0)).collect();+ let res = track(&Pyramid::build(&blank, 3), &Pyramid::build(&a, 3), &pts);+ assert!(res.iter().all(|r| !r.ok));+}
measure/src/main/rust/src/lib.rs
diff --git a/measure/src/main/rust/src/lib.rs b/measure/src/main/rust/src/lib.rsindex 80016c9ffe..990911a70e 100644--- a/measure/src/main/rust/src/lib.rs+++ b/measure/src/main/rust/src/lib.rs@@ -19,6 +19,8 @@ pub mod corners; pub mod epipolar; pub mod klt; +#[cfg(test)] #[path = "lib_tests.rs"] mod lib_tests;+ use epipolar::{recover_pose, RelPose}; use klt::Pyramid; use vision_core::imgbuf::Gray;
measure/src/main/rust/src/lib_tests.rs
diff --git a/measure/src/main/rust/src/lib_tests.rs b/measure/src/main/rust/src/lib_tests.rsnew file mode 100644index 0000000000..1b3f832156--- /dev/null+++ b/measure/src/main/rust/src/lib_tests.rs@@ -0,0 +1,193 @@+//! Tests for `CvSession` state handling and the pixel->bearing calibration.+//! End-to-end frame behaviour is also covered by `tests/cv_core.rs`; these pin+//! the diagnostics contract and recovery paths the Kotlin engine reads.++use super::*;+use vision_core::imgbuf::Gray;++/// Smooth aperiodic texture (seeded random grid, upsampled), shifted by whole+/// pixels. No period for the tracker or the corner detector to alias onto.+fn aperiodic(w: usize, h: usize, shift_x: i32, shift_y: i32) -> Gray {+ let mut seed = 20240u64;+ let mut rnd = || {+ seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);+ ((seed >> 40) & 0xff) as f32+ };+ let gw = w / 4 + 8;+ let gh = h / 4 + 8;+ let grid: Vec<f32> = (0..gw * gh).map(|_| rnd()).collect();+ let mut g = Gray::new(w, h);+ for y in 0..h {+ for x in 0..w {+ let gx = (x as i32 - shift_x) as f32 / 4.0 + 4.0;+ let gy = (y as i32 - shift_y) as f32 / 4.0 + 4.0;+ let (x0, y0) = (gx.floor() as usize, gy.floor() as usize);+ let (fx, fy) = (gx - x0 as f32, gy - y0 as f32);+ let v = grid[y0 * gw + x0] * (1.0 - fx) * (1.0 - fy)+ + grid[y0 * gw + x0 + 1] * fx * (1.0 - fy)+ + grid[(y0 + 1) * gw + x0] * (1.0 - fx) * fy+ + grid[(y0 + 1) * gw + x0 + 1] * fx * fy;+ g.px[y * w + x] = v.clamp(0.0, 255.0) as u8;+ }+ }+ g.gaussian_blur_3x3()+}++fn blank(w: usize, h: usize) -> Gray {+ let mut g = Gray::new(w, h);+ for v in g.px.iter_mut() {+ *v = 128;+ }+ g+}++// --- Calibration ---------------------------------------------------------------++#[test]+fn calibrated_maps_the_principal_point_to_the_origin() {+ let s = CvSession::new(300.0, 280.0, 160.0, 120.0);+ assert_eq!(s.calibrated((160.0, 120.0)), (0.0, 0.0));+}++#[test]+fn calibrated_applies_focal_length_and_principal_point_per_axis() {+ let s = CvSession::new(200.0, 100.0, 50.0, 40.0);+ assert_eq!(s.calibrated((250.0, 140.0)), (1.0, 1.0));+ assert_eq!(s.calibrated((0.0, 0.0)), (-0.25, -0.4));+ // One focal length right of centre on x, centre on y.+ assert_eq!(s.calibrated((250.0, 40.0)), (1.0, 0.0));+}++// --- Session state machine -------------------------------------------------------++#[test]+fn first_frame_reports_the_full_diagnostics_contract() {+ let mut s = CvSession::new(300.0, 300.0, 160.0, 120.0);+ let flow = s.process_frame(&aperiodic(320, 240, 0, 0));+ assert!(flow.first_frame);+ assert!(flow.pairs.is_empty());+ assert!(flow.pose.is_none());+ assert_eq!(flow.seeded, flow.point_count, "first frame seeds what it reports");+ assert_eq!(flow.forward_ok, 0);+ assert_eq!(flow.fb_survivors, 0);+ assert_eq!(flow.ransac_inliers, -1, "RANSAC did not run");+ assert!(flow.point_count > 50);+}++#[test]+fn diagnostics_are_ordered_and_consistent_on_a_tracked_frame() {+ let mut s = CvSession::new(300.0, 300.0, 160.0, 120.0);+ let f1 = s.process_frame(&aperiodic(320, 240, 0, 0));+ let f2 = s.process_frame(&aperiodic(320, 240, 3, 1));+ assert!(!f2.first_frame);+ assert_eq!(f2.seeded, f1.point_count, "seeded is what the last frame left");+ assert!(f2.forward_ok >= f2.fb_survivors, "FB check can only remove tracks");+ assert!(f2.fb_survivors >= f2.pairs.len(), "RANSAC can only remove pairs");+ assert!(f2.point_count >= f2.pairs.len());+ assert!(f2.point_count <= corners::MAX_CORNERS);+ if f2.pose.is_some() {+ // When a pose was recovered, pairs are exactly the RANSAC inliers.+ assert_eq!(f2.ransac_inliers as usize, f2.pairs.len());+ }+}++#[test]+fn a_sideways_shift_recovers_a_pose_with_dominant_x_translation() {+ let mut s = CvSession::new(300.0, 300.0, 160.0, 120.0);+ s.process_frame(&aperiodic(320, 240, 0, 0));+ let f2 = s.process_frame(&aperiodic(320, 240, 3, 0));+ let pose = f2.pose.expect("pose from a clean sideways shift");+ // Near-identity rotation for a pure translation.+ assert!((pose.r[(0, 0)] - 1.0).abs() < 0.02, "R00 {}", pose.r[(0, 0)]);+ assert!((pose.r[(1, 1)] - 1.0).abs() < 0.02, "R11 {}", pose.r[(1, 1)]);+ assert!(pose.r[(0, 1)].abs() < 0.02 && pose.r[(1, 0)].abs() < 0.02);+ // Unit translation, dominated by the x axis (sign fixed by the epipolar+ // convention and asserted exactly in the epipolar unit tests).+ let n = pose.t.norm();+ assert!((n - 1.0).abs() < 1e-9, "|t| {n}");+ assert!(pose.t[0].abs() / n > 0.8, "t {:?}", pose.t);+}++#[test]+fn too_few_pairs_skip_ransac_and_pose() {+ // A small frame yields only a couple of tracks: below the 8-point minimum+ // RANSAC must not run (ransac_inliers stays -1) and no pose is reported.+ let mut s = CvSession::new(300.0, 300.0, 50.0, 40.0);+ s.process_frame(&aperiodic(100, 80, 0, 0));+ let f2 = s.process_frame(&aperiodic(100, 80, 2, 0));+ assert!(f2.pairs.len() < 8, "pairs {}", f2.pairs.len());+ assert_eq!(f2.ransac_inliers, -1);+ assert!(f2.pose.is_none());+}++#[test]+fn an_occluded_frame_produces_no_pairs_and_the_session_recovers() {+ // Texture -> blank: forward LK alone drifts, but every backward track+ // starts from a flat patch and is rejected, so the FB check must kill+ // all pairs. The next textured frame then reseeds via the top-up path.+ let mut s = CvSession::new(300.0, 300.0, 160.0, 120.0);+ s.process_frame(&aperiodic(320, 240, 0, 0));+ let f2 = s.process_frame(&blank(320, 240));+ assert!(f2.pairs.is_empty(), "occluded frame kept {} pairs", f2.pairs.len());+ assert!(f2.pose.is_none());+ assert_eq!(f2.point_count, 0, "a blank frame seeds nothing");+ let f3 = s.process_frame(&aperiodic(320, 240, 1, 0));+ assert!(f3.point_count > 50, "session did not reseed, got {}", f3.point_count);+ let f4 = s.process_frame(&aperiodic(320, 240, 4, 1));+ assert!(f4.pairs.len() >= 15, "tracking did not resume: {}", f4.pairs.len());+}++#[test]+fn losing_most_tracks_triggers_a_top_up_reseed() {+ // A 60 px jump decorrelates the texture: nearly all tracks die, and the+ // session must top the point set back up from fresh corners instead of+ // starving on the handful of survivors.+ let mut s = CvSession::new(300.0, 300.0, 160.0, 120.0);+ s.process_frame(&aperiodic(320, 240, 0, 0));+ let f2 = s.process_frame(&aperiodic(320, 240, 60, 40));+ assert!(f2.pairs.len() < 20, "jump kept {} pairs", f2.pairs.len());+ assert!(+ f2.point_count >= corners::MAX_CORNERS / 2,+ "no top-up: point_count {}",+ f2.point_count+ );+ // Freshly seeded points are trackable on the next small motion.+ let f3 = s.process_frame(&aperiodic(320, 240, 63, 41));+ assert!(f3.pairs.len() >= 15, "reseeded points did not track: {}", f3.pairs.len());+}++#[test]+fn point_ids_never_repeat_within_a_frame_even_after_top_up() {+ let mut s = CvSession::new(300.0, 300.0, 160.0, 120.0);+ s.process_frame(&aperiodic(320, 240, 0, 0));+ s.process_frame(&aperiodic(320, 240, 60, 40)); // forces a top-up+ let f3 = s.process_frame(&aperiodic(320, 240, 63, 41));+ let mut ids: Vec<u64> = f3.pairs.iter().map(|p| p.id).collect();+ assert!(ids.len() >= 15);+ ids.sort_unstable();+ ids.dedup();+ assert_eq!(ids.len(), f3.pairs.len(), "duplicate id after top-up");+ assert!(ids.iter().all(|&id| id >= 1), "ids are 1-based");+}++#[test]+fn tiny_frames_never_track_and_never_panic() {+ let mut s = CvSession::new(300.0, 300.0, 10.0, 10.0);+ let f1 = s.process_frame(&Gray::new(20, 20));+ assert!(f1.first_frame);+ assert_eq!(f1.point_count, 0);+ let f2 = s.process_frame(&Gray::new(20, 20));+ assert!(f2.pairs.is_empty());+ assert!(f2.pose.is_none());+}++#[test]+fn reset_clears_points_so_the_next_frame_reseeds_from_scratch() {+ let mut s = CvSession::new(300.0, 300.0, 160.0, 120.0);+ let f1 = s.process_frame(&aperiodic(320, 240, 0, 0));+ s.process_frame(&aperiodic(320, 240, 3, 0));+ s.reset();+ let f3 = s.process_frame(&aperiodic(320, 240, 5, 5));+ assert!(f3.first_frame);+ assert_eq!(f3.point_count, f1.point_count, "same frame must reseed identically");+}