1use crate::linalg::{damped_least_squares, jacobi_eigen, smallest_right_singular};
20use crate::matrix::Matrix;
21use crate::{Error, Result};
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum EstimationMethod {
30 LeastSquares,
31 Ransac,
32}
33
34pub struct HomographyResult {
37 pub matrix: Matrix,
38 pub mask: Matrix,
39}
40
41pub struct PnpResult {
44 pub rotation_vector: Matrix,
45 pub translation_vector: Matrix,
46}
47
48pub struct PnpRansacResult {
50 pub rotation_vector: Matrix,
51 pub translation_vector: Matrix,
52 pub mask: Matrix,
53}
54
55pub struct EpipolarResult {
57 pub matrix: Matrix,
58 pub mask: Matrix,
59}
60
61pub struct RecoverPoseResult {
64 pub rotation: Matrix,
65 pub translation: Matrix,
66 pub mask: Matrix,
67}
68
69pub struct CalibrateCameraResult {
74 pub camera: Matrix,
75 pub distortion: Matrix,
76 pub rotations: Matrix,
77 pub translations: Matrix,
78 pub rms_error: Matrix,
79}
80
81pub fn find_homography(
94 source: &Matrix,
95 destination: &Matrix,
96 method: EstimationMethod,
97 ransac_threshold: f32,
98 max_iterations: i32,
99 seed: u64,
100) -> Result<HomographyResult> {
101 let source = read_points2(source, 4, "find_homography")?;
102 let destination = read_points2(destination, 4, "find_homography")?;
103 if source.len() != destination.len() {
104 return Err(Error::invalid_argument(
105 "find_homography source and destination must share point count",
106 ));
107 }
108 match method {
109 EstimationMethod::LeastSquares => {
110 let h = dlt_homography(&source, &destination).ok_or_else(|| degenerate("find_homography"))?;
111 Ok(HomographyResult {
112 matrix: mat3_f32(h)?,
113 mask: ones_mask(source.len())?,
114 })
115 }
116 EstimationMethod::Ransac => {
117 if !ransac_threshold.is_finite() || ransac_threshold <= 0.0 {
118 return Err(Error::invalid_argument(
119 "find_homography ransac_threshold must be positive and finite",
120 ));
121 }
122 if max_iterations < 1 {
123 return Err(Error::invalid_argument(
124 "find_homography max_iterations must be positive",
125 ));
126 }
127 let n = source.len();
128 let threshold = ransac_threshold as f64;
129 let inliers = ransac_consensus(4, n, max_iterations as usize, seed, |sample| {
130 let src: Vec<[f64; 2]> = sample.iter().map(|i| source[*i]).collect();
131 let dst: Vec<[f64; 2]> = sample.iter().map(|i| destination[*i]).collect();
132 dlt_homography(&src, &dst).map(|h| {
133 inlier_indices(n, |i| {
134 homography_error(&h, &source[i], &destination[i]) <= threshold
135 })
136 })
137 })
138 .ok_or_else(|| degenerate("find_homography"))?;
139 let src: Vec<[f64; 2]> = inliers.iter().map(|i| source[*i]).collect();
140 let dst: Vec<[f64; 2]> = inliers.iter().map(|i| destination[*i]).collect();
141 let h = dlt_homography(&src, &dst).ok_or_else(|| degenerate("find_homography"))?;
142 Ok(HomographyResult {
143 matrix: mat3_f32(h)?,
144 mask: index_mask(n, &inliers)?,
145 })
146 }
147 }
148}
149
150pub fn solve_pnp(object: &Matrix, image: &Matrix, camera: &Matrix) -> Result<PnpResult> {
161 let object = read_points3(object, 4, "solve_pnp")?;
162 let image = read_points2(image, 4, "solve_pnp")?;
163 if object.len() != image.len() {
164 return Err(Error::invalid_argument(
165 "solve_pnp object and image must share point count",
166 ));
167 }
168 let k = read_mat3(camera, "solve_pnp")?;
169 let pose = dlt_pose(&object, &image, &k).ok_or_else(|| degenerate("solve_pnp"))?;
170 let pose = refine_pose(&object, &image, &k, pose).ok_or_else(|| degenerate("solve_pnp"))?;
171 Ok(PnpResult {
172 rotation_vector: vector_f32(&rodrigues_vector(&pose.0))?,
173 translation_vector: vector_f32(&[pose.1[0], pose.1[1], pose.1[2]])?,
174 })
175}
176
177pub fn solve_pnp_ransac(
187 object: &Matrix,
188 image: &Matrix,
189 camera: &Matrix,
190 reprojection_threshold: f32,
191 max_iterations: i32,
192 seed: u64,
193) -> Result<PnpRansacResult> {
194 let object = read_points3(object, 6, "solve_pnp_ransac")?;
195 let image = read_points2(image, 6, "solve_pnp_ransac")?;
196 if object.len() != image.len() {
197 return Err(Error::invalid_argument(
198 "solve_pnp_ransac object and image must share point count",
199 ));
200 }
201 if !reprojection_threshold.is_finite() || reprojection_threshold <= 0.0 {
202 return Err(Error::invalid_argument(
203 "solve_pnp_ransac reprojection_threshold must be positive and finite",
204 ));
205 }
206 if max_iterations < 1 {
207 return Err(Error::invalid_argument(
208 "solve_pnp_ransac max_iterations must be positive",
209 ));
210 }
211 let k = read_mat3(camera, "solve_pnp_ransac")?;
212 let n = object.len();
213 let threshold = reprojection_threshold as f64;
214 let inliers = ransac_consensus(6, n, max_iterations as usize, seed, |sample| {
215 let obj: Vec<[f64; 3]> = sample.iter().map(|i| object[*i]).collect();
216 let img: Vec<[f64; 2]> = sample.iter().map(|i| image[*i]).collect();
217 dlt_pose(&obj, &img, &k)
218 .and_then(|pose| refine_pose(&obj, &img, &k, pose))
219 .map(|pose| {
220 inlier_indices(n, |i| {
221 reprojection_error(&pose, &k, &object[i], &image[i]) <= threshold
222 })
223 })
224 })
225 .ok_or_else(|| degenerate("solve_pnp_ransac"))?;
226 let obj: Vec<[f64; 3]> = inliers.iter().map(|i| object[*i]).collect();
227 let img: Vec<[f64; 2]> = inliers.iter().map(|i| image[*i]).collect();
228 let pose = dlt_pose(&obj, &img, &k)
229 .and_then(|pose| refine_pose(&obj, &img, &k, pose))
230 .ok_or_else(|| degenerate("solve_pnp_ransac"))?;
231 Ok(PnpRansacResult {
232 rotation_vector: vector_f32(&rodrigues_vector(&pose.0))?,
233 translation_vector: vector_f32(&[pose.1[0], pose.1[1], pose.1[2]])?,
234 mask: index_mask(n, &inliers)?,
235 })
236}
237
238pub fn rodrigues(input: &Matrix) -> Result<Matrix> {
246 let shape = input.shape();
247 let values = input.read_f32()?;
248 if shape == [3, 1].as_slice() || shape == [1, 3].as_slice() {
249 let r = [values[0] as f64, values[1] as f64, values[2] as f64];
250 let rotation = rodrigues_matrix(&r);
251 mat3_f32(rotation)
252 } else if shape == [3, 3].as_slice() {
253 let m = read_mat3(input, "rodrigues")?;
254 vector_f32(&rodrigues_vector(&m))
255 } else {
256 Err(Error::invalid_argument(
257 "rodrigues requires a [3, 1]/[1, 3] rotation vector or [3, 3] rotation matrix",
258 ))
259 }
260}
261
262pub fn project_points(
273 object: &Matrix,
274 rvec: &Matrix,
275 tvec: &Matrix,
276 camera: &Matrix,
277 distortion: &Matrix,
278) -> Result<Matrix> {
279 let object = read_points3(object, 1, "project_points")?;
280 let r = read_vector(rvec, 3, "project_points")?;
281 let t = read_vector(tvec, 3, "project_points")?;
282 let k = read_mat3(camera, "project_points")?;
283 let distortion = read_vector_free(distortion, "project_points")?;
284 let rotation = rodrigues_matrix(&[r[0], r[1], r[2]]);
285 let mut projected = Vec::with_capacity(object.len() * 2);
286 for point in &object {
287 let [x, y, z] = camera_project(&rotation, &[t[0], t[1], t[2]], point);
288 if z.abs() < 1e-12 {
289 return Err(Error::invalid_argument(
290 "project_points produced a point at the camera plane",
291 ));
292 }
293 let (xn, yn) = distort_normalized(x / z, y / z, &distortion);
294 projected.push((k[0][0] * xn + k[0][1] * yn + k[0][2]) as f32);
295 projected.push((k[1][0] * xn + k[1][1] * yn + k[1][2]) as f32);
296 }
297 Matrix::new_from_f32([object.len(), 2], &projected)
298}
299
300pub fn undistort_rectify_map(
311 camera: &Matrix,
312 distortion: &Matrix,
313 rectification: Option<&Matrix>,
314 projection: Option<&Matrix>,
315 width: i32,
316 height: i32,
317) -> Result<Matrix> {
318 if width < 1 || height < 1 {
319 return Err(Error::invalid_argument(
320 "undistort_rectify_map requires positive width and height",
321 ));
322 }
323 let k = read_mat3(camera, "undistort_rectify_map")?;
324 let distortion = read_vector_free(distortion, "undistort_rectify_map")?;
325 let rotation = match rectification {
326 Some(matrix) => read_mat3(matrix, "undistort_rectify_map")?,
327 None => IDENTITY3,
328 };
329 let projection = match projection {
330 Some(matrix) => read_mat3(matrix, "undistort_rectify_map")?,
331 None => k,
332 };
333 let pinv = invert3(projection)
334 .ok_or_else(|| Error::invalid_argument("undistort_rectify_map projection is singular"))?;
335 let (w, h) = (width as usize, height as usize);
336 let mut map = vec![0.0f32; 2 * w * h];
337 for v in 0..h {
338 for u in 0..w {
339 let pin = [
341 pinv[0][0] * u as f64 + pinv[0][1] * v as f64 + pinv[0][2],
342 pinv[1][0] * u as f64 + pinv[1][1] * v as f64 + pinv[1][2],
343 pinv[2][0] * u as f64 + pinv[2][1] * v as f64 + pinv[2][2],
344 ];
345 let ideal = [
346 rotation[0][0] * pin[0] + rotation[0][1] * pin[1] + rotation[0][2] * pin[2],
347 rotation[1][0] * pin[0] + rotation[1][1] * pin[1] + rotation[1][2] * pin[2],
348 rotation[2][0] * pin[0] + rotation[2][1] * pin[1] + rotation[2][2] * pin[2],
349 ];
350 if ideal[2].abs() < 1e-12 {
351 return Err(Error::invalid_argument(
352 "undistort_rectify_map rectification produced a point at the plane",
353 ));
354 }
355 let (xd, yd) = distort_normalized(ideal[0] / ideal[2], ideal[1] / ideal[2], &distortion);
356 map[v * w + u] = (k[0][0] * xd + k[0][1] * yd + k[0][2]) as f32;
357 map[w * h + v * w + u] = (k[1][0] * xd + k[1][1] * yd + k[1][2]) as f32;
358 }
359 }
360 Matrix::new_from_f32([1, 2, h, w], &map)
361}
362
363pub fn undistort_points(
372 points: &Matrix,
373 camera: &Matrix,
374 distortion: &Matrix,
375 rectification: Option<&Matrix>,
376 projection: Option<&Matrix>,
377) -> Result<Matrix> {
378 let points = read_points2(points, 1, "undistort_points")?;
379 let k = read_mat3(camera, "undistort_points")?;
380 let distortion = read_vector_free(distortion, "undistort_points")?;
381 let kinv =
382 invert3(k).ok_or_else(|| Error::invalid_argument("undistort_points camera is singular"))?;
383 let rotation = match rectification {
384 Some(matrix) => read_mat3(matrix, "undistort_points")?,
385 None => IDENTITY3,
386 };
387 let mut output = Vec::with_capacity(points.len() * 2);
388 for &[u, v] in &points {
389 let mut x = kinv[0][0] * u + kinv[0][1] * v + kinv[0][2];
390 let mut y = kinv[1][0] * u + kinv[1][1] * v + kinv[1][2];
391 let w_hom = kinv[2][0] * u + kinv[2][1] * v + kinv[2][2];
392 if w_hom.abs() < 1e-12 {
393 return Err(Error::invalid_argument(
394 "undistort_points camera produced a point at infinity",
395 ));
396 }
397 x /= w_hom;
398 y /= w_hom;
399 let (x0, y0) = (x, y);
403 let (k1, k2t, p1, p2, k3) = distortion_terms(&distortion);
404 for _ in 0..8 {
405 let r2 = x * x + y * y;
406 let icd = 1.0 / (1.0 + k1 * r2 + k2t * r2 * r2 + k3 * r2 * r2 * r2);
407 let delta_x = 2.0 * p1 * x * y + p2 * (r2 + 2.0 * x * x);
408 let delta_y = p1 * (r2 + 2.0 * y * y) + 2.0 * p2 * x * y;
409 x = (x0 - delta_x) * icd;
410 y = (y0 - delta_y) * icd;
411 }
412 let rx = rotation[0][0] * x + rotation[0][1] * y + rotation[0][2];
413 let ry = rotation[1][0] * x + rotation[1][1] * y + rotation[1][2];
414 let rz = rotation[2][0] * x + rotation[2][1] * y + rotation[2][2];
415 let (mut ox, mut oy) = (rx, ry);
416 if let Some(projection_matrix) = projection {
417 let p = read_mat3(projection_matrix, "undistort_points")?;
418 if rz.abs() < 1e-12 {
419 return Err(Error::invalid_argument(
420 "undistort_points rectification produced a point at the plane",
421 ));
422 }
423 ox = p[0][0] * rx / rz + p[0][1] * ry / rz + p[0][2];
424 oy = p[1][0] * rx / rz + p[1][1] * ry / rz + p[1][2];
425 }
426 output.push(ox as f32);
427 output.push(oy as f32);
428 }
429 Matrix::new_from_f32([points.len(), 2], &output)
430}
431
432fn degenerate(operation: &str) -> Error {
433 Error::invalid_argument(format!("{operation} point set is degenerate"))
434}
435
436const IDENTITY3: [[f64; 3]; 3] = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
439
440fn read_points2(matrix: &Matrix, minimum: usize, operation: &str) -> Result<Vec<[f64; 2]>> {
441 let shape = matrix.shape();
442 if shape.len() != 2 || shape[1] != 2 || shape[0] < minimum {
443 return Err(Error::invalid_argument(format!(
444 "{operation} requires an [N, 2] matrix with N >= {minimum}"
445 )));
446 }
447 let values = matrix.read_f32()?;
448 Ok(
449 values
450 .as_chunks::<2>()
451 .0
452 .iter()
453 .map(|pair| [pair[0] as f64, pair[1] as f64])
454 .collect(),
455 )
456}
457
458fn read_points3(matrix: &Matrix, minimum: usize, operation: &str) -> Result<Vec<[f64; 3]>> {
459 let shape = matrix.shape();
460 if shape.len() != 2 || shape[1] != 3 || shape[0] < minimum {
461 return Err(Error::invalid_argument(format!(
462 "{operation} requires an [N, 3] matrix with N >= {minimum}"
463 )));
464 }
465 let values = matrix.read_f32()?;
466 Ok(
467 values
468 .as_chunks::<3>()
469 .0
470 .iter()
471 .map(|tri| [tri[0] as f64, tri[1] as f64, tri[2] as f64])
472 .collect(),
473 )
474}
475
476fn read_vector(matrix: &Matrix, expected: usize, operation: &str) -> Result<Vec<f64>> {
477 let values = matrix.read_f32()?;
478 if values.len() != expected {
479 return Err(Error::invalid_argument(format!(
480 "{operation} requires a length-{expected} vector"
481 )));
482 }
483 Ok(values.iter().map(|value| *value as f64).collect())
484}
485
486fn read_vector_free(matrix: &Matrix, operation: &str) -> Result<Vec<f64>> {
487 let shape = matrix.shape();
488 if shape.len() > 2 || (shape.len() == 2 && shape[0] != 1 && shape[1] != 1) {
489 return Err(Error::invalid_argument(format!(
490 "{operation} requires a vector-shaped distortion matrix"
491 )));
492 }
493 let values = matrix.read_f32()?;
494 Ok(values.iter().map(|value| *value as f64).collect())
495}
496
497fn read_mat3(matrix: &Matrix, operation: &str) -> Result<[[f64; 3]; 3]> {
498 if matrix.shape() != [3, 3].as_slice() {
499 return Err(Error::invalid_argument(format!(
500 "{operation} requires a [3, 3] matrix"
501 )));
502 }
503 let values = matrix.read_f32()?;
504 let mut out = [[0.0f64; 3]; 3];
505 for row in 0..3 {
506 for column in 0..3 {
507 out[row][column] = values[row * 3 + column] as f64;
508 }
509 }
510 Ok(out)
511}
512
513fn mat3_f32(m: [[f64; 3]; 3]) -> Result<Matrix> {
514 let mut values = [0.0f32; 9];
515 for row in 0..3 {
516 for column in 0..3 {
517 values[row * 3 + column] = m[row][column] as f32;
518 }
519 }
520 Matrix::new_from_f32([3, 3], &values)
521}
522
523fn vector_f32(values: &[f64]) -> Result<Matrix> {
524 let flat: Vec<f32> = values.iter().map(|value| *value as f32).collect();
525 Matrix::new_from_f32([values.len(), 1], &flat)
526}
527
528fn ones_mask(n: usize) -> Result<Matrix> {
529 Matrix::new_from_f32([n, 1], &vec![1.0f32; n])
530}
531
532fn index_mask(n: usize, indices: &[usize]) -> Result<Matrix> {
533 let mut mask = vec![0.0f32; n];
534 for &index in indices {
535 mask[index] = 1.0;
536 }
537 Matrix::new_from_f32([n, 1], &mask)
538}
539
540fn inlier_indices(n: usize, predicate: impl Fn(usize) -> bool) -> Vec<usize> {
541 (0..n).filter(|&index| predicate(index)).collect()
542}
543
544fn invert3(m: [[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> {
547 let det = m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
548 - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
549 + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]);
550 if det.abs() < 1e-14 {
551 return None;
552 }
553 let inv = 1.0 / det;
554 Some([
555 [
556 (m[1][1] * m[2][2] - m[1][2] * m[2][1]) * inv,
557 (m[0][2] * m[2][1] - m[0][1] * m[2][2]) * inv,
558 (m[0][1] * m[1][2] - m[0][2] * m[1][1]) * inv,
559 ],
560 [
561 (m[1][2] * m[2][0] - m[1][0] * m[2][2]) * inv,
562 (m[0][0] * m[2][2] - m[0][2] * m[2][0]) * inv,
563 (m[0][2] * m[1][0] - m[0][0] * m[1][2]) * inv,
564 ],
565 [
566 (m[1][0] * m[2][1] - m[1][1] * m[2][0]) * inv,
567 (m[0][1] * m[2][0] - m[0][0] * m[2][1]) * inv,
568 (m[0][0] * m[1][1] - m[0][1] * m[1][0]) * inv,
569 ],
570 ])
571}
572
573fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
574 [
575 a[1] * b[2] - a[2] * b[1],
576 a[2] * b[0] - a[0] * b[2],
577 a[0] * b[1] - a[1] * b[0],
578 ]
579}
580
581fn norm(a: [f64; 3]) -> f64 {
582 (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]).sqrt()
583}
584
585fn normalize_vec(a: [f64; 3]) -> [f64; 3] {
586 let n = norm(a);
587 if n < 1e-14 {
588 return a;
589 }
590 [a[0] / n, a[1] / n, a[2] / n]
591}
592
593fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
594 a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
595}
596
597fn mul_mat3(a: &[[f64; 3]; 3], b: &[[f64; 3]; 3]) -> [[f64; 3]; 3] {
598 let mut out = [[0.0f64; 3]; 3];
599 for i in 0..3 {
600 for j in 0..3 {
601 out[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j];
602 }
603 }
604 out
605}
606
607fn transpose3(m: [[f64; 3]; 3]) -> [[f64; 3]; 3] {
608 [
609 [m[0][0], m[1][0], m[2][0]],
610 [m[0][1], m[1][1], m[2][1]],
611 [m[0][2], m[1][2], m[2][2]],
612 ]
613}
614
615#[allow(clippy::type_complexity)]
618fn svd3(m: [[f64; 3]; 3]) -> Option<([[f64; 3]; 3], [f64; 3], [[f64; 3]; 3])> {
619 let mt = transpose3(m);
620 let mtm = mul_mat3(&mt, &m);
621 let mmt = mul_mat3(&m, &mt);
622 let (vvals, vvec) = jacobi_eigen(&mtm, 3)?;
623 let (uvals, uvec) = jacobi_eigen(&mmt, 3)?;
624 let mut s = [0.0f64; 3];
625 let mut v = [[0.0f64; 3]; 3];
626 let mut u = [[0.0f64; 3]; 3];
627 for column in 0..3 {
628 s[column] = vvals[2 - column].max(0.0).sqrt();
629 for row in 0..3 {
630 v[row][column] = vvec[row][2 - column];
631 u[row][column] = uvec[row][2 - column];
632 }
633 }
634 let _ = uvals;
635 for column in 0..3 {
637 if s[column] > 1e-10 {
638 for row in 0..3 {
639 u[row][column] =
640 (m[row][0] * v[0][column] + m[row][1] * v[1][column] + m[row][2] * v[2][column])
641 / s[column];
642 }
643 }
644 }
645 for column in 0..3 {
647 let column_vec = [u[0][column], u[1][column], u[2][column]];
648 if norm(column_vec) < 0.5 {
649 let others: Vec<[f64; 3]> = (0..3)
650 .filter(|&c| c != column)
651 .map(|c| [u[0][c], u[1][c], u[2][c]])
652 .collect();
653 let candidate = normalize_vec(cross(others[0], others[1]));
654 for (row, ur) in u.iter_mut().enumerate() {
655 ur[column] = candidate[row];
656 }
657 }
658 }
659 if det3(&v) < 0.0 {
661 for r in v.iter_mut() {
662 r[2] = -r[2];
663 }
664 }
665 if det3(&u) < 0.0 {
666 for r in u.iter_mut() {
667 r[2] = -r[2];
668 }
669 }
670 Some((u, s, transpose3(v)))
671}
672
673fn det3(m: &[[f64; 3]; 3]) -> f64 {
674 m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
675 - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
676 + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
677}
678
679fn dlt_homography(source: &[[f64; 2]], destination: &[[f64; 2]]) -> Option<[[f64; 3]; 3]> {
683 let (ts, ns) = normalize2d(source)?;
684 let (td, nd) = normalize2d(destination)?;
685 let n = ns.len();
686 let mut a = vec![0.0f64; 2 * n * 9];
687 for (index, (&[x, y], &[u, v])) in ns.iter().zip(nd.iter()).enumerate() {
688 let row = 2 * index * 9;
689 a[row..row + 9].copy_from_slice(&[x, y, 1.0, 0.0, 0.0, 0.0, -u * x, -u * y, -u]);
690 a[row + 9..row + 18].copy_from_slice(&[0.0, 0.0, 0.0, x, y, 1.0, -v * x, -v * y, -v]);
691 }
692 let vectors = smallest_right_singular::<9>(&a, 2 * n)?;
693 let mut h = [[0.0f64; 3]; 3];
694 for row in 0..3 {
695 for column in 0..3 {
696 h[row][column] = vectors[row * 3 + column][0];
697 }
698 }
699 let td_inv = invert3(td)?;
701 let ts_mul = mul_mat3(&h, &ts);
702 let full = mul_mat3(&td_inv, &ts_mul);
703 let scale = full[2][2];
704 if scale.abs() < 1e-14 {
705 return None;
706 }
707 let mut out = [[0.0f64; 3]; 3];
708 for row in 0..3 {
709 for column in 0..3 {
710 out[row][column] = full[row][column] / scale;
711 }
712 }
713 Some(out)
714}
715
716#[allow(clippy::type_complexity)]
718fn normalize2d(points: &[[f64; 2]]) -> Option<([[f64; 3]; 3], Vec<[f64; 2]>)> {
719 let n = points.len() as f64;
720 if n < 1.0 {
721 return None;
722 }
723 let (mut cx, mut cy) = (0.0, 0.0);
724 for &[x, y] in points {
725 cx += x;
726 cy += y;
727 }
728 cx /= n;
729 cy /= n;
730 let mut scale = 0.0;
731 for &[x, y] in points {
732 scale += ((x - cx) * (x - cx) + (y - cy) * (y - cy)).sqrt();
733 }
734 scale /= n;
735 if scale < 1e-14 {
736 scale = 1.0;
737 }
738 let s = 1.0 / scale;
739 let transform = [[s, 0.0, -s * cx], [0.0, s, -s * cy], [0.0, 0.0, 1.0]];
740 let normalized = points
741 .iter()
742 .map(|&[x, y]| [(x - cx) * s, (y - cy) * s])
743 .collect();
744 Some((transform, normalized))
745}
746
747fn homography_error(h: &[[f64; 3]; 3], source: &[f64; 2], destination: &[f64; 2]) -> f64 {
749 let forward = match project_h(h, source) {
750 Some([x, y]) => (x - destination[0]).powi(2) + (y - destination[1]).powi(2),
751 None => return f64::MAX,
752 };
753 let backward = match invert3(*h).and_then(|hinv| project_h(&hinv, destination)) {
754 Some([x, y]) => (x - source[0]).powi(2) + (y - source[1]).powi(2),
755 None => return f64::MAX,
756 };
757 forward + backward
758}
759
760fn project_h(h: &[[f64; 3]; 3], p: &[f64; 2]) -> Option<[f64; 2]> {
762 let x = h[0][0] * p[0] + h[0][1] * p[1] + h[0][2];
763 let y = h[1][0] * p[0] + h[1][1] * p[1] + h[1][2];
764 let w = h[2][0] * p[0] + h[2][1] * p[1] + h[2][2];
765 if w.abs() < 1e-14 {
766 return None;
767 }
768 Some([x / w, y / w])
769}
770
771struct Pcg32 {
776 state: u64,
777}
778
779impl Pcg32 {
780 fn new(seed: u64) -> Self {
781 let mut rng = Self { state: 0 };
782 rng.next_u32();
783 rng.state = rng.state.wrapping_add(seed);
784 rng.next_u32();
785 rng
786 }
787
788 fn next_u32(&mut self) -> u32 {
789 let old = self.state;
790 self.state = old.wrapping_mul(6364136223846793005).wrapping_add(3);
791 let shifted = (((old >> 18) ^ old) >> 27) as u32;
792 shifted.rotate_right((old >> 59) as u32)
793 }
794
795 fn next_u64(&mut self) -> u64 {
796 (u64::from(self.next_u32()) << 32) | u64::from(self.next_u32())
797 }
798}
799
800fn ransac_consensus(
804 sample_size: usize,
805 n: usize,
806 iterations: usize,
807 seed: u64,
808 mut estimate: impl FnMut(&[usize]) -> Option<Vec<usize>>,
809) -> Option<Vec<usize>> {
810 if n < sample_size {
811 return None;
812 }
813 let mut rng = Pcg32::new(seed);
814 let mut best: Vec<usize> = Vec::new();
815 for _ in 0..iterations {
816 let mut sample: Vec<usize> = (0..n).collect();
817 for count in (2..=n).rev() {
818 if count <= n - sample_size {
819 break;
820 }
821 let range = count as u64;
822 let reject = range.wrapping_neg() % range;
823 let value = loop {
824 let value = rng.next_u64();
825 if value >= reject {
826 break value;
827 }
828 };
829 sample.swap(count - 1, (value % range) as usize);
830 }
831 let sample = &sample[n - sample_size..];
832 if let Some(inliers) = estimate(sample).filter(|i| i.len() > best.len()) {
833 best = inliers;
834 }
835 }
836 if best.is_empty() { None } else { Some(best) }
837}
838
839fn camera_project(rotation: &[[f64; 3]; 3], t: &[f64; 3], point: &[f64; 3]) -> [f64; 3] {
843 [
844 rotation[0][0] * point[0] + rotation[0][1] * point[1] + rotation[0][2] * point[2] + t[0],
845 rotation[1][0] * point[0] + rotation[1][1] * point[1] + rotation[1][2] * point[2] + t[1],
846 rotation[2][0] * point[0] + rotation[2][1] * point[1] + rotation[2][2] * point[2] + t[2],
847 ]
848}
849
850fn reprojection_error(
852 pose: &([[f64; 3]; 3], [f64; 3]),
853 camera: &[[f64; 3]; 3],
854 object: &[f64; 3],
855 image: &[f64; 2],
856) -> f64 {
857 let [x, y, z] = camera_project(&pose.0, &pose.1, object);
858 if z.abs() < 1e-12 {
859 return f64::MAX;
860 }
861 let u = (camera[0][0] * x + camera[0][1] * y + camera[0][2] * z) / z;
862 let v = (camera[1][0] * x + camera[1][1] * y + camera[1][2] * z) / z;
863 let du = u - image[0];
864 let dv = v - image[1];
865 du * du + dv * dv
866}
867
868fn rodrigues_matrix(r: &[f64; 3]) -> [[f64; 3]; 3] {
870 let theta = norm(*r);
871 if theta < 1e-12 {
872 return IDENTITY3;
873 }
874 let k = [r[0] / theta, r[1] / theta, r[2] / theta];
875 let (c, s) = (theta.cos(), theta.sin());
876 let outer = |i: usize, j: usize| k[i] * k[j] * (1.0 - c);
877 let skew = [
878 [0.0, -k[2] * s, k[1] * s],
879 [k[2] * s, 0.0, -k[0] * s],
880 [-k[1] * s, k[0] * s, 0.0],
881 ];
882 let mut out = [[0.0f64; 3]; 3];
883 for i in 0..3 {
884 for j in 0..3 {
885 out[i][j] = (if i == j { c } else { 0.0 }) + outer(i, j) + skew[i][j];
886 }
887 }
888 out
889}
890
891fn rodrigues_vector(rotation: &[[f64; 3]; 3]) -> [f64; 3] {
893 let trace = rotation[0][0] + rotation[1][1] + rotation[2][2];
894 let cosine = ((trace - 1.0) / 2.0).clamp(-1.0, 1.0);
895 let theta = cosine.acos();
896 if theta < 1e-8 {
897 return [0.0, 0.0, 0.0];
898 }
899 let denominator = 2.0 * theta.sin();
900 if denominator.abs() < 1e-8 {
901 let mut axis = [
903 ((rotation[0][0] + 1.0) / 2.0).max(0.0).sqrt(),
904 ((rotation[1][1] + 1.0) / 2.0).max(0.0).sqrt(),
905 ((rotation[2][2] + 1.0) / 2.0).max(0.0).sqrt(),
906 ];
907 if rotation[0][1] < 0.0 {
908 axis[1] = -axis[1];
909 }
910 if rotation[0][2] < 0.0 {
911 axis[2] = -axis[2];
912 }
913 return normalize_vec(axis).map(|v| v * theta);
914 }
915 let scale = theta / denominator;
916 [
917 (rotation[2][1] - rotation[1][2]) * scale,
918 (rotation[0][2] - rotation[2][0]) * scale,
919 (rotation[1][0] - rotation[0][1]) * scale,
920 ]
921}
922
923fn dlt_pose(
926 object: &[[f64; 3]],
927 image: &[[f64; 2]],
928 camera: &[[f64; 3]; 3],
929) -> Option<([[f64; 3]; 3], [f64; 3])> {
930 let kinv = invert3(*camera)?;
931 let normalized: Vec<[f64; 2]> = image
932 .iter()
933 .map(|&[u, v]| {
934 let x = kinv[0][0] * u + kinv[0][1] * v + kinv[0][2];
935 let y = kinv[1][0] * u + kinv[1][1] * v + kinv[1][2];
936 let w = kinv[2][0] * u + kinv[2][1] * v + kinv[2][2];
937 [x / w, y / w]
938 })
939 .collect();
940 let n = object.len();
941 let mut a = vec![0.0f64; 2 * n * 12];
942 for (index, (&point, &[xn, yn])) in object.iter().zip(normalized.iter()).enumerate() {
943 let [x, y, z] = point;
944 let row = 2 * index * 12;
945 a[row..row + 12].copy_from_slice(&[
946 x,
947 y,
948 z,
949 1.0,
950 0.0,
951 0.0,
952 0.0,
953 0.0,
954 -xn * x,
955 -xn * y,
956 -xn * z,
957 -xn,
958 ]);
959 a[row + 12..row + 24].copy_from_slice(&[
960 0.0,
961 0.0,
962 0.0,
963 0.0,
964 x,
965 y,
966 z,
967 1.0,
968 -yn * x,
969 -yn * y,
970 -yn * z,
971 -yn,
972 ]);
973 }
974 let vectors = smallest_right_singular::<12>(&a, 2 * n)?;
975 let mut rotation = [[0.0f64; 3]; 3];
976 let mut translation = [0.0f64; 3];
977 for row in 0..3 {
978 for column in 0..3 {
979 rotation[row][column] = vectors[row * 4 + column][0];
980 }
981 translation[row] = vectors[row * 4 + 3][0];
982 }
983 let (mut u, _, vt) = svd3(rotation)?;
985 let mut proper = mul_mat3(&u, &vt);
986 if det3(&proper) < 0.0 {
987 for r in u.iter_mut() {
988 r[2] = -r[2];
989 }
990 proper = mul_mat3(&u, &vt);
991 }
992 let scale = norm([proper[0][0], proper[0][1], proper[0][2]]);
993 let _ = scale;
994 let column_norms: Vec<f64> = (0..3)
996 .map(|c| norm([rotation[0][c], rotation[1][c], rotation[2][c]]))
997 .collect();
998 let mean = (column_norms[0] + column_norms[1] + column_norms[2]) / 3.0;
999 if mean < 1e-14 {
1000 return None;
1001 }
1002 let factor = 1.0 / mean;
1003 for t in translation.iter_mut() {
1004 *t *= factor;
1005 }
1006 let mut depth = 0.0;
1008 for &point in object {
1009 let p = camera_project(&proper, &translation, &point);
1010 depth += p[2];
1011 }
1012 if depth < 0.0 {
1013 for (r, t) in proper.iter_mut().zip(translation.iter_mut()) {
1014 for c in r.iter_mut() {
1015 *c = -*c;
1016 }
1017 *t = -*t;
1018 }
1019 }
1020 Some((proper, translation))
1021}
1022
1023fn refine_pose(
1025 object: &[[f64; 3]],
1026 image: &[[f64; 2]],
1027 camera: &[[f64; 3]; 3],
1028 pose: ([[f64; 3]; 3], [f64; 3]),
1029) -> Option<([[f64; 3]; 3], [f64; 3])> {
1030 let mut params = {
1031 let r = rodrigues_vector(&pose.0);
1032 [r[0], r[1], r[2], pose.1[0], pose.1[1], pose.1[2]]
1033 };
1034 let residuals = |params: &[f64]| -> Vec<f64> {
1035 let rotation = rodrigues_matrix(&[params[0], params[1], params[2]]);
1036 let t = [params[3], params[4], params[5]];
1037 let mut out = Vec::with_capacity(object.len() * 2);
1038 for (point, &target) in object.iter().zip(image.iter()) {
1039 let [x, y, z] = camera_project(&rotation, &[t[0], t[1], t[2]], point);
1040 let (u, v) = if z.abs() < 1e-9 {
1041 (f64::MAX * 1e-6, f64::MAX * 1e-6)
1042 } else {
1043 (
1044 (camera[0][0] * x + camera[0][1] * y + camera[0][2] * z) / z,
1045 (camera[1][0] * x + camera[1][1] * y + camera[1][2] * z) / z,
1046 )
1047 };
1048 out.push(u - target[0]);
1049 out.push(v - target[1]);
1050 }
1051 out
1052 };
1053 let n = params.len();
1054 let mut cost: f64 = residuals(¶ms).iter().map(|r| r * r).sum();
1055 for _ in 0..20 {
1056 let r = residuals(¶ms);
1057 let mut jacobian = vec![0.0f64; r.len() * n];
1058 let eps = 1e-6;
1059 for column in 0..n {
1060 let mut shifted = params;
1061 shifted[column] += eps;
1062 let shifted_residuals = residuals(&shifted);
1063 for (row, value) in shifted_residuals.iter().enumerate() {
1064 jacobian[row * n + column] = (value - r[row]) / eps;
1065 }
1066 }
1067 let step = damped_least_squares(&jacobian, &r, r.len(), n, 1e-3)?;
1068 let mut improved = false;
1069 for scale in [1.0, 0.5, 0.25] {
1070 let mut candidate = params;
1071 for i in 0..n {
1072 candidate[i] += step[i] * scale;
1073 }
1074 let candidate_cost: f64 = residuals(&candidate).iter().map(|r| r * r).sum();
1075 if candidate_cost < cost {
1076 params = candidate;
1077 cost = candidate_cost;
1078 improved = true;
1079 break;
1080 }
1081 }
1082 if !improved {
1083 break;
1084 }
1085 }
1086 Some((
1087 rodrigues_matrix(&[params[0], params[1], params[2]]),
1088 [params[3], params[4], params[5]],
1089 ))
1090}
1091
1092fn distortion_terms(distortion: &[f64]) -> (f64, f64, f64, f64, f64) {
1096 let term = |index: usize| distortion.get(index).copied().unwrap_or(0.0);
1097 (term(0), term(1), term(2), term(3), term(4))
1098}
1099
1100fn distort_normalized(x: f64, y: f64, distortion: &[f64]) -> (f64, f64) {
1104 let (k1, k2, p1, p2, k3) = distortion_terms(distortion);
1105 let r2 = x * x + y * y;
1106 let radial = if distortion.len() >= 8 {
1107 let (k4, k5, k6) = (
1108 distortion.get(5).copied().unwrap_or(0.0),
1109 distortion.get(6).copied().unwrap_or(0.0),
1110 distortion.get(7).copied().unwrap_or(0.0),
1111 );
1112 (1.0 + k1 * r2 + k2 * r2 * r2 + k3 * r2 * r2 * r2)
1113 / (1.0 + k4 * r2 + k5 * r2 * r2 + k6 * r2 * r2 * r2)
1114 } else {
1115 1.0 + k1 * r2 + k2 * r2 * r2 + k3 * r2 * r2 * r2
1116 };
1117 let dx = 2.0 * p1 * x * y + p2 * (r2 + 2.0 * x * x);
1118 let dy = p1 * (r2 + 2.0 * y * y) + 2.0 * p2 * x * y;
1119 (x * radial + dx, y * radial + dy)
1120}
1121
1122pub fn find_fundamental(
1136 points1: &Matrix,
1137 points2: &Matrix,
1138 method: EstimationMethod,
1139 ransac_threshold: f32,
1140 max_iterations: i32,
1141 seed: u64,
1142) -> Result<EpipolarResult> {
1143 let points1 = read_points2(points1, 8, "find_fundamental")?;
1144 let points2 = read_points2(points2, 8, "find_fundamental")?;
1145 if points1.len() != points2.len() {
1146 return Err(Error::invalid_argument(
1147 "find_fundamental inputs must share point count",
1148 ));
1149 }
1150 match method {
1151 EstimationMethod::LeastSquares => {
1152 let f = eight_point(&points1, &points2).ok_or_else(|| degenerate("find_fundamental"))?;
1153 Ok(EpipolarResult {
1154 matrix: mat3_f32(f)?,
1155 mask: ones_mask(points1.len())?,
1156 })
1157 }
1158 EstimationMethod::Ransac => {
1159 if !ransac_threshold.is_finite() || ransac_threshold <= 0.0 {
1160 return Err(Error::invalid_argument(
1161 "find_fundamental ransac_threshold must be positive and finite",
1162 ));
1163 }
1164 if max_iterations < 1 {
1165 return Err(Error::invalid_argument(
1166 "find_fundamental max_iterations must be positive",
1167 ));
1168 }
1169 let n = points1.len();
1170 let threshold = ransac_threshold as f64;
1171 let inliers = ransac_consensus(8, n, max_iterations as usize, seed, |sample| {
1172 let p1: Vec<[f64; 2]> = sample.iter().map(|i| points1[*i]).collect();
1173 let p2: Vec<[f64; 2]> = sample.iter().map(|i| points2[*i]).collect();
1174 eight_point(&p1, &p2).map(|f| {
1175 inlier_indices(n, |i| {
1176 epipolar_error(&f, &points1[i], &points2[i]) <= threshold
1177 })
1178 })
1179 })
1180 .ok_or_else(|| degenerate("find_fundamental"))?;
1181 let p1: Vec<[f64; 2]> = inliers.iter().map(|i| points1[*i]).collect();
1182 let p2: Vec<[f64; 2]> = inliers.iter().map(|i| points2[*i]).collect();
1183 let f = eight_point(&p1, &p2).ok_or_else(|| degenerate("find_fundamental"))?;
1184 Ok(EpipolarResult {
1185 matrix: mat3_f32(f)?,
1186 mask: index_mask(n, &inliers)?,
1187 })
1188 }
1189 }
1190}
1191
1192pub fn find_essential(
1203 points1: &Matrix,
1204 points2: &Matrix,
1205 camera: &Matrix,
1206 method: EstimationMethod,
1207 ransac_threshold: f32,
1208 max_iterations: i32,
1209 seed: u64,
1210) -> Result<EpipolarResult> {
1211 let k = read_mat3(camera, "find_essential")?;
1212 let kinv =
1213 invert3(k).ok_or_else(|| Error::invalid_argument("find_essential camera is singular"))?;
1214 let normalize = |matrix: &Matrix, op: &str| -> Result<Vec<[f64; 2]>> {
1215 let points = read_points2(matrix, 8, op)?;
1216 Ok(
1217 points
1218 .iter()
1219 .map(|&[u, v]| {
1220 let x = kinv[0][0] * u + kinv[0][1] * v + kinv[0][2];
1221 let y = kinv[1][0] * u + kinv[1][1] * v + kinv[1][2];
1222 let w = kinv[2][0] * u + kinv[2][1] * v + kinv[2][2];
1223 [x / w, y / w]
1224 })
1225 .collect(),
1226 )
1227 };
1228 let points1 = normalize(points1, "find_essential")?;
1229 let points2 = normalize(points2, "find_essential")?;
1230 if points1.len() != points2.len() {
1231 return Err(Error::invalid_argument(
1232 "find_essential inputs must share point count",
1233 ));
1234 }
1235 match method {
1237 EstimationMethod::LeastSquares => {
1238 let e = eight_point(&points1, &points2)
1239 .and_then(essential_enforce)
1240 .ok_or_else(|| degenerate("find_essential"))?;
1241 Ok(EpipolarResult {
1242 matrix: mat3_f32(e)?,
1243 mask: ones_mask(points1.len())?,
1244 })
1245 }
1246 EstimationMethod::Ransac => {
1247 if !ransac_threshold.is_finite() || ransac_threshold <= 0.0 {
1248 return Err(Error::invalid_argument(
1249 "find_essential ransac_threshold must be positive and finite",
1250 ));
1251 }
1252 if max_iterations < 1 {
1253 return Err(Error::invalid_argument(
1254 "find_essential max_iterations must be positive",
1255 ));
1256 }
1257 let n = points1.len();
1258 let threshold = ransac_threshold as f64;
1259 let inliers = ransac_consensus(8, n, max_iterations as usize, seed, |sample| {
1260 let p1: Vec<[f64; 2]> = sample.iter().map(|i| points1[*i]).collect();
1261 let p2: Vec<[f64; 2]> = sample.iter().map(|i| points2[*i]).collect();
1262 eight_point(&p1, &p2).and_then(essential_enforce).map(|e| {
1263 inlier_indices(n, |i| {
1264 epipolar_error(&e, &points1[i], &points2[i]) <= threshold
1265 })
1266 })
1267 })
1268 .ok_or_else(|| degenerate("find_essential"))?;
1269 let p1: Vec<[f64; 2]> = inliers.iter().map(|i| points1[*i]).collect();
1270 let p2: Vec<[f64; 2]> = inliers.iter().map(|i| points2[*i]).collect();
1271 let e = eight_point(&p1, &p2)
1272 .and_then(essential_enforce)
1273 .ok_or_else(|| degenerate("find_essential"))?;
1274 Ok(EpipolarResult {
1275 matrix: mat3_f32(e)?,
1276 mask: index_mask(n, &inliers)?,
1277 })
1278 }
1279 }
1280}
1281
1282#[allow(clippy::type_complexity)]
1293pub fn recover_pose(
1294 essential: &Matrix,
1295 points1: &Matrix,
1296 points2: &Matrix,
1297 camera: &Matrix,
1298) -> Result<RecoverPoseResult> {
1299 let e = read_mat3(essential, "recover_pose")?;
1300 let k = read_mat3(camera, "recover_pose")?;
1301 let kinv =
1302 invert3(k).ok_or_else(|| Error::invalid_argument("recover_pose camera is singular"))?;
1303 let points1 = read_points2(points1, 1, "recover_pose")?;
1304 let points2 = read_points2(points2, 1, "recover_pose")?;
1305 if points1.len() != points2.len() {
1306 return Err(Error::invalid_argument(
1307 "recover_pose inputs must share point count",
1308 ));
1309 }
1310 let n = points1.len();
1311 let normalized = |points: &[[f64; 2]]| -> Vec<[f64; 2]> {
1312 points
1313 .iter()
1314 .map(|&[u, v]| {
1315 let x = kinv[0][0] * u + kinv[0][1] * v + kinv[0][2];
1316 let y = kinv[1][0] * u + kinv[1][1] * v + kinv[1][2];
1317 let w = kinv[2][0] * u + kinv[2][1] * v + kinv[2][2];
1318 [x / w, y / w]
1319 })
1320 .collect()
1321 };
1322 let pn1 = normalized(&points1);
1323 let pn2 = normalized(&points2);
1324 let (u, _, vt) = svd3(e).ok_or_else(|| degenerate("recover_pose"))?;
1325 let w = [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]];
1326 let wt = transpose3(w);
1327 let mut u_adj = u;
1328 if det3(&u_adj) < 0.0 {
1329 for r in u_adj.iter_mut() {
1330 r[2] = -r[2];
1331 }
1332 }
1333 let mut v_adj = transpose3(vt);
1334 if det3(&v_adj) < 0.0 {
1335 for r in v_adj.iter_mut() {
1336 r[2] = -r[2];
1337 }
1338 }
1339 let r1 = mul_mat3(&mul_mat3(&u_adj, &w), &transpose3(v_adj));
1340 let r2 = mul_mat3(&mul_mat3(&u_adj, &wt), &transpose3(v_adj));
1341 let t_pos = [u_adj[0][2], u_adj[1][2], u_adj[2][2]];
1342 let t_neg = [-t_pos[0], -t_pos[1], -t_pos[2]];
1343 let p1: [[f64; 4]; 3] = [
1344 [1.0, 0.0, 0.0, 0.0],
1345 [0.0, 1.0, 0.0, 0.0],
1346 [0.0, 0.0, 1.0, 0.0],
1347 ];
1348 let mut best: Option<([[f64; 3]; 3], [f64; 3], Vec<usize>)> = None;
1349 for (rotation, t) in [(r1, t_pos), (r1, t_neg), (r2, t_pos), (r2, t_neg)] {
1350 let p2: [[f64; 4]; 3] = [
1351 [rotation[0][0], rotation[0][1], rotation[0][2], t[0]],
1352 [rotation[1][0], rotation[1][1], rotation[1][2], t[1]],
1353 [rotation[2][0], rotation[2][1], rotation[2][2], t[2]],
1354 ];
1355 let mut in_front = Vec::new();
1356 for index in 0..n {
1357 if let Some([x, y, z, w]) = triangulate_point(&p1, &p2, &pn1[index], &pn2[index]) {
1358 if w.abs() < 1e-14 {
1359 continue;
1360 }
1361 let point = [x / w, y / w, z / w];
1362 let depth2 =
1363 rotation[2][0] * point[0] + rotation[2][1] * point[1] + rotation[2][2] * point[2] + t[2];
1364 if point[2] > 0.0 && depth2 > 0.0 {
1365 in_front.push(index);
1366 }
1367 }
1368 }
1369 if best
1370 .as_ref()
1371 .is_none_or(|(_, _, best)| in_front.len() > best.len())
1372 {
1373 best = Some((rotation, t, in_front));
1374 }
1375 }
1376 let (rotation, translation, in_front) = best.ok_or_else(|| degenerate("recover_pose"))?;
1377 if in_front.is_empty() {
1378 return Err(degenerate("recover_pose"));
1379 }
1380 Ok(RecoverPoseResult {
1381 rotation: mat3_f32(rotation)?,
1382 translation: vector_f32(&translation)?,
1383 mask: index_mask(n, &in_front)?,
1384 })
1385}
1386
1387pub fn triangulate_points(
1395 projection1: &Matrix,
1396 projection2: &Matrix,
1397 points1: &Matrix,
1398 points2: &Matrix,
1399) -> Result<Matrix> {
1400 let p1 = read_mat34(projection1, "triangulate_points")?;
1401 let p2 = read_mat34(projection2, "triangulate_points")?;
1402 let points1 = read_points2(points1, 1, "triangulate_points")?;
1403 let points2 = read_points2(points2, 1, "triangulate_points")?;
1404 if points1.len() != points2.len() {
1405 return Err(Error::invalid_argument(
1406 "triangulate_points inputs must share point count",
1407 ));
1408 }
1409 let mut output = Vec::with_capacity(points1.len() * 4);
1410 for index in 0..points1.len() {
1411 let point = triangulate_point(&p1, &p2, &points1[index], &points2[index])
1412 .ok_or_else(|| degenerate("triangulate_points"))?;
1413 output.extend(point.iter().map(|v| *v as f32));
1414 }
1415 Matrix::new_from_f32([points1.len(), 4], &output)
1416}
1417
1418fn read_mat34(matrix: &Matrix, operation: &str) -> Result<[[f64; 4]; 3]> {
1419 if matrix.shape() != [3, 4].as_slice() {
1420 return Err(Error::invalid_argument(format!(
1421 "{operation} requires a [3, 4] projection matrix"
1422 )));
1423 }
1424 let values = matrix.read_f32()?;
1425 let mut out = [[0.0f64; 4]; 3];
1426 for row in 0..3 {
1427 for column in 0..4 {
1428 out[row][column] = values[row * 4 + column] as f64;
1429 }
1430 }
1431 Ok(out)
1432}
1433
1434fn triangulate_point(
1436 p1: &[[f64; 4]; 3],
1437 p2: &[[f64; 4]; 3],
1438 point1: &[f64; 2],
1439 point2: &[f64; 2],
1440) -> Option<[f64; 4]> {
1441 let mut a = [0.0f64; 4 * 4];
1442 for column in 0..4 {
1443 a[column] = point1[0] * p1[2][column] - p1[0][column];
1444 a[4 + column] = point1[1] * p1[2][column] - p1[1][column];
1445 a[8 + column] = point2[0] * p2[2][column] - p2[0][column];
1446 a[12 + column] = point2[1] * p2[2][column] - p2[1][column];
1447 }
1448 let vectors = smallest_right_singular::<4>(&a, 4)?;
1449 Some([vectors[0][0], vectors[1][0], vectors[2][0], vectors[3][0]])
1450}
1451
1452fn eight_point(points1: &[[f64; 2]], points2: &[[f64; 2]]) -> Option<[[f64; 3]; 3]> {
1454 let (t1, n1) = normalize2d(points1)?;
1455 let (t2, n2) = normalize2d(points2)?;
1456 let n = n1.len();
1457 let mut a = vec![0.0f64; n * 9];
1458 for (index, (&[x, y], &[u, v])) in n1.iter().zip(n2.iter()).enumerate() {
1459 let row = index * 9;
1460 a[row..row + 9].copy_from_slice(&[u * x, u * y, u, v * x, v * y, v, x, y, 1.0]);
1461 }
1462 let vectors = smallest_right_singular::<9>(&a, n)?;
1463 let mut f = [[0.0f64; 3]; 3];
1464 for row in 0..3 {
1465 for column in 0..3 {
1466 f[row][column] = vectors[row * 3 + column][0];
1467 }
1468 }
1469 let (u, s, vt) = svd3(f)?;
1471 let mut f_rank2 = [[0.0f64; 3]; 3];
1472 for i in 0..3 {
1473 for j in 0..3 {
1474 f_rank2[i][j] = s[0] * u[i][0] * vt[0][j] + s[1] * u[i][1] * vt[1][j];
1475 }
1476 }
1477 let t2t = transpose3(t2);
1479 Some(mul_mat3(&t2t, &mul_mat3(&f_rank2, &t1)))
1480}
1481
1482fn essential_enforce(e: [[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> {
1484 let (u, s, vt) = svd3(e)?;
1485 let mean = (s[0] + s[1]) / 2.0;
1486 let mut out = [[0.0f64; 3]; 3];
1487 for i in 0..3 {
1488 for j in 0..3 {
1489 out[i][j] = mean * (u[i][0] * vt[0][j] + u[i][1] * vt[1][j]);
1490 }
1491 }
1492 Some(out)
1493}
1494
1495fn epipolar_error(f: &[[f64; 3]; 3], p1: &[f64; 2], p2: &[f64; 2]) -> f64 {
1497 let x = [p1[0], p1[1], 1.0];
1498 let xp = [p2[0], p2[1], 1.0];
1499 let fx = [
1500 dot([f[0][0], f[0][1], f[0][2]], x),
1501 dot([f[1][0], f[1][1], f[1][2]], x),
1502 dot([f[2][0], f[2][1], f[2][2]], x),
1503 ];
1504 let ftx = [
1505 dot([f[0][0], f[1][0], f[2][0]], xp),
1506 dot([f[0][1], f[1][1], f[2][1]], xp),
1507 dot([f[0][2], f[1][2], f[2][2]], xp),
1508 ];
1509 let residual = dot(xp, fx);
1510 let denom1 = fx[0] * fx[0] + fx[1] * fx[1];
1511 let denom2 = ftx[0] * ftx[0] + ftx[1] * ftx[1];
1512 if denom1 < 1e-24 || denom2 < 1e-24 {
1513 return f64::MAX;
1514 }
1515 residual * residual * (1.0 / denom1 + 1.0 / denom2)
1516}
1517
1518pub fn calibrate_camera(
1534 object: &Matrix,
1535 image: &Matrix,
1536 refine_iterations: i32,
1537) -> Result<CalibrateCameraResult> {
1538 let oshape = object.shape();
1539 let ishape = image.shape();
1540 if oshape.len() != 3 || oshape[2] != 3 {
1541 return Err(Error::invalid_argument(
1542 "calibrate_camera requires object [V, N, 3]",
1543 ));
1544 }
1545 if ishape.len() != 3 || ishape[2] != 2 || ishape[0] != oshape[0] || ishape[1] != oshape[1] {
1546 return Err(Error::invalid_argument(
1547 "calibrate_camera requires image [V, N, 2] matching object",
1548 ));
1549 }
1550 let (views, n) = (oshape[0], oshape[1]);
1551 if views < 3 {
1552 return Err(Error::invalid_argument(
1553 "calibrate_camera requires V >= 3 views",
1554 ));
1555 }
1556 if n < 4 {
1557 return Err(Error::invalid_argument(
1558 "calibrate_camera requires N >= 4 points per view",
1559 ));
1560 }
1561 if refine_iterations < 0 {
1562 return Err(Error::invalid_argument(
1563 "calibrate_camera refine_iterations must be nonnegative",
1564 ));
1565 }
1566 let ovals = object.read_f32()?;
1567 let ivals = image.read_f32()?;
1568 let object_views: Vec<Vec<[f64; 3]>> = (0..views)
1569 .map(|v| {
1570 let base = v * n * 3;
1571 ovals[base..base + n * 3]
1572 .as_chunks::<3>()
1573 .0
1574 .iter()
1575 .map(|t| [t[0] as f64, t[1] as f64, t[2] as f64])
1576 .collect()
1577 })
1578 .collect();
1579 let image_views: Vec<Vec<[f64; 2]>> = (0..views)
1580 .map(|v| {
1581 let base = v * n * 2;
1582 ivals[base..base + n * 2]
1583 .as_chunks::<2>()
1584 .0
1585 .iter()
1586 .map(|t| [t[0] as f64, t[1] as f64])
1587 .collect()
1588 })
1589 .collect();
1590 for (v, view) in object_views.iter().enumerate() {
1591 if view.iter().any(|p| p[2].abs() > 1e-6) {
1592 return Err(Error::invalid_argument(format!(
1593 "calibrate_camera view {v} is not planar (z != 0)"
1594 )));
1595 }
1596 }
1597 let homographies: Vec<[[f64; 3]; 3]> = object_views
1599 .iter()
1600 .zip(image_views.iter())
1601 .map(|(obj, img)| {
1602 let src: Vec<[f64; 2]> = obj.iter().map(|p| [p[0], p[1]]).collect();
1603 dlt_homography(&src, img)
1604 })
1605 .collect::<Option<Vec<_>>>()
1606 .ok_or_else(|| degenerate("calibrate_camera"))?;
1607 let mut equations = vec![0.0f64; 2 * views * 6];
1610 for (v, h) in homographies.iter().enumerate() {
1611 let v_row = |p: usize, q: usize| -> [f64; 6] {
1612 let hp = |i: usize| h[i][p];
1613 let hq = |i: usize| h[i][q];
1614 [
1615 hp(0) * hq(0),
1616 hp(0) * hq(1) + hp(1) * hq(0),
1617 hp(1) * hq(1),
1618 hp(2) * hq(0) + hp(0) * hq(2),
1619 hp(2) * hq(1) + hp(1) * hq(2),
1620 hp(2) * hq(2),
1621 ]
1622 };
1623 let v12 = v_row(0, 1);
1624 let v11 = v_row(0, 0);
1625 let v22 = v_row(1, 1);
1626 for i in 0..6 {
1627 equations[2 * v * 6 + i] = v12[i];
1628 equations[(2 * v + 1) * 6 + i] = v11[i] - v22[i];
1629 }
1630 }
1631 let b = smallest_right_singular::<6>(&equations, 2 * views)
1632 .ok_or_else(|| degenerate("calibrate_camera"))?;
1633 let b = [b[0][0], b[1][0], b[2][0], b[3][0], b[4][0], b[5][0]];
1634 let mut camera = zhang_intrinsics(&b)
1636 .or_else(|| zhang_intrinsics(&b.map(|v| -v)))
1637 .ok_or_else(|| degenerate("calibrate_camera"))?;
1638 let kinv = invert3(camera).ok_or_else(|| degenerate("calibrate_camera"))?;
1640 let mut poses: Vec<([f64; 3], [f64; 3])> = Vec::with_capacity(views);
1641 for h in &homographies {
1642 let kh = mul_mat3(&kinv, h);
1643 let l1 = norm([kh[0][0], kh[1][0], kh[2][0]]);
1644 let l2 = norm([kh[0][1], kh[1][1], kh[2][1]]);
1645 if l1 < 1e-14 || l2 < 1e-14 {
1646 return Err(degenerate("calibrate_camera"));
1647 }
1648 let scale = 2.0 / (l1 + l2);
1649 let r1 = [kh[0][0] * scale, kh[1][0] * scale, kh[2][0] * scale];
1650 let r2 = [kh[0][1] * scale, kh[1][1] * scale, kh[2][1] * scale];
1651 let r3 = cross(r1, r2);
1652 let mut rotation = [
1653 [r1[0], r2[0], r3[0]],
1654 [r1[1], r2[1], r3[1]],
1655 [r1[2], r2[2], r3[2]],
1656 ];
1657 if let Some((u, _, vt)) = svd3(rotation) {
1659 rotation = mul_mat3(&u, &vt);
1660 }
1661 if det3(&rotation) < 0.0 {
1662 for r in rotation.iter_mut() {
1663 for c in r.iter_mut() {
1664 *c = -*c;
1665 }
1666 }
1667 }
1668 let t = [kh[0][2] * scale, kh[1][2] * scale, kh[2][2] * scale];
1669 poses.push((rodrigues_vector(&rotation), t));
1670 }
1671 let mut distortion = [0.0f64; 2];
1672 if refine_iterations > 0 {
1673 calibrate_refine(
1674 &mut camera,
1675 &mut distortion,
1676 &mut poses,
1677 &object_views,
1678 &image_views,
1679 refine_iterations as usize,
1680 );
1681 }
1682 let rotation_mats: Vec<[[f64; 3]; 3]> = poses.iter().map(|(r, _)| rodrigues_matrix(r)).collect();
1684 let mut sse = 0.0;
1685 let mut count = 0usize;
1686 for (v, view) in object_views.iter().enumerate() {
1687 for (point, &target) in view.iter().zip(image_views[v].iter()) {
1688 let [x, y, z] = camera_project(&rotation_mats[v], &poses[v].1, point);
1689 if z.abs() < 1e-12 {
1690 continue;
1691 }
1692 let (xn, yn) = distort_normalized(x / z, y / z, &distortion);
1693 let u = camera[0][0] * xn + camera[0][1] * yn + camera[0][2];
1694 let w = camera[1][0] * xn + camera[1][1] * yn + camera[1][2];
1695 sse += (u - target[0]).powi(2) + (w - target[1]).powi(2);
1696 count += 1;
1697 }
1698 }
1699 let rms = if count > 0 {
1700 (sse / count as f64).sqrt()
1701 } else {
1702 0.0
1703 };
1704 let mut rvecs = Vec::with_capacity(views * 3);
1705 let mut tvecs = Vec::with_capacity(views * 3);
1706 for (r, t) in &poses {
1707 rvecs.extend(r.iter().map(|v| *v as f32));
1708 tvecs.extend(t.iter().map(|v| *v as f32));
1709 }
1710 Ok(CalibrateCameraResult {
1711 camera: mat3_f32(camera)?,
1712 distortion: vector_f32(&[distortion[0], distortion[1], 0.0, 0.0, 0.0])?,
1713 rotations: Matrix::new_from_f32([views, 3], &rvecs)?,
1714 translations: Matrix::new_from_f32([views, 3], &tvecs)?,
1715 rms_error: vector_f32(&[rms])?,
1716 })
1717}
1718
1719fn zhang_intrinsics(b: &[f64; 6]) -> Option<[[f64; 3]; 3]> {
1721 let [b0, b1, b2, b3, b4, b5] = *b;
1722 let denom = b0 * b2 - b1 * b1;
1723 if denom.abs() < 1e-24 {
1724 return None;
1725 }
1726 let v0 = (b1 * b3 - b0 * b4) / denom;
1727 let lambda = b5 - (b3 * b3 + v0 * (b1 * b3 - b0 * b4)) / b0;
1728 if lambda <= 0.0 || b0.abs() < 1e-24 {
1729 return None;
1730 }
1731 let alpha = (lambda / b0).sqrt();
1732 let inner = b0 * b2 - b1 * b1;
1733 if inner <= 0.0 {
1734 return None;
1735 }
1736 let beta = (lambda * b0 / inner).sqrt();
1737 let gamma = -b1 * alpha * alpha * beta / lambda;
1738 let u0 = gamma * v0 / beta - b3 * alpha * alpha / lambda;
1739 if !(alpha.is_finite() && beta.is_finite() && u0.is_finite() && v0.is_finite()) {
1740 return None;
1741 }
1742 Some([[alpha, gamma, u0], [0.0, beta, v0], [0.0, 0.0, 1.0]])
1743}
1744
1745#[allow(clippy::type_complexity)]
1747fn calibrate_refine(
1748 camera: &mut [[f64; 3]; 3],
1749 distortion: &mut [f64; 2],
1750 poses: &mut Vec<([f64; 3], [f64; 3])>,
1751 object_views: &[Vec<[f64; 3]>],
1752 image_views: &[Vec<[f64; 2]>],
1753 iterations: usize,
1754) {
1755 let views = poses.len();
1756 let pack7 = |camera: &[[f64; 3]; 3], distortion: &[f64; 2]| -> Vec<f64> {
1758 vec![
1759 camera[0][0],
1760 camera[0][1],
1761 camera[0][2],
1762 camera[1][1],
1763 camera[1][2],
1764 distortion[0],
1765 distortion[1],
1766 ]
1767 };
1768 let unpack = |p: &[f64]| -> ([[f64; 3]; 3], [f64; 2], Vec<([f64; 3], [f64; 3])>) {
1769 let cam = [[p[0], p[1], p[2]], [0.0, p[3], p[4]], [0.0, 0.0, 1.0]];
1770 let mut ps = Vec::with_capacity(views);
1771 for v in 0..views {
1772 let base = 7 + v * 6;
1773 ps.push((
1774 [p[base], p[base + 1], p[base + 2]],
1775 [p[base + 3], p[base + 4], p[base + 5]],
1776 ));
1777 }
1778 (cam, [p[5], p[6]], ps)
1779 };
1780 let mut params = {
1781 let mut p = pack7(camera, distortion);
1782 for (r, t) in poses.iter() {
1783 p.extend_from_slice(r);
1784 p.extend_from_slice(t);
1785 }
1786 p
1787 };
1788 let residuals = |p: &[f64]| -> Vec<f64> {
1789 let (cam, dist, ps) = unpack(p);
1790 let mut out = Vec::new();
1791 for (v, view) in object_views.iter().enumerate() {
1792 let rotation = rodrigues_matrix(&ps[v].0);
1793 for (point, &target) in view.iter().zip(image_views[v].iter()) {
1794 let [x, y, z] = camera_project(&rotation, &ps[v].1, point);
1795 let (u, w) = if z.abs() < 1e-9 {
1796 (f64::MAX * 1e-6, f64::MAX * 1e-6)
1797 } else {
1798 let (xn, yn) = distort_normalized(x / z, y / z, &[dist[0], dist[1]]);
1799 (
1800 cam[0][0] * xn + cam[0][1] * yn + cam[0][2],
1801 cam[1][1] * yn + cam[1][2],
1802 )
1803 };
1804 out.push(u - target[0]);
1805 out.push(w - target[1]);
1806 }
1807 }
1808 out
1809 };
1810 let n = params.len();
1811 let mut cost: f64 = residuals(¶ms).iter().map(|r| r * r).sum();
1812 for _ in 0..iterations {
1813 let r = residuals(¶ms);
1814 let mut jacobian = vec![0.0f64; r.len() * n];
1815 for column in 0..n {
1816 let mut shifted = params.clone();
1817 let eps = (params[column].abs() * 1e-6).max(1e-6);
1818 shifted[column] += eps;
1819 let shifted_residuals = residuals(&shifted);
1820 for (row, value) in shifted_residuals.iter().enumerate() {
1821 jacobian[row * n + column] = (value - r[row]) / eps;
1822 }
1823 }
1824 let Some(step) = damped_least_squares(&jacobian, &r, r.len(), n, 1e-3) else {
1825 break;
1826 };
1827 let mut improved = false;
1828 for scale in [1.0, 0.5, 0.25] {
1829 let mut candidate = params.clone();
1830 for i in 0..n {
1831 candidate[i] += step[i] * scale;
1832 }
1833 let candidate_cost: f64 = residuals(&candidate).iter().map(|r| r * r).sum();
1834 if candidate_cost < cost {
1835 params = candidate;
1836 cost = candidate_cost;
1837 improved = true;
1838 break;
1839 }
1840 }
1841 if !improved {
1842 break;
1843 }
1844 }
1845 let (cam, dist, ps) = unpack(¶ms);
1846 *camera = cam;
1847 *distortion = dist;
1848 *poses = ps;
1849}