M13.3: face tracking methods, Face Track Points / Measurements, camera lens distortion, docs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-03 04:36:12 -04:00
co-authored by Claude Opus 5.5
parent 0bce3f2e49
commit d209fa001f
19 changed files with 939 additions and 74 deletions
+38 -8
View File
@@ -10,6 +10,7 @@
use rayon::prelude::*;
use super::Distortion;
use super::geometry::Pose;
use super::linalg::*;
@@ -19,6 +20,8 @@ pub struct BaCam {
pub pose: Pose,
/// Focal length (pixels).
pub f: f64,
/// Lens distortion (shared by all cameras; adjusted when [`BaOpts::distortion`]).
pub dist: Distortion,
}
/// One observation: camera `cam` sees point `pt` at `uv` (pixels relative to the principal
@@ -50,11 +53,13 @@ pub struct BaOpts {
/// Huber threshold (pixels).
pub huber: f64,
pub max_iter: usize,
/// Adjust the shared radial distortion `(k1, k2)` too.
pub distortion: bool,
}
impl Default for BaOpts {
fn default() -> Self {
BaOpts { focal: FocalMode::Fixed, fix_points: false, fix_centers: false, fixed: vec![], huber: 2.0, max_iter: 30 }
BaOpts { focal: FocalMode::Fixed, fix_points: false, fix_centers: false, fixed: vec![], huber: 2.0, max_iter: 30, distortion: false }
}
}
@@ -77,7 +82,8 @@ pub fn residual(c: &BaCam, x: V3, uv: [f64; 2]) -> Option<[f64; 2]> {
if p[2] <= 1e-9 {
return None;
}
Some([c.f * p[0] / p[2] - uv[0], c.f * p[1] / p[2] - uv[1]])
let q = c.dist.distort([c.f * p[0] / p[2], c.f * p[1] / p[2]]);
Some([q[0] - uv[0], q[1] - uv[1]])
}
/// Total robust cost.
@@ -108,6 +114,8 @@ struct Layout {
fidx: Vec<usize>,
/// Index of the shared focal parameter.
shared: Option<usize>,
/// Index of `k1` (then `k2`) when the distortion is adjusted.
dist: Option<usize>,
n: usize,
rot_only: bool,
}
@@ -132,7 +140,11 @@ fn layout(ncam: usize, o: &BaOpts) -> Layout {
n += 1;
n - 1
});
Layout { start, fidx, shared, n, rot_only: o.fix_centers }
let dist = o.distortion.then(|| {
n += 2;
n - 2
});
Layout { start, fidx, shared, dist, n, rot_only: o.fix_centers }
}
/// Camera-side Jacobian entries of one observation: (parameter index, d r / d param).
@@ -204,12 +216,21 @@ pub fn adjust(cams: &mut [BaCam], pts: &mut [V3], obs: &[BaObs], o: &BaOpts) ->
continue;
}
let iz = 1.0 / xc[2];
let p = [c.f * xc[0] * iz, c.f * xc[1] * iz];
let r = [p[0] - ob.uv[0], p[1] - ob.uv[1]];
let p0 = [c.f * xc[0] * iz, c.f * xc[1] * iz];
let pd = c.dist.distort(p0);
let r = [pd[0] - ob.uv[0], pd[1] - ob.uv[1]];
let e = (r[0] * r[0] + r[1] * r[1]).sqrt();
let w = if e <= o.huber { 1.0 } else { o.huber / e };
let a = [[c.f * iz, 0.0, -c.f * xc[0] * iz * iz], [0.0, c.f * iz, -c.f * xc[1] * iz * iz]];
let a0 = [[c.f * iz, 0.0, -c.f * xc[0] * iz * iz], [0.0, c.f * iz, -c.f * xc[1] * iz * iz]];
// Through the distortion: d r = D d p.
let (dj, dk) = c.dist.jacobian(p0);
let a = [0, 1].map(|i| [0, 1, 2].map(|k| dj[i][0] * a0[0][k] + dj[i][1] * a0[1][k]));
let p = [dj[0][0] * p0[0] + dj[0][1] * p0[1], dj[1][0] * p0[0] + dj[1][1] * p0[1]];
cam_jac(&l, ci, c, xc, &a, p, &mut jc);
if let Some(g) = l.dist {
jc.push((g, [dk[0][0], dk[1][0]]));
jc.push((g + 1, [dk[0][1], dk[1][1]]));
}
// Point Jacobian: A R.
let jx = if o.fix_points {
[[0.0; 3]; 2]
@@ -236,7 +257,8 @@ pub fn adjust(cams: &mut [BaCam], pts: &mut [V3], obs: &[BaObs], o: &BaOpts) ->
[w * (ja[0] * jx[0][0] + ja[1] * jx[1][0]), w * (ja[0] * jx[0][1] + ja[1] * jx[1][1]), w * (ja[0] * jx[0][2] + ja[1] * jx[1][2])];
// Each observation of a point is on another camera: only the shared focal
// length repeats.
let found = if Some(*ia) == l.shared { ps.w.iter_mut().find(|e| e.0 == *ia) } else { None };
let repeats = Some(*ia) == l.shared || l.dist.is_some_and(|g| *ia == g || *ia == g + 1);
let found = if repeats { ps.w.iter_mut().find(|e| e.0 == *ia) } else { None };
match found {
Some(e) => e.1 = add(e.1, wv),
None => ps.w.push((*ia, wv)),
@@ -385,6 +407,10 @@ pub fn adjust(cams: &mut [BaCam], pts: &mut [V3], obs: &[BaObs], o: &BaOpts) ->
if let Some(g) = l.shared {
c.f *= dc[g].clamp(-0.5, 0.5).exp();
}
if let Some(g) = l.dist {
c.dist.k1 += dc[g].clamp(-0.2, 0.2);
c.dist.k2 += dc[g + 1].clamp(-0.2, 0.2);
}
}
let mut np: Vec<V3> = pts.to_vec();
if !o.fix_points {
@@ -445,7 +471,11 @@ mod tests {
let truth: Vec<V3> = (0..80).map(|_| [u() * 6.0, u() * 4.0, 6.0 + u() * 4.0]).collect();
let f = 900.0;
let cams_true: Vec<BaCam> = (0..6)
.map(|i| BaCam { pose: Pose { r: rodrigues([0.0, -0.05 * i as f64, 0.01 * i as f64]), c: [0.3 * i as f64, 0.05 * i as f64, 0.0] }, f })
.map(|i| BaCam {
pose: Pose { r: rodrigues([0.0, -0.05 * i as f64, 0.01 * i as f64]), c: [0.3 * i as f64, 0.05 * i as f64, 0.0] },
f,
dist: Distortion::NONE,
})
.collect();
let mut obs = vec![];
for (ci, c) in cams_true.iter().enumerate() {
+107 -2
View File
@@ -28,8 +28,15 @@
//! tripod solution when it explains the tracks as well as the general one (a quick rotation fit
//! at the general solution's focal length skips the tripod search when it clearly fails).
//!
//! The camera model has square pixels, the principal point at the layer centre and no lens
//! distortion. Camera space is x right, y down, z forward (After Effects' convention); a camera
//! 5. **Lens distortion** (Solve Lens Distortion, or Detailed Analysis): radial distortion
//! `p_d = p (1 + k1 ρ² + k2 ρ⁴)` (ρ = distance from the principal point over half the frame
//! diagonal; Brown's model without the tangential terms) is solved jointly with the cameras
//! and points in a final bundle adjustment on the raw tracks; the whole solve is then repeated
//! on tracks undistorted with that estimate (the linear initialisations assume a pinhole
//! camera) and adjusted jointly again. The solve stores `k1, k2`; the effect can undistort
//! its output so composited 3D layers line up.
//!
//! The camera model has square pixels and the principal point at the layer centre. Camera space is x right, y down, z forward (After Effects' convention); a camera
//! is `(R, C, f)` with `X_cam = R (X − C)` and pixel `u = f x / z + w / 2`.
//!
//! The solve is stored in a canonical frame: the first solved frame's camera is at the origin
@@ -105,6 +112,69 @@ impl CameraTracks {
}
}
/// Radial lens distortion around the principal point (see the module docs).
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct Distortion {
pub k1: f64,
pub k2: f64,
/// Normalisation radius ρ = 1 (pixels): half the frame diagonal; 0 = no distortion.
pub radius: f64,
}
impl Distortion {
pub const NONE: Distortion = Distortion { k1: 0.0, k2: 0.0, radius: 0.0 };
/// No distortion for frames of `size` (the radius set, coefficients zero).
pub fn for_size(size: [f64; 2]) -> Distortion {
Distortion { k1: 0.0, k2: 0.0, radius: 0.5 * size[0].hypot(size[1]) }
}
pub fn is_none(&self) -> bool {
self.radius <= 0.0 || (self.k1 == 0.0 && self.k2 == 0.0)
}
fn rho2(&self, p: [f64; 2]) -> f64 {
(p[0] * p[0] + p[1] * p[1]) / (self.radius * self.radius)
}
/// Ideal → distorted (pixels relative to the principal point).
pub fn distort(&self, p: [f64; 2]) -> [f64; 2] {
if self.radius <= 0.0 {
return p;
}
let r2 = self.rho2(p);
let d = 1.0 + self.k1 * r2 + self.k2 * r2 * r2;
[p[0] * d, p[1] * d]
}
/// Distorted → ideal (fixed-point iteration).
pub fn undistort(&self, q: [f64; 2]) -> [f64; 2] {
if self.is_none() {
return q;
}
let mut p = q;
for _ in 0..30 {
let r2 = self.rho2(p);
let d = 1.0 + self.k1 * r2 + self.k2 * r2 * r2;
if d.abs() < 1e-6 {
break;
}
p = [q[0] / d, q[1] / d];
}
p
}
/// `d distort / d p` (2 × 2, row-major) and `d distort / d (k1, k2)` (rows x, y).
pub fn jacobian(&self, p: [f64; 2]) -> ([[f64; 2]; 2], [[f64; 2]; 2]) {
if self.radius <= 0.0 {
return ([[1.0, 0.0], [0.0, 1.0]], [[0.0; 2]; 2]);
}
let r2 = self.rho2(p);
let d = 1.0 + self.k1 * r2 + self.k2 * r2 * r2;
// d(r2)/dp = 2 p / R².
let dd = (self.k1 + 2.0 * self.k2 * r2) * 2.0 / (self.radius * self.radius);
let j = [[d + p[0] * dd * p[0], p[0] * dd * p[1]], [p[1] * dd * p[0], d + p[1] * dd * p[1]]];
let k = [[p[0] * r2, p[0] * r2 * r2], [p[1] * r2, p[1] * r2 * r2]];
(j, k)
}
}
/// 3D Camera Tracker ▸ Shot Type.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -178,6 +248,8 @@ pub struct SolveSettings {
pub method: SolveMethod,
/// Track ids the user deleted.
pub deleted: Vec<u32>,
/// Solve radial lens distortion jointly with the cameras.
pub lens_distortion: bool,
}
/// The solved camera of one frame.
@@ -261,6 +333,9 @@ pub struct CameraSolve {
pub points: Vec<SolvedPoint>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ground: Option<Ground>,
/// The solved lens distortion (Solve Lens Distortion).
#[serde(skip_serializing_if = "Option::is_none")]
pub distortion: Option<Distortion>,
}
impl CameraSolve {
@@ -355,6 +430,36 @@ impl CameraSolve {
}
}
/// An ideal (pinhole) image point → where it appears in the footage (layer pixels), through
/// the solved lens distortion.
pub fn to_image(&self, p: [f64; 2]) -> [f64; 2] {
match &self.distortion {
Some(d) if !d.is_none() => {
let c = [self.size[0] * 0.5, self.size[1] * 0.5];
let q = d.distort([p[0] - c[0], p[1] - c[1]]);
[q[0] + c[0], q[1] + c[1]]
}
_ => p,
}
}
/// A footage point → its ideal (undistorted) position.
pub fn to_ideal(&self, p: [f64; 2]) -> [f64; 2] {
match &self.distortion {
Some(d) if !d.is_none() => {
let c = [self.size[0] * 0.5, self.size[1] * 0.5];
let q = d.undistort([p[0] - c[0], p[1] - c[1]]);
[q[0] + c[0], q[1] + c[1]]
}
_ => p,
}
}
/// Project world point `x` on frame `k`: through the lens distortion into the footage, or
/// (`undistorted`) into the undistorted image.
pub fn project(&self, k: usize, x: V3, undistorted: bool) -> Option<[f64; 2]> {
let q = self.frames.get(k)?.project(self.size, x)?;
Some(if undistorted { q } else { self.to_image(q) })
}
/// The first solved frame.
pub fn first_solved(&self) -> Option<usize> {
self.frames.iter().position(|c| c.solved)
+113 -12
View File
@@ -8,7 +8,7 @@ use rayon::prelude::*;
use super::bundle::{self, BaCam, BaObs, BaOpts, FocalMode};
use super::geometry::{self, Pose};
use super::linalg::*;
use super::{CameraSolve, CameraTracks, ShotType, SolveMethod, SolveSettings, SolvedFrame, SolvedPoint};
use super::{CameraSolve, CameraTracks, Distortion, ShotType, SolveMethod, SolveSettings, SolvedFrame, SolvedPoint};
use crate::fit::{Model, ransac};
fn debug() -> bool {
@@ -142,6 +142,8 @@ struct Cfg {
focal: FocalMode,
/// Registration estimates a focal length per frame.
per_frame_f: bool,
/// The global adjustments also adjust the lens distortion.
distortion: bool,
}
const F_PRIOR: f64 = 30.0;
@@ -183,7 +185,7 @@ impl Recon {
&mut cams,
&mut pts,
&obs,
&BaOpts { focal, fix_points: false, fix_centers: cfg.kind == Kind::Tripod, fixed, huber: d.huber(), max_iter: iters },
&BaOpts { focal, fix_points: false, fix_centers: cfg.kind == Kind::Tripod, fixed, huber: d.huber(), max_iter: iters, distortion: cfg.distortion },
);
for (k, c) in frames.iter().zip(&cams) {
self.cams.insert(*k, *c);
@@ -289,6 +291,7 @@ impl Recon {
fixed: vec![false],
huber,
max_iter: 40,
distortion: false,
};
let mut best: Option<(usize, BaCam)> = None;
// Robust start (large Huber threshold), then tighten; from the prediction and, failing
@@ -371,7 +374,11 @@ fn predict(r: &Recon, k: usize) -> Option<BaCam> {
match (before, after) {
(Some((ka, a)), Some((kb, b))) => {
let t = (k - ka) as f64 / (kb - ka) as f64;
Some(BaCam { pose: Pose { r: slerp(&a.pose.r, &b.pose.r, t), c: add(scale(a.pose.c, 1.0 - t), scale(b.pose.c, t)) }, f: a.f * (b.f / a.f).powf(t) })
Some(BaCam {
pose: Pose { r: slerp(&a.pose.r, &b.pose.r, t), c: add(scale(a.pose.c, 1.0 - t), scale(b.pose.c, t)) },
f: a.f * (b.f / a.f).powf(t),
dist: a.dist,
})
}
(Some((ka, a)), None) => {
// Constant velocity from the two previous cameras.
@@ -381,7 +388,7 @@ fn predict(r: &Recon, k: usize) -> Option<BaCam> {
let dr = log_rot(&mm(&a.pose.r, &mt(&p.pose.r)));
let rr = mm(&rodrigues(scale(dr, t.min(2.0))), &a.pose.r);
let c = add(a.pose.c, scale(sub(a.pose.c, p.pose.c), t.min(2.0)));
Some(BaCam { pose: Pose { r: rr, c }, f: a.f })
Some(BaCam { pose: Pose { r: rr, c }, f: a.f, dist: a.dist })
}
None => Some(a),
}
@@ -392,7 +399,7 @@ fn predict(r: &Recon, k: usize) -> Option<BaCam> {
let dr = log_rot(&mm(&b.pose.r, &mt(&nx.pose.r)));
let rr = mm(&rodrigues(scale(dr, t.min(2.0))), &b.pose.r);
let c = add(b.pose.c, scale(sub(b.pose.c, nx.pose.c), t.min(2.0)));
Some(BaCam { pose: Pose { r: rr, c }, f: b.f })
Some(BaCam { pose: Pose { r: rr, c }, f: b.f, dist: b.dist })
}
None => Some(b),
},
@@ -459,8 +466,8 @@ fn init_pair(d: &Data, a: usize, b: usize, f: f64, use_e: bool, use_h: bool) ->
fn grow(d: &Data, kfs: &[usize], j: usize, init: &(Pose, HashMap<u32, V3>), f: f64, cfg: &Cfg, cancel: Option<&AtomicBool>) -> Option<Recon> {
let (a, b) = (kfs[0], kfs[j]);
let mut r = Recon::default();
r.cams.insert(a, BaCam { pose: Pose::IDENTITY, f });
r.cams.insert(b, BaCam { pose: init.0, f });
r.cams.insert(a, BaCam { pose: Pose::IDENTITY, f, dist: Distortion::NONE });
r.cams.insert(b, BaCam { pose: init.0, f, dist: Distortion::NONE });
r.pts = init.1.clone();
let inner = |r: &mut Recon, frames: &[usize]| {
let focal = if cfg.per_frame_f && frames.len() > 2 { FocalMode::PerCamera(F_PRIOR) } else { FocalMode::Fixed };
@@ -495,7 +502,7 @@ fn grow(d: &Data, kfs: &[usize], j: usize, init: &(Pose, HashMap<u32, V3>), f: f
/// Tripod reconstruction over keyframes `kfs` at focal length `f`.
fn grow_tripod(d: &Data, kfs: &[usize], f: f64, cfg: &Cfg, cancel: Option<&AtomicBool>) -> Option<Recon> {
let mut r = Recon::default();
r.cams.insert(kfs[0], BaCam { pose: Pose::IDENTITY, f });
r.cams.insert(kfs[0], BaCam { pose: Pose::IDENTITY, f, dist: Distortion::NONE });
let ray = |p: [f64; 2], f: f64| normalize([p[0] / f, p[1] / f, 1.0]);
for w in kfs.windows(2) {
if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
@@ -519,7 +526,7 @@ fn grow_tripod(d: &Data, kfs: &[usize], f: f64, cfg: &Cfg, cancel: Option<&Atomi
rel = geometry::procrustes(&ia, &ib)?;
}
let pa = r.cams[&a].pose.r;
r.cams.insert(b, BaCam { pose: Pose { r: mm(&rel, &pa), c: [0.0; 3] }, f });
r.cams.insert(b, BaCam { pose: Pose { r: mm(&rel, &pa), c: [0.0; 3] }, f, dist: Distortion::NONE });
}
r.triangulate(d, Kind::Tripod, 0.0, 20.0);
let frames: Vec<usize> = r.cams.keys().copied().collect();
@@ -640,8 +647,101 @@ fn search_focal(w: f64, eval: &(dyn Fn(f64) -> f64 + Sync)) -> f64 {
if best.1 <= errs[i] { best.0.exp() } else { fs[i] }
}
/// A solve before its canonical output.
struct Core {
d: Data,
r: Recon,
method: SolveMethod,
kind: Kind,
cfg: Cfg,
focal: FocalMode,
kfs: Vec<usize>,
}
/// `tracks` with every position undistorted by `dist`.
fn undistorted(tracks: &CameraTracks, dist: &Distortion) -> CameraTracks {
let c = [tracks.size[0] * 0.5, tracks.size[1] * 0.5];
let mut t = tracks.clone();
for tr in t.tracks.iter_mut() {
for p in tr.pts.iter_mut() {
let q = dist.undistort([p[0] as f64 - c[0], p[1] as f64 - c[1]]);
*p = [(q[0] + c[0]) as f32, (q[1] + c[1]) as f32];
}
}
t
}
/// Solve the camera of a tracked clip.
pub fn solve(tracks: &CameraTracks, s: &SolveSettings, cancel: Option<&AtomicBool>) -> Result<CameraSolve, SolveError> {
if !s.lens_distortion {
let c = solve_core(tracks, s, cancel)?;
return Ok(finish(&c.d, tracks, s, c.r, c.method, c.kind));
}
// Lens distortion: solve, adjust (k1, k2) jointly on the raw tracks, then solve again on
// tracks undistorted with the estimate and adjust jointly once more.
let mut dist = Distortion::for_size(tracks.size);
let mut out = None;
for pass in 0..2 {
let und = (pass > 0).then(|| undistorted(tracks, &dist));
let c = solve_core(und.as_ref().unwrap_or(tracks), s, cancel)?;
let d = Data::new(tracks, &s.deleted);
d.set_noise(c.d.noise());
let mut r = c.r;
for cam in r.cams.values_mut() {
cam.dist = dist;
}
let cfg = Cfg { distortion: true, ..c.cfg };
let all: Vec<usize> = r.cams.keys().copied().collect();
let frames: Vec<usize> = if all.len() <= 160 { all.clone() } else { c.kfs.iter().copied().filter(|k| r.cams.contains_key(k)).collect() };
if frames.len() < 2 {
return err("the camera could not be solved (not enough parallax or features)");
}
// The pinhole solve's outliers include the distorted frame edges: start from all
// observations (the Huber loss keeps real outliers in check), then reject again.
r.outliers.clear();
r.adjust(&d, &frames, &cfg, c.focal, 30);
r.outliers.clear();
r.reject(&d);
r.adjust(&d, &frames, &cfg, c.focal, 30);
dist = r.cams[&frames[0]].dist;
for cam in r.cams.values_mut() {
cam.dist = dist;
}
if frames.len() < all.len() {
// Refine the other frames against the adjusted points and distortion.
let base = r.clone();
let rcfg = Cfg { distortion: false, ..cfg };
let refined: Vec<(usize, Option<BaCam>)> = all
.par_iter()
.filter(|k| !frames.contains(k))
.map(|k| {
let mut local = Recon { cams: base.cams.clone(), pts: base.pts.clone(), outliers: HashSet::new() };
let start = local.cams[k];
let ok = local.register(&d, *k, start, &rcfg);
(*k, if ok { local.cams.get(k).copied() } else { None })
})
.collect();
for (k, cam) in refined {
if let Some(cam) = cam {
r.cams.insert(k, cam);
}
}
r.reject(&d);
}
if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
return err("cancelled");
}
if debug() {
eprintln!("lens distortion pass {pass}: k1 {:.5} k2 {:.5}", dist.k1, dist.k2);
}
let mut sol = finish(&d, tracks, s, r, c.method, c.kind);
sol.distortion = Some(dist);
out = Some(sol);
}
out.ok_or_else(|| SolveError("the camera could not be solved".into()))
}
fn solve_core(tracks: &CameraTracks, s: &SolveSettings, cancel: Option<&AtomicBool>) -> Result<Core, SolveError> {
let d = Data::new(tracks, &s.deleted);
if d.n < 2 {
return err("the clip must be at least two frames long");
@@ -653,7 +753,7 @@ pub fn solve(tracks: &CameraTracks, s: &SolveSettings, cancel: Option<&AtomicBoo
let cancelled = || cancel.is_some_and(|c| c.load(Ordering::Relaxed));
let fixed_f = (s.shot == ShotType::SpecifyAngle).then(|| focal_of(d.w, if s.hfov > 0.0 { s.hfov } else { 40.0 }));
let variable = s.shot == ShotType::VariableZoom;
let gcfg = Cfg { kind: Kind::General, focal: FocalMode::Fixed, per_frame_f: false };
let gcfg = Cfg { kind: Kind::General, focal: FocalMode::Fixed, per_frame_f: false, distortion: false };
let tcfg = Cfg { kind: Kind::Tripod, ..gcfg };
// The focal-length search runs on the first keyframes only.
let mini: Vec<usize> = kfs.iter().copied().take(10).collect();
@@ -738,7 +838,7 @@ pub fn solve(tracks: &CameraTracks, s: &SolveSettings, cancel: Option<&AtomicBoo
}
let (att, _) = results.swap_remove(pick);
let kind = if att.method == SolveMethod::TripodPan { Kind::Tripod } else { Kind::General };
let cfg = Cfg { kind, focal: FocalMode::Fixed, per_frame_f: variable };
let cfg = Cfg { kind, focal: FocalMode::Fixed, per_frame_f: variable, distortion: false };
let mut r = att.recon;
let focal = match (fixed_f, variable) {
(Some(_), _) => FocalMode::Fixed,
@@ -845,7 +945,7 @@ pub fn solve(tracks: &CameraTracks, s: &SolveSettings, cancel: Option<&AtomicBoo
(m, _) => m,
};
lap("final adjustment");
Ok(finish(&d, tracks, s, r, method, kind))
Ok(Core { d, r, method, kind, cfg, focal, kfs: kf_frames })
}
/// Thickness of a point cloud: √(smallest / middle eigenvalue of its covariance).
@@ -949,5 +1049,6 @@ fn finish(d: &Data, tracks: &CameraTracks, s: &SolveSettings, r: Recon, method:
frames,
points,
ground: None,
distortion: None,
}
}
+61 -4
View File
@@ -105,7 +105,7 @@ fn path_error(s: &CameraSolve, t: &Truth) -> (f64, f64) {
}
fn settings(shot: ShotType, method: SolveMethod) -> SolveSettings {
SolveSettings { shot, hfov: 0.0, method, deleted: vec![] }
SolveSettings { shot, hfov: 0.0, method, deleted: vec![], lens_distortion: false }
}
#[test]
@@ -149,7 +149,8 @@ fn specified_angle_of_view_is_kept() {
let pts = random_points(300, 5, [0.0, 0.0, 10.0], [14.0, 8.0, 8.0]);
let tr = tracks_of(&pts, &t, 6, true);
let hfov = 2.0 * (W * 0.5 / f).atan().to_degrees();
let s = solve(&tr, &SolveSettings { shot: ShotType::SpecifyAngle, hfov, method: SolveMethod::Typical, deleted: vec![] }, None).unwrap();
let s =
solve(&tr, &SolveSettings { shot: ShotType::SpecifyAngle, hfov, method: SolveMethod::Typical, deleted: vec![], lens_distortion: false }, None).unwrap();
assert!((s.focal() - f).abs() < 1e-6);
assert!(s.average_error < 0.5);
let (pe, _) = path_error(&s, &t);
@@ -226,7 +227,9 @@ fn mostly_flat_scene_and_ground_plane() {
}
// Ground plane from the solved (coplanar) points: every point lies on it.
let hfov = 2.0 * (W * 0.5 / f).atan().to_degrees();
let mut s = solve(&tr, &SolveSettings { shot: ShotType::SpecifyAngle, hfov, method: SolveMethod::MostlyFlat, deleted: vec![] }, None).expect("solve");
let mut s =
solve(&tr, &SolveSettings { shot: ShotType::SpecifyAngle, hfov, method: SolveMethod::MostlyFlat, deleted: vec![], lens_distortion: false }, None)
.expect("solve");
let ids: Vec<u32> = s.visible(0).map(|p| p.id).take(12).collect();
let g = s.ground_from(&ids, 0).expect("ground");
let spread = s.points.iter().map(|p| dot(sub(p.pos, g.origin), g.normal).abs()).fold(0.0, f64::max);
@@ -251,7 +254,9 @@ fn deleted_tracks_are_ignored_and_cancel_stops() {
let tr = tracks_of(&pts, &t, 14, true);
let deleted: Vec<u32> = (0..40).collect();
let hfov = 2.0 * (W * 0.5 / 1000.0f64).atan().to_degrees();
let s = solve(&tr, &SolveSettings { shot: ShotType::SpecifyAngle, hfov, method: SolveMethod::Typical, deleted: deleted.clone() }, None).unwrap();
let s =
solve(&tr, &SolveSettings { shot: ShotType::SpecifyAngle, hfov, method: SolveMethod::Typical, deleted: deleted.clone(), lens_distortion: false }, None)
.unwrap();
assert!(s.points.iter().all(|p| !deleted.contains(&p.id)));
let stop = std::sync::atomic::AtomicBool::new(true);
let r = solve(&tr, &settings(ShotType::FixedAngle, SolveMethod::Typical), Some(&stop));
@@ -436,3 +441,55 @@ fn solve_saved_tracks() {
t0.elapsed()
);
}
/// Pass every track position through a lens distortion (around the frame centre).
fn distort_tracks(t: &CameraTracks, d: &Distortion) -> CameraTracks {
let mut t = t.clone();
for tr in t.tracks.iter_mut() {
for p in tr.pts.iter_mut() {
let q = d.distort([p[0] as f64 - W / 2.0, p[1] as f64 - H / 2.0]);
*p = [(q[0] + W / 2.0) as f32, (q[1] + H / 2.0) as f32];
}
}
t
}
#[test]
fn lens_distortion_is_recovered_in_the_bundle_adjustment() {
let f = 1000.0;
let t = moving_camera(36, |_| f);
let pts = random_points(450, 7, [0.0, 0.0, 10.0], [16.0, 9.0, 8.0]);
let truth = Distortion { k1: -0.12, k2: 0.03, radius: 0.5 * W.hypot(H) };
let tr = distort_tracks(&tracks_of(&pts, &t, 8, true), &truth);
let plain = solve(&tr, &settings(ShotType::FixedAngle, SolveMethod::Typical), None).expect("pinhole solve");
let lens = solve(&tr, &SolveSettings { lens_distortion: true, ..settings(ShotType::FixedAngle, SolveMethod::Typical) }, None).expect("lens solve");
let d = lens.distortion.expect("distortion solved");
eprintln!(
"pinhole error {:.3} px (focal {:.1}); with distortion {:.3} px (focal {:.1}), k1 {:.4} k2 {:.4}",
plain.average_error,
plain.focal(),
lens.average_error,
lens.focal(),
d.k1,
d.k2
);
assert!(plain.distortion.is_none());
assert!((d.k1 - truth.k1).abs() < 0.005, "k1 {}", d.k1);
assert!((d.k2 - truth.k2).abs() < 0.01, "k2 {}", d.k2);
// The distortion model explains the tracks: about the noise level, far below the pinhole fit.
assert!(lens.average_error < 0.3, "{}", lens.average_error);
assert!(lens.average_error < 0.5 * plain.average_error, "{} vs {}", lens.average_error, plain.average_error);
assert!((lens.focal() - f).abs() < 0.02 * f, "focal {}", lens.focal());
let (path, rot) = path_error(&lens, &t);
assert!(path < 0.01 && rot < 0.3, "path {path} rot {rot}");
// Projection through the lens lands on the (distorted) tracks; undistorting inverts it.
let p = [100.0, 80.0];
let q = lens.to_image(p);
let back = lens.to_ideal(q);
assert!((back[0] - p[0]).abs() < 1e-6 && (back[1] - p[1]).abs() < 1e-6);
let sp = &lens.points[0];
let k = sp.first as usize;
let obs = tr.track(sp.id).and_then(|t| t.at(k as u32)).expect("observed");
let proj = lens.project(k, sp.pos, false).expect("in front");
assert!((proj[0] - obs[0]).hypot(proj[1] - obs[1]) < 2.0, "{proj:?} vs {obs:?}");
}
+5
View File
@@ -624,6 +624,11 @@ impl FaceTracker {
};
let mut t = FaceTracker { skin, prev: guess, expect: canon };
let fit = t.fit(frame)?;
// A face shows at least two of: left eye, right eye, mouth.
let found = [EYE[0][4], EYE[1][4], MOUTH[0]].iter().filter(|i| fit.detected[**i]).count();
if found < 2 {
return None;
}
t.accept(&fit);
Some((t, fit))
}