M12.6: 3D Camera Tracker effect + UI
Effect > Perspective > 3D Camera Tracker (Shot Type, Horizontal Angle of View, Show/Render Track Points, Track Point Size, Target Size, Advanced: Solve Method, Method Used, Average Error, Detailed Analysis, Auto-delete Points Across Time, Hide Warning Banner); tracks and solve stored in the effect with keys (frame edits re-track, setting / deleted-point edits only re-solve). Background job (Analyzing in background (step 1 of 2) / Solving camera banner, cancel, one undo step). Commands: track.camera (replaces the stub), camera.analyze/cancel/solveStatus/points/selectPoints/ createFromSolve/create/setGroundPlane/deletePoints; the one-node 3D Tracker Camera keyed per frame and text / solids / nulls / shadow catcher + light on the target plane, Create Multiple. Viewer: depth-sized coloured targets, hover target plane, click / shift / marquee selection, AE right-click menu, Delete; Effect Controls Analyze / Cancel / Create Camera; Tracker panel Track Camera. Solver: adaptive noise thresholds, denser keyframes, quick tripod check, faster Cholesky and parallel Schur complement. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
bab4f88c22
commit
cba8d7e737
@@ -173,6 +173,9 @@ pub fn adjust(cams: &mut [BaCam], pts: &mut [V3], obs: &[BaObs], o: &BaOpts) ->
|
||||
}
|
||||
let mut cur = cost(cams, pts, obs, o);
|
||||
let initial = cur;
|
||||
let t0 = web_time::Instant::now();
|
||||
let mut tries = 0usize;
|
||||
let dbg = std::env::var_os("EC_CAMTRACK_DEBUG").is_some() && l.n > 200;
|
||||
let mut lambda = 1e-4;
|
||||
let mut iters = 0;
|
||||
if l.n == 0 && o.fix_points {
|
||||
@@ -231,7 +234,10 @@ pub fn adjust(cams: &mut [BaCam], pts: &mut [V3], obs: &[BaObs], o: &BaOpts) ->
|
||||
for (ia, ja) in &jc {
|
||||
let wv =
|
||||
[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])];
|
||||
match ps.w.iter_mut().find(|e| e.0 == *ia) {
|
||||
// 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 };
|
||||
match found {
|
||||
Some(e) => e.1 = add(e.1, wv),
|
||||
None => ps.w.push((*ia, wv)),
|
||||
}
|
||||
@@ -294,31 +300,67 @@ pub fn adjust(cams: &mut [BaCam], pts: &mut [V3], obs: &[BaObs], o: &BaOpts) ->
|
||||
// ---- Try steps with increasing damping.
|
||||
let mut accepted = false;
|
||||
for _try in 0..12 {
|
||||
tries += 1;
|
||||
let mut s = base_s.clone();
|
||||
let mut rhs = base_bc.clone();
|
||||
for i in 0..n {
|
||||
let d = s[i * n + i];
|
||||
s[i * n + i] = d + lambda * d.max(1e-6 * mean_diag);
|
||||
}
|
||||
// Schur complement over the points.
|
||||
let mut vinv: Vec<Option<M3>> = vec![None; npts];
|
||||
// Schur complement over the points: S −= W V⁻¹ Wᵀ, rhs −= W V⁻¹ bp (in parallel
|
||||
// chunks of points when the reduced system is small enough to copy per thread).
|
||||
let vinv: Vec<Option<M3>> = if o.fix_points {
|
||||
vec![None; npts]
|
||||
} else {
|
||||
systems
|
||||
.par_iter()
|
||||
.map(|ps| {
|
||||
let mut v = ps.v;
|
||||
let vd = (v[0][0] + v[1][1] + v[2][2]) / 3.0;
|
||||
for k in 0..3 {
|
||||
v[k][k] += lambda * v[k][k].max(1e-6 * vd.max(1e-12)) + 1e-12;
|
||||
}
|
||||
inv3(&v)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
if !o.fix_points {
|
||||
for (j, ps) in systems.iter().enumerate() {
|
||||
let mut v = ps.v;
|
||||
let vd = (v[0][0] + v[1][1] + v[2][2]) / 3.0;
|
||||
for k in 0..3 {
|
||||
v[k][k] += lambda * v[k][k].max(1e-6 * vd.max(1e-12)) + 1e-12;
|
||||
}
|
||||
let Some(vi) = inv3(&v) else { continue };
|
||||
vinv[j] = Some(vi);
|
||||
let vb = mv(&vi, ps.bp);
|
||||
let wv: Vec<V3> = ps.w.iter().map(|(_, w)| mv(&vi, *w)).collect();
|
||||
for (a, (ia, wa)) in ps.w.iter().enumerate() {
|
||||
rhs[*ia] -= dot(*wa, vb);
|
||||
for (ib, wb) in &ps.w {
|
||||
s[ia * n + ib] -= dot(wv[a], *wb);
|
||||
let reduce = |range: std::ops::Range<usize>, s: &mut [f64], rhs: &mut [f64]| {
|
||||
for j in range {
|
||||
let (Some(vi), ps) = (&vinv[j], &systems[j]) else { continue };
|
||||
let vb = mv(vi, ps.bp);
|
||||
let wv: Vec<V3> = ps.w.iter().map(|(_, w)| mv(vi, *w)).collect();
|
||||
for (a, (ia, wa)) in ps.w.iter().enumerate() {
|
||||
rhs[*ia] -= dot(*wa, vb);
|
||||
for (ib, wb) in &ps.w[a..] {
|
||||
let d = dot(wv[a], *wb);
|
||||
s[ia * n + ib] -= d;
|
||||
if ia != ib {
|
||||
s[ib * n + ia] -= d;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let chunks = rayon::current_num_threads().clamp(1, 8);
|
||||
if n <= 1200 && npts >= 64 && chunks > 1 {
|
||||
let per = npts.div_ceil(chunks);
|
||||
let parts: Vec<(Vec<f64>, Vec<f64>)> = (0..chunks)
|
||||
.into_par_iter()
|
||||
.map(|t| {
|
||||
let (mut ds, mut dr) = (vec![0.0; n * n], vec![0.0; n]);
|
||||
reduce(t * per..((t + 1) * per).min(npts), &mut ds, &mut dr);
|
||||
(ds, dr)
|
||||
})
|
||||
.collect();
|
||||
for (ds, dr) in parts {
|
||||
s.par_iter_mut().zip(ds.par_iter()).for_each(|(x, y)| *x += y);
|
||||
for (x, y) in rhs.iter_mut().zip(dr) {
|
||||
*x += y;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
reduce(0..npts, &mut s, &mut rhs);
|
||||
}
|
||||
}
|
||||
let mut dc = rhs;
|
||||
@@ -363,9 +405,18 @@ pub fn adjust(cams: &mut [BaCam], pts: &mut [V3], obs: &[BaObs], o: &BaOpts) ->
|
||||
let gain = cur - c2;
|
||||
cur = c2;
|
||||
lambda = (lambda / 3.0).max(1e-9);
|
||||
accepted = gain > 1e-10 * cur.max(1e-12);
|
||||
accepted = gain > 1e-6 * cur.max(1e-12);
|
||||
if !accepted {
|
||||
// Converged (tiny improvement).
|
||||
if dbg {
|
||||
eprintln!(
|
||||
"ba n={} pts={} obs={} iters={iters} tries={tries} {:.2}s cost {initial:.1} -> {cur:.1}",
|
||||
l.n,
|
||||
npts,
|
||||
obs.len(),
|
||||
t0.elapsed().as_secs_f64()
|
||||
);
|
||||
}
|
||||
return BaReport { initial_cost: initial, cost: cur, iterations: iters };
|
||||
}
|
||||
break;
|
||||
@@ -376,6 +427,9 @@ pub fn adjust(cams: &mut [BaCam], pts: &mut [V3], obs: &[BaObs], o: &BaOpts) ->
|
||||
break;
|
||||
}
|
||||
}
|
||||
if dbg {
|
||||
eprintln!("ba n={} pts={} obs={} iters={iters} tries={tries} {:.2}s cost {initial:.1} -> {cur:.1}", l.n, npts, obs.len(), t0.elapsed().as_secs_f64());
|
||||
}
|
||||
BaReport { initial_cost: initial, cost: cur, iterations: iters }
|
||||
}
|
||||
|
||||
|
||||
@@ -89,7 +89,7 @@ impl TrackAnalyzer {
|
||||
let (cx, cy) = ((p[0] / cell) as usize, (p[1] / cell) as usize);
|
||||
!occ.get(cy * gw + cx).copied().unwrap_or(true)
|
||||
};
|
||||
let opts = CornerOpts { max_features: want - self.active.len().min(want), min_distance: md, quality: 0.005, window: 2, border: 8 };
|
||||
let opts = CornerOpts { max_features: want - self.active.len().min(want), min_distance: md, quality: 0.001, window: 2, border: 8 };
|
||||
for p in good_features(&pyr, &opts, Some(&free)) {
|
||||
let l = pyr.to_layer(p);
|
||||
let id = self.tracks.len() as u32;
|
||||
|
||||
@@ -298,6 +298,23 @@ pub fn sym_eigen(a: &[f64], n: usize) -> (Vec<f64>, Vec<f64>) {
|
||||
(vals, vecs)
|
||||
}
|
||||
|
||||
/// Dot product, four lanes (lets the compiler vectorise).
|
||||
fn dot_n(a: &[f64], b: &[f64]) -> f64 {
|
||||
let mut acc = [0.0f64; 4];
|
||||
let (ca, cb) = (a.chunks_exact(4), b.chunks_exact(4));
|
||||
let (ra, rb) = (ca.remainder(), cb.remainder());
|
||||
for (x, y) in ca.zip(cb) {
|
||||
for k in 0..4 {
|
||||
acc[k] += x[k] * y[k];
|
||||
}
|
||||
}
|
||||
let mut s = acc[0] + acc[1] + acc[2] + acc[3];
|
||||
for (x, y) in ra.iter().zip(rb) {
|
||||
s += x * y;
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Solve `A x = b` for a symmetric positive definite `A` (`n × n`, row-major) in place by
|
||||
/// Cholesky factorisation. Returns false when `A` is not positive definite.
|
||||
pub fn cholesky_solve(a: &mut [f64], n: usize, b: &mut [f64]) -> bool {
|
||||
@@ -313,16 +330,9 @@ pub fn cholesky_solve(a: &mut [f64], n: usize, b: &mut [f64]) -> bool {
|
||||
a[j * n + j] = d;
|
||||
let (head, tail) = a.split_at_mut((j + 1) * n);
|
||||
let rowj = &head[j * n..j * n + j];
|
||||
// Rows below j are independent.
|
||||
use rayon::prelude::*;
|
||||
let work = |row: &mut [f64]| {
|
||||
let s: f64 = row[j] - row[..j].iter().zip(rowj).map(|(a, b)| a * b).sum::<f64>();
|
||||
row[j] = s / d;
|
||||
};
|
||||
if n - j > 192 {
|
||||
tail.par_chunks_mut(n).for_each(work);
|
||||
} else {
|
||||
tail.chunks_mut(n).for_each(work);
|
||||
// Rows below j (sequential: per-column parallel dispatch costs more than it saves).
|
||||
for row in tail.chunks_mut(n) {
|
||||
row[j] = (row[j] - dot_n(&row[..j], rowj)) / d;
|
||||
}
|
||||
}
|
||||
// Forward: L y = b.
|
||||
|
||||
@@ -13,7 +13,10 @@
|
||||
//! the other keyframes are added incrementally (**resection** by robust pose refinement,
|
||||
//! **triangulation** of new tracks by the linear method of H&Z §12.2); a sparse
|
||||
//! **Levenberg–Marquardt bundle adjustment** with the Schur complement over the points
|
||||
//! ([`bundle`]) refines everything; the frames between keyframes are resected last.
|
||||
//! ([`bundle`]) refines everything; the frames between keyframes are resected last. Inlier
|
||||
//! thresholds start from the analysis resolution and are re-estimated from the residuals
|
||||
//! (median absolute residual) once the keyframes are solved, so features on moving objects,
|
||||
//! occlusion edges and screen-locked overlays drop out.
|
||||
//! 3. **Focal length**: *Specify Angle of View* fixes it; *Fixed Angle of View* searches it
|
||||
//! (the reprojection error of the keyframe reconstruction over a log-spaced range of focal
|
||||
//! lengths, refined by golden-section search) and then adjusts it in the bundle adjustment
|
||||
@@ -22,7 +25,8 @@
|
||||
//! 4. **Tripod pan** shots (no camera translation) are solved as a pure rotation: frame-to-frame
|
||||
//! rotations from the tracked rays (orthogonal Procrustes) refined by the same bundle
|
||||
//! adjustment with the camera centres fixed. *Auto Detect* solves both ways and keeps the
|
||||
//! tripod solution when it explains the tracks as well as the general one.
|
||||
//! 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
|
||||
|
||||
@@ -37,8 +37,9 @@ struct Data {
|
||||
tracks: Vec<(u32, usize, Vec<[f64; 2]>)>,
|
||||
/// Per frame: (track index, position).
|
||||
by_frame: Vec<Vec<(u32, [f64; 2])>>,
|
||||
/// Tracking noise scale (pixels).
|
||||
noise: f64,
|
||||
/// Tracking noise scale (pixels): starts from the analysis resolution and is re-estimated
|
||||
/// from the residuals once the keyframes are solved.
|
||||
noise_bits: std::sync::atomic::AtomicU64,
|
||||
}
|
||||
|
||||
impl Data {
|
||||
@@ -58,23 +59,31 @@ impl Data {
|
||||
}
|
||||
tracks.push((tr.id, tr.start as usize, pts));
|
||||
}
|
||||
Data { n, w: t.size[0], tracks, by_frame, noise: t.factor.max(1.0) }
|
||||
let noise = (0.5 * t.factor).max(0.5);
|
||||
Data { n, w: t.size[0], tracks, by_frame, noise_bits: std::sync::atomic::AtomicU64::new(noise.to_bits()) }
|
||||
}
|
||||
fn at(&self, ti: u32, k: usize) -> Option<[f64; 2]> {
|
||||
let (_, s, p) = &self.tracks[ti as usize];
|
||||
k.checked_sub(*s).and_then(|i| p.get(i).copied())
|
||||
}
|
||||
fn noise(&self) -> f64 {
|
||||
f64::from_bits(self.noise_bits.load(Ordering::Relaxed))
|
||||
}
|
||||
fn set_noise(&self, v: f64) {
|
||||
self.noise_bits.store(v.to_bits(), Ordering::Relaxed);
|
||||
}
|
||||
fn inlier_thr(&self) -> f64 {
|
||||
4.0 * self.noise
|
||||
4.0 * self.noise()
|
||||
}
|
||||
fn huber(&self) -> f64 {
|
||||
1.0 * self.noise
|
||||
self.noise()
|
||||
}
|
||||
}
|
||||
|
||||
/// Parallax-based keyframes: a new keyframe when the median feature motion since the last
|
||||
/// exceeds 3 % of the width, when fewer than 60 % of its features survive, or before the shared
|
||||
/// features drop below 24. The first and last frames with features are keyframes.
|
||||
/// exceeds 1.5 % of the width, when fewer than 70 % of its features survive, after 12 frames, or
|
||||
/// before the shared features drop below 24. The first and last frames with features are
|
||||
/// keyframes.
|
||||
fn keyframes(d: &Data) -> Vec<usize> {
|
||||
let Some(first) = (0..d.n).find(|k| d.by_frame[*k].len() >= 8) else { return vec![] };
|
||||
let mut kf = vec![first];
|
||||
@@ -97,7 +106,7 @@ fn keyframes(d: &Data) -> Vec<usize> {
|
||||
disp.sort_by(f64::total_cmp);
|
||||
let med = disp.get(disp.len() / 2).copied().unwrap_or(0.0);
|
||||
let ratio = disp.len() as f64 / base.len().max(1) as f64;
|
||||
if med > 0.03 * d.w || ratio < 0.6 || disp.len() < 24 {
|
||||
if med > 0.015 * d.w || ratio < 0.7 || disp.len() < 24 || j - last >= 12 {
|
||||
last = j;
|
||||
kf.push(j);
|
||||
}
|
||||
@@ -405,7 +414,7 @@ fn init_pair(d: &Data, a: usize, b: usize, f: f64, use_e: bool, use_h: bool) ->
|
||||
}
|
||||
let x1: Vec<[f64; 2]> = sh.iter().map(|s| [s.1[0] / f, s.1[1] / f]).collect();
|
||||
let x2: Vec<[f64; 2]> = sh.iter().map(|s| [s.2[0] / f, s.2[1] / f]).collect();
|
||||
let thr = 2.0 * d.noise / f;
|
||||
let thr = 2.0 * d.noise() / f;
|
||||
let mut cands: Vec<Pose> = vec![];
|
||||
if use_e && let Some((e, inl)) = geometry::ransac_essential(&x1, &x2, thr, 400, (a * 7919 + b) as u64) {
|
||||
let (p1, p2): (Vec<[f64; 2]>, Vec<[f64; 2]>) = (0..x1.len()).filter(|i| inl[*i]).map(|i| (x1[i], x2[i])).unzip();
|
||||
@@ -415,7 +424,7 @@ fn init_pair(d: &Data, a: usize, b: usize, f: f64, use_e: bool, use_h: bool) ->
|
||||
}
|
||||
if use_h {
|
||||
let (s1, s2): (Vec<[f64; 2]>, Vec<[f64; 2]>) = sh.iter().map(|s| (s.1, s.2)).unzip();
|
||||
if let Some(fit) = ransac(Model::Homography, &s1, &s2, 2.0 * d.noise, 500, (a * 31 + b) as u64) {
|
||||
if let Some(fit) = ransac(Model::Homography, &s1, &s2, 2.0 * d.noise(), 500, (a * 31 + b) as u64) {
|
||||
let h = fit.h.0;
|
||||
// Normalised: K⁻¹ H K with K = diag(f, f, 1).
|
||||
let hn = [[h[0][0], h[0][1], h[0][2] / f], [h[1][0], h[1][1], h[1][2] / f], [h[2][0] * f, h[2][1] * f, h[2][2]]];
|
||||
@@ -651,6 +660,12 @@ pub fn solve(tracks: &CameraTracks, s: &SolveSettings, cancel: Option<&AtomicBoo
|
||||
let try_general = matches!(s.method, SolveMethod::Auto | SolveMethod::Typical | SolveMethod::MostlyFlat);
|
||||
let try_tripod = matches!(s.method, SolveMethod::Auto | SolveMethod::TripodPan);
|
||||
|
||||
let t0 = web_time::Instant::now();
|
||||
let lap = |what: &str| {
|
||||
if debug() {
|
||||
eprintln!("{what}: {:.2} s", t0.elapsed().as_secs_f64());
|
||||
}
|
||||
};
|
||||
let mut results: Vec<(Attempt, f64)> = vec![];
|
||||
if try_general {
|
||||
let f = match fixed_f {
|
||||
@@ -666,7 +681,20 @@ pub fn solve(tracks: &CameraTracks, s: &SolveSettings, cancel: Option<&AtomicBoo
|
||||
results.push((a, f));
|
||||
}
|
||||
}
|
||||
if try_tripod && !cancelled() {
|
||||
lap("general");
|
||||
// Auto Detect: a quick tripod check at the general solve's focal length; when a rotation
|
||||
// clearly cannot explain the tracks, the tripod search is skipped.
|
||||
let tripod_plausible = match (s.method, results.first()) {
|
||||
(SolveMethod::Auto, Some((g, f))) => {
|
||||
let quick = tripod(&d, &mini, *f, &tcfg, cancel).map(|a| a.err).unwrap_or(f64::INFINITY);
|
||||
if debug() {
|
||||
eprintln!("quick tripod check: {quick:.3} vs general {:.3}", g.err);
|
||||
}
|
||||
quick <= 3.0 * g.err + d.noise()
|
||||
}
|
||||
_ => true,
|
||||
};
|
||||
if try_tripod && tripod_plausible && !cancelled() {
|
||||
let f = match fixed_f {
|
||||
Some(f) => f,
|
||||
None => search_focal(d.w, &|f| tripod(&d, &mini, f, &Cfg { per_frame_f: variable, ..tcfg }, cancel).map(|a| a.err).unwrap_or(f64::INFINITY)),
|
||||
@@ -696,7 +724,7 @@ pub fn solve(tracks: &CameraTracks, s: &SolveSettings, cancel: Option<&AtomicBoo
|
||||
if debug() {
|
||||
eprintln!("auto: general {eg:.4} tripod {et:.4} baseline/depth {:.4}", base / med);
|
||||
}
|
||||
if et <= (eg * 1.25).max(eg + 0.05 * d.noise) || base / med < 0.01 { t } else { g }
|
||||
if et <= (eg * 1.25).max(eg + 0.05 * d.noise()) || base / med < 0.01 { t } else { g }
|
||||
}
|
||||
(Some(g), None) => g,
|
||||
(None, Some(t)) => t,
|
||||
@@ -717,15 +745,44 @@ pub fn solve(tracks: &CameraTracks, s: &SolveSettings, cancel: Option<&AtomicBoo
|
||||
(None, true) => FocalMode::PerCamera(F_PRIOR),
|
||||
(None, false) => FocalMode::Shared,
|
||||
};
|
||||
lap("tripod");
|
||||
// Keyframes: adjust with the focal length free, reject, re-triangulate, adjust again.
|
||||
let kf_frames: Vec<usize> = r.cams.keys().copied().collect();
|
||||
r.adjust(&d, &kf_frames, &cfg, focal, 40);
|
||||
r.reject(&d);
|
||||
// Re-estimate the tracking noise from the inlier residuals (robustly, from their median:
|
||||
// for 2D Gaussian noise of deviation σ the median distance is 1.1774 σ), then tighten the
|
||||
// thresholds: observations of moving objects and occlusion edges become outliers.
|
||||
let mut res: Vec<f64> = vec![];
|
||||
for (k, c) in &r.cams {
|
||||
for (ti, uv) in &d.by_frame[*k] {
|
||||
if r.outliers.contains(&(*ti, *k)) {
|
||||
continue;
|
||||
}
|
||||
if let Some(e) = r.pts.get(ti).and_then(|x| bundle::residual(c, *x, *uv)) {
|
||||
res.push(e[0].hypot(e[1]));
|
||||
}
|
||||
}
|
||||
}
|
||||
if res.len() > 20 {
|
||||
res.sort_by(f64::total_cmp);
|
||||
let sigma = res[res.len() / 2] / 1.1774;
|
||||
let floor = 0.05 * tracks.factor.max(1.0);
|
||||
d.set_noise((1.5 * sigma).clamp(floor, d.noise()));
|
||||
if debug() {
|
||||
eprintln!("noise: σ {sigma:.3} → {:.3}", d.noise());
|
||||
}
|
||||
r.outliers.clear();
|
||||
r.reject(&d);
|
||||
}
|
||||
r.triangulate(&d, kind, 1.0, 1.0);
|
||||
r.adjust(&d, &kf_frames, &cfg, focal, 40);
|
||||
r.reject(&d);
|
||||
r.adjust(&d, &kf_frames, &cfg, focal, 20);
|
||||
if cancelled() {
|
||||
return err("cancelled");
|
||||
}
|
||||
lap("keyframe adjustment");
|
||||
// Every other frame: resect from the points (nearest registered camera first).
|
||||
let mut todo: Vec<usize> = (0..d.n).filter(|k| !r.cams.contains_key(k)).collect();
|
||||
todo.sort_by_key(|k| r.cams.keys().map(|c| c.abs_diff(*k)).min().unwrap_or(usize::MAX));
|
||||
@@ -746,6 +803,7 @@ pub fn solve(tracks: &CameraTracks, s: &SolveSettings, cancel: Option<&AtomicBoo
|
||||
if cancelled() {
|
||||
return err("cancelled");
|
||||
}
|
||||
lap("resection");
|
||||
// Points for the tracks that only lived between keyframes, then the final adjustment over
|
||||
// every frame (when that stays affordable).
|
||||
r.triangulate(&d, kind, 1.0, 1.0);
|
||||
@@ -786,6 +844,7 @@ pub fn solve(tracks: &CameraTracks, s: &SolveSettings, cancel: Option<&AtomicBoo
|
||||
}
|
||||
(m, _) => m,
|
||||
};
|
||||
lap("final adjustment");
|
||||
Ok(finish(&d, tracks, s, r, method, kind))
|
||||
}
|
||||
|
||||
|
||||
@@ -358,3 +358,81 @@ fn perf_long_clip() {
|
||||
eprintln!("300 frames, {} tracks: {:?} err {:.3} focal {:.1} in {:?}", tr.tracks.len(), s.method_used, s.average_error, s.focal(), t0.elapsed());
|
||||
assert!(s.average_error < 0.5);
|
||||
}
|
||||
|
||||
/// Solve tracks saved from the app (`EC_CAMTRACK_FILE=tracks.json cargo test -p effectcraft-track
|
||||
/// --release solve_saved_tracks -- --ignored --nocapture`): a debugging aid.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn solve_saved_tracks() {
|
||||
let Some(path) = std::env::var_os("EC_CAMTRACK_FILE") else { return };
|
||||
let mut tr = CameraTracks::from_json(&std::fs::read_to_string(path).unwrap()).unwrap();
|
||||
if let Some(maxy) = std::env::var("EC_CAMTRACK_MAXY").ok().and_then(|v| v.parse::<f32>().ok()) {
|
||||
tr.tracks.retain(|t| t.pts.iter().all(|p| p[1] < maxy));
|
||||
}
|
||||
let shot = if std::env::var_os("EC_CAMTRACK_VARIABLE").is_some() { ShotType::VariableZoom } else { ShotType::FixedAngle };
|
||||
let t0 = std::time::Instant::now();
|
||||
// With the true cameras (`[{pos, poi, zoom}]` per frame, two-node), how consistent are the
|
||||
// tracks themselves?
|
||||
if let Some(tp) = std::env::var_os("EC_CAMTRACK_TRUTH") {
|
||||
let v: Vec<serde_json::Value> = serde_json::from_str(&std::fs::read_to_string(tp).unwrap()).unwrap();
|
||||
let g = |x: &serde_json::Value| -> V3 { [x[0].as_f64().unwrap(), x[1].as_f64().unwrap(), x[2].as_f64().unwrap()] };
|
||||
let cams: Vec<(super::geometry::Pose, f64)> = v
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let (pos, poi) = (g(&c["pos"]), g(&c["poi"]));
|
||||
let fwd = normalize(sub(poi, pos));
|
||||
let d0 = [0.0, 1.0, 0.0];
|
||||
let down = normalize(sub(d0, scale(fwd, dot(d0, fwd))));
|
||||
let right = cross(down, fwd);
|
||||
(super::geometry::Pose { r: [right, down, fwd], c: pos }, c["zoom"].as_f64().unwrap())
|
||||
})
|
||||
.collect();
|
||||
let (w, h) = (tr.size[0], tr.size[1]);
|
||||
let mut means = vec![];
|
||||
let mut drop_ids = vec![];
|
||||
for t in &tr.tracks {
|
||||
let views: Vec<(super::geometry::Pose, [f64; 2])> = t
|
||||
.pts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, p)| {
|
||||
let (pose, z) = cams[t.start as usize + i];
|
||||
(pose, [(p[0] as f64 - w / 2.0) / z, (p[1] as f64 - h / 2.0) / z])
|
||||
})
|
||||
.collect();
|
||||
let Some(x) = super::geometry::triangulate(&views) else { continue };
|
||||
let e: Vec<f64> = views.iter().filter_map(|(p, o)| super::geometry::reproj2(p, x, *o).map(|e| e.sqrt() * cams[0].1)).collect();
|
||||
means.push((e.iter().sum::<f64>() / e.len().max(1) as f64, t.pts[0]));
|
||||
if std::env::var_os("EC_CAMTRACK_TRUTH_FILTER").is_some() && means.last().unwrap().0 > 1.0 {
|
||||
drop_ids.push(t.id);
|
||||
}
|
||||
}
|
||||
tr.tracks.retain(|t| !drop_ids.contains(&t.id));
|
||||
means.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
eprintln!(
|
||||
"true-camera track errors (px): median {:.2}; quartiles {:?}",
|
||||
means[means.len() / 2].0,
|
||||
[means[means.len() / 4].0, means[means.len() * 3 / 4].0]
|
||||
);
|
||||
for m in means.iter().step_by(6) {
|
||||
eprintln!(" {:.2} at {:?}", m.0, m.1);
|
||||
}
|
||||
}
|
||||
let mut st = settings(shot, SolveMethod::Auto);
|
||||
if let Some(a) = std::env::var("EC_CAMTRACK_AOV").ok().and_then(|v| v.parse::<f64>().ok()) {
|
||||
st.shot = ShotType::SpecifyAngle;
|
||||
st.hfov = a;
|
||||
}
|
||||
let s = solve(&tr, &st, None).expect("solve");
|
||||
eprintln!(
|
||||
"{} frames, {} tracks: {:?} err {:.3} focal {:.1} (hfov {:.1}) points {} in {:?}",
|
||||
tr.frames,
|
||||
tr.tracks.len(),
|
||||
s.method_used,
|
||||
s.average_error,
|
||||
s.focal(),
|
||||
s.hfov(s.focal()),
|
||||
s.points.len(),
|
||||
t0.elapsed()
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user