M12.3: tracker core
New L2 crate effectcraft-track: per-point feature/search region tracking with pyramid normalized cross-correlation and Lucas-Kanade (similarity + gain/bias) sub-pixel refinement, confidence, adapt/stop/extrapolate/continue actions, RGB/luminance/saturation channels, blur/enhance pre-processing, and homography/affine/similarity solves. Project: Motion Trackers > Tracker n > Track Point n property tree (GroupKind::Tracker with type, target and options). Engine: track.* commands (new/motion/stabilize/property/select/setType/setTarget/options/setPoint/ analyze/stop/apply/reset/delete/status), background or blocking analysis job with progress and cancel (one undo step), apply to Transform, Stabilize and Corner Pin. Renderer::layer_source for the tracker's frames. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
5273f1ba96
commit
243098a144
@@ -0,0 +1,626 @@
|
||||
//! Motion tracking, clean-room from textbook methods:
|
||||
//!
|
||||
//! - each **track point** has a *feature region* (the pattern to follow) and a *search region*
|
||||
//! (where to look for it in the next frame), as in After Effects' Tracker;
|
||||
//! - the pattern is located by **normalized cross-correlation** (Lewis, "Fast Normalized
|
||||
//! Cross-Correlation", 1995) searched **coarse to fine over an image pyramid**;
|
||||
//! - the integer match is refined to **sub-pixel** precision (and, optionally, the feature's
|
||||
//! rotation and scale) by **Lucas–Kanade** Gauss–Newton image alignment (Lucas & Kanade 1981;
|
||||
//! Baker & Matthews, "Lucas-Kanade 20 Years On", 2004) with a gain/bias photometric model;
|
||||
//! - **confidence** is the correlation of the template with the matched region, in percent;
|
||||
//! when it drops below a threshold the tracker continues, stops, extrapolates the motion or
|
||||
//! adapts the feature (re-samples the template), like AE's Motion Tracker Options.
|
||||
//!
|
||||
//! Only the pixels around each search region are converted and pre-processed, so tracking cost is
|
||||
//! independent of the frame size. Points are tracked in parallel and the coarse correlation search
|
||||
//! is parallel over candidate rows (rayon).
|
||||
//!
|
||||
//! Coordinates are *layer* pixels: the frame image's pixel `(i, j)` covers `[i, i+1) × [j, j+1)`
|
||||
//! after subtracting the frame's `offset` (see [`Frame`]).
|
||||
|
||||
pub mod plane;
|
||||
pub mod solve;
|
||||
|
||||
use effectcraft_raster::Image;
|
||||
use rayon::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub use plane::{Channel, Plane};
|
||||
pub use solve::{Homography, angle_and_length, unwrap_degrees};
|
||||
|
||||
/// What to do when a frame's confidence is below the threshold.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ConfidenceAction {
|
||||
/// Keep the match anyway.
|
||||
Continue,
|
||||
/// Stop the analysis before this frame.
|
||||
Stop,
|
||||
/// Ignore the match and continue the previous motion.
|
||||
Extrapolate,
|
||||
/// Keep the match and re-sample the feature from this frame.
|
||||
#[default]
|
||||
Adapt,
|
||||
}
|
||||
|
||||
impl ConfidenceAction {
|
||||
pub const ALL: [ConfidenceAction; 4] = [ConfidenceAction::Continue, ConfidenceAction::Stop, ConfidenceAction::Extrapolate, ConfidenceAction::Adapt];
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
ConfidenceAction::Continue => "Continue Tracking",
|
||||
ConfidenceAction::Stop => "Stop Tracking",
|
||||
ConfidenceAction::Extrapolate => "Extrapolate Motion",
|
||||
ConfidenceAction::Adapt => "Adapt Feature",
|
||||
}
|
||||
}
|
||||
pub fn from_name(s: &str) -> Option<ConfidenceAction> {
|
||||
let n = s.to_ascii_lowercase().replace([' ', '_', '-'], "");
|
||||
ConfidenceAction::ALL.into_iter().find(|a| {
|
||||
format!("{a:?}").to_ascii_lowercase() == n
|
||||
|| a.label().to_ascii_lowercase().replace(' ', "") == n
|
||||
|| a.label().to_ascii_lowercase().replace(' ', "").starts_with(&n)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Motion Tracker Options that affect matching.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct TrackOptions {
|
||||
pub channel: Channel,
|
||||
/// Pre-process blur radius in pixels (0 = off).
|
||||
pub blur: f64,
|
||||
/// Pre-process edge enhancement.
|
||||
pub enhance: bool,
|
||||
/// Sub-pixel positioning (else whole-pixel matches).
|
||||
pub subpixel: bool,
|
||||
/// Re-sample the feature on every frame.
|
||||
pub adapt_every_frame: bool,
|
||||
/// Confidence threshold in percent for `action`.
|
||||
pub threshold: f64,
|
||||
pub action: ConfidenceAction,
|
||||
/// Also estimate each feature's rotation and scale while matching (follows rotating or
|
||||
/// zooming features without adapting).
|
||||
pub track_shape: bool,
|
||||
}
|
||||
|
||||
impl Default for TrackOptions {
|
||||
fn default() -> Self {
|
||||
TrackOptions {
|
||||
channel: Channel::Luminance,
|
||||
blur: 0.0,
|
||||
enhance: false,
|
||||
subpixel: true,
|
||||
adapt_every_frame: false,
|
||||
threshold: 80.0,
|
||||
action: ConfidenceAction::Adapt,
|
||||
track_shape: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One track point's regions (layer pixels).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PointSpec {
|
||||
pub center: [f64; 2],
|
||||
/// Feature region width and height.
|
||||
pub feature_size: [f64; 2],
|
||||
/// Search region centre relative to the feature centre.
|
||||
pub search_offset: [f64; 2],
|
||||
/// Search region width and height.
|
||||
pub search_size: [f64; 2],
|
||||
}
|
||||
|
||||
/// A frame to track in: layer pixels map to image pixels by adding `offset`.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Frame<'a> {
|
||||
pub img: &'a Image,
|
||||
pub offset: [f64; 2],
|
||||
}
|
||||
|
||||
impl<'a> Frame<'a> {
|
||||
pub fn new(img: &'a Image) -> Frame<'a> {
|
||||
Frame { img, offset: [0.0; 2] }
|
||||
}
|
||||
}
|
||||
|
||||
/// How a point's position on a frame was obtained.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Status {
|
||||
Tracked,
|
||||
/// Tracked, and the feature was re-sampled from this frame.
|
||||
Adapted,
|
||||
/// Low confidence: the previous motion was continued.
|
||||
Extrapolated,
|
||||
/// Low confidence with the Stop action: no result for this frame.
|
||||
Stopped,
|
||||
}
|
||||
|
||||
/// A point's result on one frame.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PointResult {
|
||||
/// Feature centre (layer pixels).
|
||||
pub center: [f64; 2],
|
||||
/// Match confidence, 0–100 %.
|
||||
pub confidence: f64,
|
||||
/// Feature rotation (degrees) and scale (1 = start) relative to the start frame (when
|
||||
/// `track_shape` is on).
|
||||
pub rotation: f64,
|
||||
pub scale: f64,
|
||||
pub status: Status,
|
||||
}
|
||||
|
||||
/// A template sampled on a unit grid around the feature centre at one pyramid level.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Patch {
|
||||
r: [i32; 2],
|
||||
ch: usize,
|
||||
raw: Vec<f32>,
|
||||
/// Zero-mean values and their sum of squares.
|
||||
zm: Vec<f32>,
|
||||
ss: f64,
|
||||
}
|
||||
|
||||
impl Patch {
|
||||
fn sample(plane: &Plane, c: [f64; 2], a: [f64; 2], r: [i32; 2]) -> Patch {
|
||||
let ch = plane.ch;
|
||||
let mut raw = Vec::with_capacity(((2 * r[0] + 1) * (2 * r[1] + 1)) as usize * ch);
|
||||
let mut v = [0.0f32; 3];
|
||||
for gy in -r[1]..=r[1] {
|
||||
for gx in -r[0]..=r[0] {
|
||||
let (ux, uy) = (gx as f64, gy as f64);
|
||||
plane.sample(c[0] + a[0] * ux - a[1] * uy, c[1] + a[1] * ux + a[0] * uy, &mut v);
|
||||
raw.extend_from_slice(&v[..ch]);
|
||||
}
|
||||
}
|
||||
let mean = raw.iter().map(|x| *x as f64).sum::<f64>() / raw.len().max(1) as f64;
|
||||
let zm: Vec<f32> = raw.iter().map(|x| (*x as f64 - mean) as f32).collect();
|
||||
let ss = zm.iter().map(|x| (*x as f64) * (*x as f64)).sum();
|
||||
Patch { r, ch, raw, zm, ss }
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalized cross-correlation of `patch` with `plane` sampled at `c + A u` (A = similarity
|
||||
/// `[[a0, -a1], [a1, a0]]`). Pure translations share one set of bilinear weights.
|
||||
fn ncc(plane: &Plane, p: &Patch, c: [f64; 2], a: [f64; 2]) -> f64 {
|
||||
if p.ss <= 1e-12 {
|
||||
return 0.0;
|
||||
}
|
||||
let ch = p.ch;
|
||||
let (mut s, mut s2, mut st) = (0.0f64, 0.0f64, 0.0f64);
|
||||
let identity = (a[0] - 1.0).abs() < 1e-9 && a[1].abs() < 1e-9;
|
||||
let fx = c[0] - 0.5;
|
||||
let fy = c[1] - 0.5;
|
||||
let (bx, by) = (fx.floor(), fy.floor());
|
||||
let inside = bx as i64 - p.r[0] as i64 >= 0
|
||||
&& by as i64 - p.r[1] as i64 >= 0
|
||||
&& (bx as i64 + p.r[0] as i64 + 1) < plane.w as i64
|
||||
&& (by as i64 + p.r[1] as i64 + 1) < plane.h as i64;
|
||||
if identity && inside {
|
||||
let (tx, ty) = ((fx - bx) as f32, (fy - by) as f32);
|
||||
let (w00, w10, w01, w11) = ((1.0 - tx) * (1.0 - ty), tx * (1.0 - ty), (1.0 - tx) * ty, tx * ty);
|
||||
let row = plane.w * ch;
|
||||
let mut k = 0;
|
||||
for gy in -p.r[1]..=p.r[1] {
|
||||
let y = (by as i64 + gy as i64) as usize;
|
||||
let base = y * row;
|
||||
for gx in -p.r[0]..=p.r[0] {
|
||||
let x = (bx as i64 + gx as i64) as usize;
|
||||
let i00 = base + x * ch;
|
||||
for cc in 0..ch {
|
||||
let v =
|
||||
w00 * plane.data[i00 + cc] + w10 * plane.data[i00 + ch + cc] + w01 * plane.data[i00 + row + cc] + w11 * plane.data[i00 + row + ch + cc];
|
||||
let v = v as f64;
|
||||
s += v;
|
||||
s2 += v * v;
|
||||
st += v * p.zm[k] as f64;
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let mut v = [0.0f32; 3];
|
||||
let mut k = 0;
|
||||
for gy in -p.r[1]..=p.r[1] {
|
||||
for gx in -p.r[0]..=p.r[0] {
|
||||
let (ux, uy) = (gx as f64, gy as f64);
|
||||
plane.sample(c[0] + a[0] * ux - a[1] * uy, c[1] + a[1] * ux + a[0] * uy, &mut v);
|
||||
for cc in 0..ch {
|
||||
let x = v[cc] as f64;
|
||||
s += x;
|
||||
s2 += x * x;
|
||||
st += x * p.zm[k] as f64;
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let n = p.zm.len() as f64;
|
||||
let var = s2 - s * s / n;
|
||||
if var <= 1e-12 {
|
||||
return 0.0;
|
||||
}
|
||||
(st / (var * p.ss).sqrt()).clamp(-1.0, 1.0)
|
||||
}
|
||||
|
||||
/// The pre-processed pixels around one point: a pyramid of a crop. Plane coordinates are image
|
||||
/// pixels minus `origin`, divided by `2^level`.
|
||||
struct Crop {
|
||||
origin: [f64; 2],
|
||||
levels: Vec<Plane>,
|
||||
grad0: (Plane, Plane),
|
||||
}
|
||||
|
||||
impl Crop {
|
||||
/// Crop image pixels `[c - ext, c + ext]` (image pixel coordinates), pre-processed.
|
||||
fn new(frame: &Frame, opts: &TrackOptions, c: [f64; 2], ext: [f64; 2], levels: usize) -> Crop {
|
||||
let sigma = opts.blur.max(0.0) / 2.0;
|
||||
let margin = (sigma * 3.0).ceil() + 3.0 + if opts.enhance { 6.0 } else { 0.0 } + (1 << levels) as f64;
|
||||
let x0 = (c[0] - ext[0] - margin).floor();
|
||||
let y0 = (c[1] - ext[1] - margin).floor();
|
||||
let w = ((2.0 * (ext[0] + margin)).ceil() as usize + 2).max(4);
|
||||
let h = ((2.0 * (ext[1] + margin)).ceil() as usize + 2).max(4);
|
||||
let mut p = Plane::from_image(frame.img, opts.channel, x0 as i64, y0 as i64, w, h);
|
||||
if sigma > 0.05 {
|
||||
p = p.gaussian(sigma);
|
||||
}
|
||||
if opts.enhance {
|
||||
p = p.enhance();
|
||||
}
|
||||
let grad0 = p.gradients();
|
||||
let mut lv = vec![p];
|
||||
for _ in 0..levels {
|
||||
let d = lv.last().map(Plane::downsample).unwrap_or_default();
|
||||
lv.push(d);
|
||||
}
|
||||
Crop { origin: [x0, y0], levels: lv, grad0 }
|
||||
}
|
||||
fn to_level(&self, p: [f64; 2], k: usize) -> [f64; 2] {
|
||||
let s = (1u32 << k) as f64;
|
||||
[(p[0] - self.origin[0]) / s, (p[1] - self.origin[1]) / s]
|
||||
}
|
||||
fn level_to_image(&self, p: [f64; 2], k: usize) -> [f64; 2] {
|
||||
let s = (1u32 << k) as f64;
|
||||
[p[0] * s + self.origin[0], p[1] * s + self.origin[1]]
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-point tracking state.
|
||||
#[derive(Clone, Debug)]
|
||||
struct PointState {
|
||||
spec: PointSpec,
|
||||
/// Current centre in image pixels.
|
||||
center: [f64; 2],
|
||||
/// Current similarity `[s cos θ, s sin θ]` relative to the template's frame.
|
||||
shape: [f64; 2],
|
||||
velocity: [f64; 2],
|
||||
templates: Vec<Patch>,
|
||||
levels: usize,
|
||||
}
|
||||
|
||||
fn half(v: [f64; 2]) -> [f64; 2] {
|
||||
[(v[0] / 2.0).max(1.0), (v[1] / 2.0).max(1.0)]
|
||||
}
|
||||
|
||||
impl PointState {
|
||||
fn feature_r(&self) -> [i32; 2] {
|
||||
let h = half(self.spec.feature_size);
|
||||
[h[0].round().max(2.0) as i32, h[1].round().max(2.0) as i32]
|
||||
}
|
||||
fn level_r(&self, k: usize) -> [i32; 2] {
|
||||
let r = self.feature_r();
|
||||
let s = (1 << k) as f64;
|
||||
[((r[0] as f64 / s).ceil() as i32).max(2), ((r[1] as f64 / s).ceil() as i32).max(2)]
|
||||
}
|
||||
/// Search range around the predicted centre (pixels, per axis).
|
||||
fn range(&self) -> [f64; 2] {
|
||||
let f = half(self.spec.feature_size);
|
||||
let s = half(self.spec.search_size);
|
||||
[(s[0] - f[0]).max(2.0), (s[1] - f[1]).max(2.0)]
|
||||
}
|
||||
fn extent(&self) -> f64 {
|
||||
let r = self.feature_r();
|
||||
let s = (self.shape[0] * self.shape[0] + self.shape[1] * self.shape[1]).sqrt().max(1.0);
|
||||
((r[0] * r[0] + r[1] * r[1]) as f64).sqrt() * s + 2.0
|
||||
}
|
||||
|
||||
fn new(spec: PointSpec, frame: &Frame, opts: &TrackOptions) -> PointState {
|
||||
let c = [spec.center[0] + frame.offset[0], spec.center[1] + frame.offset[1]];
|
||||
let mut st = PointState { spec, center: c, shape: [1.0, 0.0], velocity: [0.0; 2], templates: vec![], levels: 0 };
|
||||
let range = st.range();
|
||||
let fr = st.feature_r();
|
||||
let mut l = 0;
|
||||
while l < 4 && range[0].min(range[1]) / (2u32 << l) as f64 >= 3.0 && (fr[0].min(fr[1]) as f64) / (2u32 << l) as f64 >= 3.0 {
|
||||
l += 1;
|
||||
}
|
||||
st.levels = l;
|
||||
let e = st.extent();
|
||||
let crop = Crop::new(frame, opts, c, [e, e], l);
|
||||
st.resample(&crop);
|
||||
st
|
||||
}
|
||||
|
||||
/// Re-sample the templates from `crop` at the current centre and shape.
|
||||
fn resample(&mut self, crop: &Crop) {
|
||||
self.templates = (0..=self.levels).map(|k| Patch::sample(&crop.levels[k], crop.to_level(self.center, k), self.shape, self.level_r(k))).collect();
|
||||
}
|
||||
|
||||
fn step(&mut self, frame: &Frame, opts: &TrackOptions) -> PointResult {
|
||||
let prev = self.center;
|
||||
let predicted = [prev[0] + self.velocity[0], prev[1] + self.velocity[1]];
|
||||
let sc = [predicted[0] + self.spec.search_offset[0], predicted[1] + self.spec.search_offset[1]];
|
||||
let range = self.range();
|
||||
let e = self.extent();
|
||||
let crop = Crop::new(frame, opts, sc, [range[0] + e, range[1] + e], self.levels);
|
||||
let top = self.levels;
|
||||
// Coarse: exhaustive correlation over the search range at the top level.
|
||||
let s = (1u32 << top) as f64;
|
||||
let ctop = crop.to_level(sc, top);
|
||||
let (rx, ry) = ((range[0] / s).ceil() as i32, (range[1] / s).ceil() as i32);
|
||||
let plane = &crop.levels[top];
|
||||
let tpl = &self.templates[top];
|
||||
let shape = self.shape;
|
||||
let mut cands: Vec<(f64, [f64; 2])> = (-ry..=ry)
|
||||
.into_par_iter()
|
||||
.flat_map_iter(|j| {
|
||||
(-rx..=rx).map(move |i| {
|
||||
let c = [ctop[0] + i as f64, ctop[1] + j as f64];
|
||||
(ncc(plane, tpl, c, shape), c)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
cands.sort_by(|a, b| b.0.total_cmp(&a.0));
|
||||
let mut seeds: Vec<[f64; 2]> = vec![];
|
||||
for (_, c) in &cands {
|
||||
if seeds.iter().all(|q| (q[0] - c[0]).abs() > 1.5 || (q[1] - c[1]).abs() > 1.5) {
|
||||
seeds.push(*c);
|
||||
}
|
||||
if seeds.len() == 3 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Fine: refine each seed down the pyramid in a 5 × 5 neighbourhood.
|
||||
let mut best = (f64::MIN, sc);
|
||||
for seed in seeds {
|
||||
let mut c = seed;
|
||||
let mut score = f64::MIN;
|
||||
for k in (0..top).rev() {
|
||||
c = [c[0] * 2.0, c[1] * 2.0];
|
||||
let (pl, tp) = (&crop.levels[k], &self.templates[k]);
|
||||
let mut lb = (f64::MIN, c);
|
||||
for j in -2..=2 {
|
||||
for i in -2..=2 {
|
||||
let q = [c[0] + i as f64, c[1] + j as f64];
|
||||
let v = ncc(pl, tp, q, shape);
|
||||
if v > lb.0 {
|
||||
lb = (v, q);
|
||||
}
|
||||
}
|
||||
}
|
||||
(score, c) = lb;
|
||||
}
|
||||
if top == 0 {
|
||||
score = ncc(&crop.levels[0], &self.templates[0], c, shape);
|
||||
}
|
||||
if score > best.0 {
|
||||
best = (score, crop.level_to_image(c, 0));
|
||||
}
|
||||
}
|
||||
let c0 = crop.to_level(best.1, 0);
|
||||
// Sub-pixel (and shape) refinement.
|
||||
let (mut c, mut a) = (c0, shape);
|
||||
if opts.subpixel {
|
||||
let mut ok = false;
|
||||
if opts.track_shape
|
||||
&& let Some((cr, ar)) = lk_refine(&crop, &self.templates[0], c0, shape, true)
|
||||
{
|
||||
(c, a) = (cr, ar);
|
||||
ok = true;
|
||||
}
|
||||
if !ok {
|
||||
if let Some((cr, _)) = lk_refine(&crop, &self.templates[0], c0, shape, false) {
|
||||
c = cr;
|
||||
} else {
|
||||
c = parabolic(&crop.levels[0], &self.templates[0], c0, shape);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut conf = ncc(&crop.levels[0], &self.templates[0], c, a);
|
||||
// Keep the coarse match if refinement made it worse.
|
||||
let coarse = ncc(&crop.levels[0], &self.templates[0], c0, shape);
|
||||
if coarse > conf + 0.02 {
|
||||
(c, a, conf) = (c0, shape, coarse);
|
||||
}
|
||||
let confidence = (conf.max(0.0) * 100.0).min(100.0);
|
||||
let found = crop.level_to_image(c, 0);
|
||||
let low = confidence < opts.threshold;
|
||||
let mut status = Status::Tracked;
|
||||
if low {
|
||||
match opts.action {
|
||||
ConfidenceAction::Stop => {
|
||||
return self.result(prev, frame, confidence, Status::Stopped);
|
||||
}
|
||||
ConfidenceAction::Extrapolate => {
|
||||
self.center = predicted;
|
||||
return self.result(predicted, frame, confidence, Status::Extrapolated);
|
||||
}
|
||||
ConfidenceAction::Continue => {}
|
||||
ConfidenceAction::Adapt => status = Status::Adapted,
|
||||
}
|
||||
}
|
||||
self.velocity = [found[0] - prev[0], found[1] - prev[1]];
|
||||
self.center = found;
|
||||
self.shape = a;
|
||||
if opts.adapt_every_frame || status == Status::Adapted {
|
||||
status = Status::Adapted;
|
||||
self.resample(&crop);
|
||||
}
|
||||
self.result(found, frame, confidence, status)
|
||||
}
|
||||
|
||||
fn result(&self, c: [f64; 2], frame: &Frame, confidence: f64, status: Status) -> PointResult {
|
||||
PointResult {
|
||||
center: [c[0] - frame.offset[0], c[1] - frame.offset[1]],
|
||||
confidence,
|
||||
rotation: self.shape[1].atan2(self.shape[0]).to_degrees(),
|
||||
scale: (self.shape[0] * self.shape[0] + self.shape[1] * self.shape[1]).sqrt(),
|
||||
status,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sub-pixel peak from 1-D parabola fits of the correlation around `c`.
|
||||
fn parabolic(plane: &Plane, p: &Patch, c: [f64; 2], a: [f64; 2]) -> [f64; 2] {
|
||||
let f = |dx: f64, dy: f64| ncc(plane, p, [c[0] + dx, c[1] + dy], a);
|
||||
let m = f(0.0, 0.0);
|
||||
let off = |l: f64, r: f64| {
|
||||
let d = l - 2.0 * m + r;
|
||||
if d.abs() < 1e-12 { 0.0 } else { (0.5 * (l - r) / d).clamp(-0.5, 0.5) }
|
||||
};
|
||||
[c[0] + off(f(-1.0, 0.0), f(1.0, 0.0)), c[1] + off(f(0.0, -1.0), f(0.0, 1.0))]
|
||||
}
|
||||
|
||||
/// Forward-additive Lucas–Kanade (Gauss–Newton) alignment of the level-0 template with gain and
|
||||
/// bias: minimise Σ (I(c + A u) − g T(u) − b)² over the centre `c` and, with `shape`, the
|
||||
/// similarity `A`. Returns `None` when it diverges.
|
||||
fn lk_refine(crop: &Crop, p: &Patch, c0: [f64; 2], a0: [f64; 2], shape: bool) -> Option<([f64; 2], [f64; 2])> {
|
||||
let plane = &crop.levels[0];
|
||||
let (gxp, gyp) = &crop.grad0;
|
||||
let ch = p.ch;
|
||||
let (mut c, mut a) = (c0, a0);
|
||||
let mut g = 1.0f64;
|
||||
let mut b;
|
||||
// Initial photometric estimate from means/variances.
|
||||
{
|
||||
let mut v = [0.0f32; 3];
|
||||
let (mut si, mut si2, mut st, mut st2, mut n) = (0.0, 0.0, 0.0, 0.0, 0.0);
|
||||
let mut k = 0;
|
||||
for gy in -p.r[1]..=p.r[1] {
|
||||
for gx in -p.r[0]..=p.r[0] {
|
||||
let (ux, uy) = (gx as f64, gy as f64);
|
||||
plane.sample(c[0] + a[0] * ux - a[1] * uy, c[1] + a[1] * ux + a[0] * uy, &mut v);
|
||||
for cc in 0..ch {
|
||||
let (i, t) = (v[cc] as f64, p.raw[k] as f64);
|
||||
si += i;
|
||||
si2 += i * i;
|
||||
st += t;
|
||||
st2 += t * t;
|
||||
n += 1.0;
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let (mi, mt) = (si / n, st / n);
|
||||
let (vi, vt) = ((si2 / n - mi * mi).max(0.0), (st2 / n - mt * mt).max(0.0));
|
||||
if vt > 1e-12 && vi > 1e-12 {
|
||||
g = (vi / vt).sqrt();
|
||||
}
|
||||
b = mi - g * mt;
|
||||
}
|
||||
let np = if shape { 6 } else { 4 };
|
||||
let (mut v, mut vx, mut vy) = ([0.0f32; 3], [0.0f32; 3], [0.0f32; 3]);
|
||||
for _ in 0..30 {
|
||||
let mut h = [[0.0f64; 6]; 6];
|
||||
let mut rhs = [0.0f64; 6];
|
||||
let mut k = 0;
|
||||
for gy in -p.r[1]..=p.r[1] {
|
||||
for gx in -p.r[0]..=p.r[0] {
|
||||
let (ux, uy) = (gx as f64, gy as f64);
|
||||
let q = [c[0] + a[0] * ux - a[1] * uy, c[1] + a[1] * ux + a[0] * uy];
|
||||
plane.sample(q[0], q[1], &mut v);
|
||||
gxp.sample(q[0], q[1], &mut vx);
|
||||
gyp.sample(q[0], q[1], &mut vy);
|
||||
for cc in 0..ch {
|
||||
let t = p.raw[k] as f64;
|
||||
k += 1;
|
||||
let (ix, iy) = (vx[cc] as f64, vy[cc] as f64);
|
||||
let r = v[cc] as f64 - g * t - b;
|
||||
let j: [f64; 6] = if shape { [ix, iy, ix * ux + iy * uy, -ix * uy + iy * ux, -t, -1.0] } else { [ix, iy, -t, -1.0, 0.0, 0.0] };
|
||||
for m in 0..np {
|
||||
rhs[m] -= j[m] * r;
|
||||
for n in m..np {
|
||||
h[m][n] += j[m] * j[n];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for m in 0..np {
|
||||
for n in 0..m {
|
||||
h[m][n] = h[n][m];
|
||||
}
|
||||
h[m][m] *= 1.0 + 1e-6;
|
||||
h[m][m] += 1e-9;
|
||||
}
|
||||
let d = if shape {
|
||||
solve::solve_linear(h, rhs)?
|
||||
} else {
|
||||
let hh = [
|
||||
[h[0][0], h[0][1], h[0][2], h[0][3]],
|
||||
[h[1][0], h[1][1], h[1][2], h[1][3]],
|
||||
[h[2][0], h[2][1], h[2][2], h[2][3]],
|
||||
[h[3][0], h[3][1], h[3][2], h[3][3]],
|
||||
];
|
||||
let x = solve::solve_linear(hh, [rhs[0], rhs[1], rhs[2], rhs[3]])?;
|
||||
[x[0], x[1], 0.0, 0.0, x[2], x[3]]
|
||||
};
|
||||
// Limit a single step (Gauss-Newton overshoot on poorly textured features).
|
||||
let step = (d[0] * d[0] + d[1] * d[1]).sqrt();
|
||||
let k = if step > 1.0 { 1.0 / step } else { 1.0 };
|
||||
c[0] += d[0] * k;
|
||||
c[1] += d[1] * k;
|
||||
if shape {
|
||||
a[0] += d[2] * k;
|
||||
a[1] += d[3] * k;
|
||||
}
|
||||
g += d[4] * k;
|
||||
b += d[5] * k;
|
||||
if !(c[0].is_finite() && c[1].is_finite() && a[0].is_finite() && a[1].is_finite()) {
|
||||
return None;
|
||||
}
|
||||
if step < 1e-4 && (!shape || (d[2].abs() + d[3].abs()) < 1e-6) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let moved = ((c[0] - c0[0]).powi(2) + (c[1] - c0[1]).powi(2)).sqrt();
|
||||
let s0 = (a0[0] * a0[0] + a0[1] * a0[1]).sqrt();
|
||||
let s1 = (a[0] * a[0] + a[1] * a[1]).sqrt();
|
||||
if moved > 2.5 || !(0.75..=1.33).contains(&(s1 / s0.max(1e-9))) || g <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
Some((c, a))
|
||||
}
|
||||
|
||||
/// Tracks a set of points frame by frame (the points of one tracker).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Tracker {
|
||||
pub opts: TrackOptions,
|
||||
points: Vec<PointState>,
|
||||
}
|
||||
|
||||
impl Tracker {
|
||||
/// Start tracking `points` as they appear on `frame` (the start frame).
|
||||
pub fn new(opts: TrackOptions, points: &[PointSpec], frame: &Frame) -> Tracker {
|
||||
let pts = points.par_iter().map(|s| PointState::new(*s, frame, &opts)).collect();
|
||||
Tracker { opts, points: pts }
|
||||
}
|
||||
|
||||
/// Track every point into the next frame (in either time direction).
|
||||
pub fn step(&mut self, frame: &Frame) -> Vec<PointResult> {
|
||||
let opts = &self.opts;
|
||||
self.points.par_iter_mut().map(|p| p.step(frame, opts)).collect()
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.points.len()
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.points.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,243 @@
|
||||
//! Single- or multi-channel float planes: the tracker's working images (a crop of the frame in
|
||||
//! the matching channel, pre-processed), their pyramids and bilinear sampling.
|
||||
//!
|
||||
//! Continuous coordinates follow the raster crate: pixel `i` covers `[i, i + 1)` and its centre is
|
||||
//! at `i + 0.5`. Downsampling by 2 keeps that convention (level-1 coordinate = level-0 / 2).
|
||||
|
||||
use effectcraft_raster::Image;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// What the tracker compares (Motion Tracker Options ▸ Channel).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Channel {
|
||||
/// All three colour channels.
|
||||
Rgb,
|
||||
/// Rec. 709 luma.
|
||||
#[default]
|
||||
Luminance,
|
||||
/// HSV saturation.
|
||||
Saturation,
|
||||
}
|
||||
|
||||
impl Channel {
|
||||
pub const ALL: [Channel; 3] = [Channel::Rgb, Channel::Luminance, Channel::Saturation];
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Channel::Rgb => "RGB",
|
||||
Channel::Luminance => "Luminance",
|
||||
Channel::Saturation => "Saturation",
|
||||
}
|
||||
}
|
||||
pub fn from_name(s: &str) -> Option<Channel> {
|
||||
Channel::ALL.into_iter().find(|c| c.label().eq_ignore_ascii_case(s) || format!("{c:?}").eq_ignore_ascii_case(s))
|
||||
}
|
||||
pub fn channels(self) -> usize {
|
||||
if self == Channel::Rgb { 3 } else { 1 }
|
||||
}
|
||||
}
|
||||
|
||||
/// An interleaved float plane.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Plane {
|
||||
pub w: usize,
|
||||
pub h: usize,
|
||||
pub ch: usize,
|
||||
pub data: Vec<f32>,
|
||||
}
|
||||
|
||||
impl Plane {
|
||||
pub fn new(w: usize, h: usize, ch: usize) -> Plane {
|
||||
Plane { w, h, ch, data: vec![0.0; w * h * ch] }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn idx(&self, x: usize, y: usize) -> usize {
|
||||
(y * self.w + x) * self.ch
|
||||
}
|
||||
|
||||
/// Value at integer pixel `(x, y)` with edges repeated.
|
||||
#[inline]
|
||||
pub fn at(&self, x: isize, y: isize, c: usize) -> f32 {
|
||||
let x = x.clamp(0, self.w as isize - 1) as usize;
|
||||
let y = y.clamp(0, self.h as isize - 1) as usize;
|
||||
self.data[self.idx(x, y) + c]
|
||||
}
|
||||
|
||||
/// Bilinear sample at continuous coordinates (edges repeated) into `out[..ch]`.
|
||||
#[inline]
|
||||
pub fn sample(&self, x: f64, y: f64, out: &mut [f32]) {
|
||||
let fx = x - 0.5;
|
||||
let fy = y - 0.5;
|
||||
let x0 = fx.floor();
|
||||
let y0 = fy.floor();
|
||||
let tx = (fx - x0) as f32;
|
||||
let ty = (fy - y0) as f32;
|
||||
let (x0, y0) = (x0 as isize, y0 as isize);
|
||||
let inside = x0 >= 0 && y0 >= 0 && (x0 as usize) + 1 < self.w && (y0 as usize) + 1 < self.h;
|
||||
if inside {
|
||||
let i00 = self.idx(x0 as usize, y0 as usize);
|
||||
let i10 = i00 + self.ch;
|
||||
let i01 = i00 + self.w * self.ch;
|
||||
let i11 = i01 + self.ch;
|
||||
for c in 0..self.ch {
|
||||
let top = self.data[i00 + c] + (self.data[i10 + c] - self.data[i00 + c]) * tx;
|
||||
let bot = self.data[i01 + c] + (self.data[i11 + c] - self.data[i01 + c]) * tx;
|
||||
out[c] = top + (bot - top) * ty;
|
||||
}
|
||||
} else {
|
||||
for c in 0..self.ch {
|
||||
let a = self.at(x0, y0, c);
|
||||
let b = self.at(x0 + 1, y0, c);
|
||||
let cc = self.at(x0, y0 + 1, c);
|
||||
let d = self.at(x0 + 1, y0 + 1, c);
|
||||
let top = a + (b - a) * tx;
|
||||
let bot = cc + (d - cc) * tx;
|
||||
out[c] = top + (bot - top) * ty;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Crop `w × h` pixels at `(x0, y0)` of `img` in the given channel (edges repeated outside).
|
||||
pub fn from_image(img: &Image, channel: Channel, x0: i64, y0: i64, w: usize, h: usize) -> Plane {
|
||||
let ch = channel.channels();
|
||||
let mut p = Plane::new(w, h, ch);
|
||||
if img.is_empty() {
|
||||
return p;
|
||||
}
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let px = img.get_clamped(x0 + x as i64, y0 + y as i64);
|
||||
let i = (y * w + x) * ch;
|
||||
match channel {
|
||||
Channel::Rgb => p.data[i..i + 3].copy_from_slice(&px[..3]),
|
||||
Channel::Luminance => p.data[i] = 0.2126 * px[0] + 0.7152 * px[1] + 0.0722 * px[2],
|
||||
Channel::Saturation => {
|
||||
let mx = px[0].max(px[1]).max(px[2]);
|
||||
let mn = px[0].min(px[1]).min(px[2]);
|
||||
p.data[i] = if mx > 1e-6 { (mx - mn) / mx } else { 0.0 };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// Separable Gaussian blur (edges repeated).
|
||||
pub fn gaussian(&self, sigma: f64) -> Plane {
|
||||
if sigma <= 0.05 {
|
||||
return self.clone();
|
||||
}
|
||||
let r = (sigma * 3.0).ceil() as isize;
|
||||
let mut k: Vec<f32> = (-r..=r).map(|i| (-(i * i) as f64 / (2.0 * sigma * sigma)).exp() as f32).collect();
|
||||
let s: f32 = k.iter().sum();
|
||||
k.iter_mut().for_each(|v| *v /= s);
|
||||
let mut tmp = Plane::new(self.w, self.h, self.ch);
|
||||
for y in 0..self.h {
|
||||
for x in 0..self.w {
|
||||
for c in 0..self.ch {
|
||||
let mut acc = 0.0;
|
||||
for (j, kv) in k.iter().enumerate() {
|
||||
acc += kv * self.at(x as isize + j as isize - r, y as isize, c);
|
||||
}
|
||||
let i = tmp.idx(x, y) + c;
|
||||
tmp.data[i] = acc;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = Plane::new(self.w, self.h, self.ch);
|
||||
for y in 0..self.h {
|
||||
for x in 0..self.w {
|
||||
for c in 0..self.ch {
|
||||
let mut acc = 0.0;
|
||||
for (j, kv) in k.iter().enumerate() {
|
||||
acc += kv * tmp.at(x as isize, y as isize + j as isize - r, c);
|
||||
}
|
||||
let i = out.idx(x, y) + c;
|
||||
out.data[i] = acc;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Edge enhancement (unsharp mask): `x + 2 (x - blur(x))`.
|
||||
pub fn enhance(&self) -> Plane {
|
||||
let b = self.gaussian(1.5);
|
||||
let mut out = self.clone();
|
||||
for (o, (x, y)) in out.data.iter_mut().zip(self.data.iter().zip(&b.data)) {
|
||||
*o = x + 2.0 * (x - y);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Half resolution (2 × 2 box average; odd sizes round up with the edge repeated).
|
||||
pub fn downsample(&self) -> Plane {
|
||||
let w = self.w.div_ceil(2).max(1);
|
||||
let h = self.h.div_ceil(2).max(1);
|
||||
let mut out = Plane::new(w, h, self.ch);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
for c in 0..self.ch {
|
||||
let (sx, sy) = (2 * x as isize, 2 * y as isize);
|
||||
let v = self.at(sx, sy, c) + self.at(sx + 1, sy, c) + self.at(sx, sy + 1, c) + self.at(sx + 1, sy + 1, c);
|
||||
let i = out.idx(x, y) + c;
|
||||
out.data[i] = v * 0.25;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Central-difference gradients `(d/dx, d/dy)`.
|
||||
pub fn gradients(&self) -> (Plane, Plane) {
|
||||
let mut gx = Plane::new(self.w, self.h, self.ch);
|
||||
let mut gy = Plane::new(self.w, self.h, self.ch);
|
||||
for y in 0..self.h {
|
||||
for x in 0..self.w {
|
||||
for c in 0..self.ch {
|
||||
let (xi, yi) = (x as isize, y as isize);
|
||||
let i = self.idx(x, y) + c;
|
||||
gx.data[i] = 0.5 * (self.at(xi + 1, yi, c) - self.at(xi - 1, yi, c));
|
||||
gy.data[i] = 0.5 * (self.at(xi, yi + 1, c) - self.at(xi, yi - 1, c));
|
||||
}
|
||||
}
|
||||
}
|
||||
(gx, gy)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sampling_and_pyramid_share_coordinates() {
|
||||
let mut p = Plane::new(8, 8, 1);
|
||||
for y in 0..8 {
|
||||
for x in 0..8 {
|
||||
p.data[y * 8 + x] = x as f32 + 10.0 * y as f32;
|
||||
}
|
||||
}
|
||||
let mut o = [0.0];
|
||||
p.sample(2.5, 3.5, &mut o);
|
||||
assert_eq!(o[0], 32.0);
|
||||
p.sample(3.0, 3.5, &mut o);
|
||||
assert!((o[0] - 32.5).abs() < 1e-6);
|
||||
// A linear ramp keeps its value at matching coordinates on the next level.
|
||||
let d = p.downsample();
|
||||
d.sample(1.5, 1.5, &mut o);
|
||||
let mut o0 = [0.0];
|
||||
p.sample(3.0, 3.0, &mut o0);
|
||||
assert!((o[0] - o0[0]).abs() < 1e-5, "{} vs {}", o[0], o0[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channels() {
|
||||
let img = Image::filled(2, 2, [1.0, 0.5, 0.0, 1.0]);
|
||||
assert_eq!(Plane::from_image(&img, Channel::Rgb, 0, 0, 2, 2).data[..3], [1.0, 0.5, 0.0]);
|
||||
assert!((Plane::from_image(&img, Channel::Luminance, 0, 0, 2, 2).data[0] - (0.2126 + 0.3576)).abs() < 1e-6);
|
||||
assert_eq!(Plane::from_image(&img, Channel::Saturation, 0, 0, 2, 2).data[0], 1.0);
|
||||
assert_eq!(Channel::from_name("luminance"), Some(Channel::Luminance));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
//! Small geometric solves for applying tracks: a 2-point similarity (Transform track rotation and
|
||||
//! scale), a 3-point affine (Affine Corner Pin) and a 4-point homography (Perspective Corner Pin,
|
||||
//! the direct linear transform with `h33 = 1`, Hartley & Zisserman §4.1).
|
||||
|
||||
/// Solve `a x = b` (n × n, row-major) by Gaussian elimination with partial pivoting.
|
||||
pub fn solve_linear<const N: usize>(mut a: [[f64; N]; N], mut b: [f64; N]) -> Option<[f64; N]> {
|
||||
for col in 0..N {
|
||||
let piv = (col..N).max_by(|&i, &j| a[i][col].abs().total_cmp(&a[j][col].abs()))?;
|
||||
if a[piv][col].abs() < 1e-12 {
|
||||
return None;
|
||||
}
|
||||
a.swap(col, piv);
|
||||
b.swap(col, piv);
|
||||
for r in col + 1..N {
|
||||
let f = a[r][col] / a[col][col];
|
||||
if f == 0.0 {
|
||||
continue;
|
||||
}
|
||||
for c in col..N {
|
||||
a[r][c] -= f * a[col][c];
|
||||
}
|
||||
b[r] -= f * b[col];
|
||||
}
|
||||
}
|
||||
let mut x = [0.0; N];
|
||||
for r in (0..N).rev() {
|
||||
let mut s = b[r];
|
||||
for c in r + 1..N {
|
||||
s -= a[r][c] * x[c];
|
||||
}
|
||||
x[r] = s / a[r][r];
|
||||
}
|
||||
x.iter().all(|v| v.is_finite()).then_some(x)
|
||||
}
|
||||
|
||||
/// A 3 × 3 projective transform (row-major), mapping `[x, y, 1]`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Homography(pub [[f64; 3]; 3]);
|
||||
|
||||
impl Homography {
|
||||
pub const IDENTITY: Homography = Homography([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]);
|
||||
|
||||
pub fn apply(&self, p: [f64; 2]) -> [f64; 2] {
|
||||
let m = &self.0;
|
||||
let w = m[2][0] * p[0] + m[2][1] * p[1] + m[2][2];
|
||||
let w = if w.abs() < 1e-12 { 1e-12 } else { w };
|
||||
[(m[0][0] * p[0] + m[0][1] * p[1] + m[0][2]) / w, (m[1][0] * p[0] + m[1][1] * p[1] + m[1][2]) / w]
|
||||
}
|
||||
|
||||
/// The homography taking `src[i]` to `dst[i]` (four points, no three collinear).
|
||||
pub fn from_points(src: [[f64; 2]; 4], dst: [[f64; 2]; 4]) -> Option<Homography> {
|
||||
// Normalise both sets (centroid at 0, mean distance √2) for conditioning.
|
||||
let (ns, ts) = normalise(&src);
|
||||
let (nd, td) = normalise(&dst);
|
||||
let mut a = [[0.0; 8]; 8];
|
||||
let mut b = [0.0; 8];
|
||||
for i in 0..4 {
|
||||
let ([x, y], [u, v]) = (ns[i], nd[i]);
|
||||
a[2 * i] = [x, y, 1.0, 0.0, 0.0, 0.0, -u * x, -u * y];
|
||||
b[2 * i] = u;
|
||||
a[2 * i + 1] = [0.0, 0.0, 0.0, x, y, 1.0, -v * x, -v * y];
|
||||
b[2 * i + 1] = v;
|
||||
}
|
||||
let h = solve_linear(a, b)?;
|
||||
let hn = [[h[0], h[1], h[2]], [h[3], h[4], h[5]], [h[6], h[7], 1.0]];
|
||||
// H = Td⁻¹ · Hn · Ts
|
||||
let m = mul(inv_similarity(td), mul(hn, ts));
|
||||
let s = m[2][2];
|
||||
if s.abs() < 1e-12 {
|
||||
return None;
|
||||
}
|
||||
Some(Homography(m.map(|r| r.map(|v| v / s))))
|
||||
}
|
||||
|
||||
/// The affine map taking three points to three points.
|
||||
pub fn affine_from_points(src: [[f64; 2]; 3], dst: [[f64; 2]; 3]) -> Option<Homography> {
|
||||
let mut a = [[0.0; 3]; 3];
|
||||
for i in 0..3 {
|
||||
a[i] = [src[i][0], src[i][1], 1.0];
|
||||
}
|
||||
let x = solve_linear(a, [dst[0][0], dst[1][0], dst[2][0]])?;
|
||||
let y = solve_linear(a, [dst[0][1], dst[1][1], dst[2][1]])?;
|
||||
Some(Homography([x, y, [0.0, 0.0, 1.0]]))
|
||||
}
|
||||
|
||||
/// The similarity (rotation, uniform scale, translation) taking two points to two points.
|
||||
pub fn similarity_from_points(src: [[f64; 2]; 2], dst: [[f64; 2]; 2]) -> Option<Homography> {
|
||||
let (ds, dd) = (sub(src[1], src[0]), sub(dst[1], dst[0]));
|
||||
let n = ds[0] * ds[0] + ds[1] * ds[1];
|
||||
if n < 1e-12 {
|
||||
return None;
|
||||
}
|
||||
// dd = [[a, -b], [b, a]] ds
|
||||
let a = (dd[0] * ds[0] + dd[1] * ds[1]) / n;
|
||||
let b = (dd[1] * ds[0] - dd[0] * ds[1]) / n;
|
||||
let tx = dst[0][0] - (a * src[0][0] - b * src[0][1]);
|
||||
let ty = dst[0][1] - (b * src[0][0] + a * src[0][1]);
|
||||
Some(Homography([[a, -b, tx], [b, a, ty], [0.0, 0.0, 1.0]]))
|
||||
}
|
||||
}
|
||||
|
||||
/// Angle (degrees, y down = clockwise positive like After Effects' Rotation) and length of `b - a`.
|
||||
pub fn angle_and_length(a: [f64; 2], b: [f64; 2]) -> (f64, f64) {
|
||||
let d = sub(b, a);
|
||||
(d[1].atan2(d[0]).to_degrees(), (d[0] * d[0] + d[1] * d[1]).sqrt())
|
||||
}
|
||||
|
||||
/// `angle` moved by multiples of 360° to be closest to `prev` (continuous rotation curves).
|
||||
pub fn unwrap_degrees(prev: f64, angle: f64) -> f64 {
|
||||
angle + ((prev - angle) / 360.0).round() * 360.0
|
||||
}
|
||||
|
||||
fn sub(a: [f64; 2], b: [f64; 2]) -> [f64; 2] {
|
||||
[a[0] - b[0], a[1] - b[1]]
|
||||
}
|
||||
|
||||
fn mul(a: [[f64; 3]; 3], b: [[f64; 3]; 3]) -> [[f64; 3]; 3] {
|
||||
let mut o = [[0.0; 3]; 3];
|
||||
for i in 0..3 {
|
||||
for j in 0..3 {
|
||||
o[i][j] = (0..3).map(|k| a[i][k] * b[k][j]).sum();
|
||||
}
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
fn normalise(p: &[[f64; 2]; 4]) -> ([[f64; 2]; 4], [[f64; 3]; 3]) {
|
||||
let c = [p.iter().map(|q| q[0]).sum::<f64>() / 4.0, p.iter().map(|q| q[1]).sum::<f64>() / 4.0];
|
||||
let d = p.iter().map(|q| ((q[0] - c[0]).powi(2) + (q[1] - c[1]).powi(2)).sqrt()).sum::<f64>() / 4.0;
|
||||
let s = if d > 1e-12 { std::f64::consts::SQRT_2 / d } else { 1.0 };
|
||||
let t = [[s, 0.0, -s * c[0]], [0.0, s, -s * c[1]], [0.0, 0.0, 1.0]];
|
||||
(p.map(|q| [s * (q[0] - c[0]), s * (q[1] - c[1])]), t)
|
||||
}
|
||||
|
||||
fn inv_similarity(t: [[f64; 3]; 3]) -> [[f64; 3]; 3] {
|
||||
let s = t[0][0];
|
||||
[[1.0 / s, 0.0, -t[0][2] / s], [0.0, 1.0 / s, -t[1][2] / s], [0.0, 0.0, 1.0]]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn close(a: [f64; 2], b: [f64; 2], tol: f64) -> bool {
|
||||
(a[0] - b[0]).abs() < tol && (a[1] - b[1]).abs() < tol
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn homography_recovers_known_projection() {
|
||||
let h = Homography([[0.9, 0.12, 30.0], [-0.08, 1.1, -12.0], [0.0004, -0.0002, 1.0]]);
|
||||
let src = [[100.0, 100.0], [700.0, 120.0], [680.0, 500.0], [90.0, 520.0]];
|
||||
let dst = src.map(|p| h.apply(p));
|
||||
let got = Homography::from_points(src, dst).unwrap();
|
||||
for i in 0..3 {
|
||||
for j in 0..3 {
|
||||
assert!((got.0[i][j] - h.0[i][j]).abs() < 1e-6 * (1.0 + h.0[i][j].abs()), "{:?}", got.0);
|
||||
}
|
||||
}
|
||||
for p in [[0.0, 0.0], [400.0, 300.0], [1000.0, 50.0]] {
|
||||
assert!(close(got.apply(p), h.apply(p), 1e-6));
|
||||
}
|
||||
// Degenerate (collinear) input has no solution.
|
||||
assert!(Homography::from_points([[0.0, 0.0], [1.0, 1.0], [2.0, 2.0], [3.0, 3.0]], dst).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn affine_and_similarity() {
|
||||
let a = Homography::affine_from_points([[0.0, 0.0], [10.0, 0.0], [0.0, 10.0]], [[5.0, 5.0], [15.0, 7.0], [3.0, 15.0]]).unwrap();
|
||||
assert!(close(a.apply([10.0, 10.0]), [13.0, 17.0], 1e-9));
|
||||
let s = Homography::similarity_from_points([[0.0, 0.0], [10.0, 0.0]], [[1.0, 1.0], [1.0, 21.0]]).unwrap();
|
||||
assert!(close(s.apply([0.0, 10.0]), [-19.0, 1.0], 1e-9));
|
||||
let (ang, len) = angle_and_length([1.0, 1.0], [1.0, 21.0]);
|
||||
assert!((ang - 90.0).abs() < 1e-9 && (len - 20.0).abs() < 1e-9);
|
||||
assert!((unwrap_degrees(350.0, -5.0) - 355.0).abs() < 1e-9);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
//! Synthetic footage: a textured patch moving along a known path (with rotation and scale) over a
|
||||
//! textured background, with noise. Ground truth is exact, so recovered positions are compared
|
||||
//! against it directly.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Smooth, band-limited texture (periods of 9–40 px).
|
||||
fn texture(x: f64, y: f64, seed: u32) -> [f32; 3] {
|
||||
let mut v = [0.0f64; 3];
|
||||
let mut s = seed.wrapping_mul(2654435761).wrapping_add(12345);
|
||||
let mut rnd = || {
|
||||
s ^= s << 13;
|
||||
s ^= s >> 17;
|
||||
s ^= s << 5;
|
||||
(s % 10_000) as f64 / 10_000.0
|
||||
};
|
||||
for _ in 0..7 {
|
||||
let ang = rnd() * std::f64::consts::TAU;
|
||||
let period = 9.0 + rnd() * 31.0;
|
||||
let phase = rnd() * std::f64::consts::TAU;
|
||||
let k = std::f64::consts::TAU / period;
|
||||
let w = (k * (x * ang.cos() + y * ang.sin()) + phase).sin();
|
||||
let c = [rnd(), rnd(), rnd()];
|
||||
for i in 0..3 {
|
||||
v[i] += w * (0.3 + c[i]) * 0.12;
|
||||
}
|
||||
}
|
||||
v.map(|q| (0.5 + q).clamp(0.0, 1.0) as f32)
|
||||
}
|
||||
|
||||
fn noise(x: u32, y: u32, f: u32) -> f32 {
|
||||
effectcraft_raster::hash_noise(x, y.wrapping_add(f.wrapping_mul(7919)), 99) - 0.5
|
||||
}
|
||||
|
||||
/// Patch pose on a frame: centre, rotation (degrees), scale.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Pose {
|
||||
c: [f64; 2],
|
||||
rot: f64,
|
||||
scale: f64,
|
||||
}
|
||||
|
||||
impl Pose {
|
||||
/// Where the patch-local point `u` lands in the frame.
|
||||
fn map(&self, u: [f64; 2]) -> [f64; 2] {
|
||||
let (s, c) = self.rot.to_radians().sin_cos();
|
||||
[self.c[0] + self.scale * (c * u[0] - s * u[1]), self.c[1] + self.scale * (s * u[0] + c * u[1])]
|
||||
}
|
||||
fn local(&self, p: [f64; 2]) -> [f64; 2] {
|
||||
let (s, c) = self.rot.to_radians().sin_cos();
|
||||
let d = [(p[0] - self.c[0]) / self.scale, (p[1] - self.c[1]) / self.scale];
|
||||
[c * d[0] + s * d[1], -s * d[0] + c * d[1]]
|
||||
}
|
||||
}
|
||||
|
||||
/// Render a frame: background texture, the patch (half size `half`) on top, Gaussian-ish noise
|
||||
/// of amplitude `amp`, and an optional flat occluder rectangle.
|
||||
fn frame(w: u32, h: u32, pose: Pose, half: f64, amp: f32, f: u32, occluder: Option<[f64; 4]>) -> Image {
|
||||
let mut img = Image::new(w, h);
|
||||
let ss = [0.25, 0.75];
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let mut acc = [0.0f32; 3];
|
||||
for sy in ss {
|
||||
for sx in ss {
|
||||
let p = [x as f64 + sx, y as f64 + sy];
|
||||
let l = pose.local(p);
|
||||
let t = if l[0].abs() <= half && l[1].abs() <= half { texture(l[0], l[1], 7) } else { texture(p[0] * 0.7, p[1] * 0.7, 3).map(|v| v * 0.6) };
|
||||
for i in 0..3 {
|
||||
acc[i] += t[i] * 0.25;
|
||||
}
|
||||
}
|
||||
}
|
||||
let n = noise(x, y, f) * amp;
|
||||
let mut px = [acc[0] + n, acc[1] + n, acc[2] + n, 1.0];
|
||||
if let Some([ox, oy, ow, oh]) = occluder {
|
||||
let (cx, cy) = (x as f64 + 0.5, y as f64 + 0.5);
|
||||
if cx >= ox && cx < ox + ow && cy >= oy && cy < oy + oh {
|
||||
px = [0.4, 0.4, 0.4, 1.0];
|
||||
}
|
||||
}
|
||||
img.set(x, y, px);
|
||||
}
|
||||
}
|
||||
img
|
||||
}
|
||||
|
||||
fn spec(c: [f64; 2], feature: f64, search: f64) -> PointSpec {
|
||||
PointSpec { center: c, feature_size: [feature, feature], search_offset: [0.0, 0.0], search_size: [search, search] }
|
||||
}
|
||||
|
||||
fn dist(a: [f64; 2], b: [f64; 2]) -> f64 {
|
||||
((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2)).sqrt()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recovers_translation_path_subpixel() {
|
||||
let path = |f: usize| {
|
||||
let t = f as f64;
|
||||
Pose { c: [100.0 + 4.37 * t + 6.0 * (t * 0.3).sin(), 90.0 + 2.71 * t - 3.0 * (t * 0.21).cos()], rot: 0.0, scale: 1.0 }
|
||||
};
|
||||
let f0 = frame(320, 240, path(0), 40.0, 0.02, 0, None);
|
||||
let mut tr = Tracker::new(TrackOptions::default(), &[spec(path(0).c, 31.0, 71.0)], &Frame::new(&f0));
|
||||
let mut worst: f64 = 0.0;
|
||||
for f in 1..24 {
|
||||
let img = frame(320, 240, path(f), 40.0, 0.02, f as u32, None);
|
||||
let r = tr.step(&Frame::new(&img))[0];
|
||||
let e = dist(r.center, path(f).c);
|
||||
worst = worst.max(e);
|
||||
assert!(r.confidence > 90.0, "frame {f}: confidence {}", r.confidence);
|
||||
assert_eq!(r.status, Status::Tracked);
|
||||
}
|
||||
eprintln!("worst error {worst:.4} px");
|
||||
assert!(worst < 0.25, "worst error {worst} px");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_offset_and_channels() {
|
||||
let pose = |f: usize| Pose { c: [120.0 + 3.3 * f as f64, 100.0 - 1.7 * f as f64], rot: 0.0, scale: 1.0 };
|
||||
for channel in Channel::ALL {
|
||||
for (blur, enhance) in [(0.0, false), (3.0, false), (0.0, true)] {
|
||||
let opts = TrackOptions { channel, blur, enhance, ..Default::default() };
|
||||
let f0 = frame(240, 200, pose(0), 36.0, 0.01, 0, None);
|
||||
// Layer coordinates are image pixels minus the offset.
|
||||
let off = [10.0, -5.0];
|
||||
let c0 = [pose(0).c[0] - off[0], pose(0).c[1] - off[1]];
|
||||
let mut tr = Tracker::new(opts, &[spec(c0, 29.0, 61.0)], &Frame { img: &f0, offset: off });
|
||||
for f in 1..6 {
|
||||
let img = frame(240, 200, pose(f), 36.0, 0.01, f as u32, None);
|
||||
let r = tr.step(&Frame { img: &img, offset: off })[0];
|
||||
let want = [pose(f).c[0] - off[0], pose(f).c[1] - off[1]];
|
||||
assert!(dist(r.center, want) < 0.3, "{channel:?} blur {blur} enhance {enhance} frame {f}: {:?} vs {want:?}", r.center);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_points_recover_rotation_and_scale() {
|
||||
let pose = |f: usize| Pose { c: [160.0 + 1.5 * f as f64, 120.0 + 0.8 * f as f64], rot: 1.8 * f as f64, scale: 1.0 + 0.01 * f as f64 };
|
||||
let u = [[-26.0, 0.0], [26.0, 0.0]];
|
||||
let p0 = pose(0);
|
||||
let f0 = frame(320, 240, p0, 52.0, 0.01, 0, None);
|
||||
let mut tr = Tracker::new(TrackOptions::default(), &u.map(|q| spec(p0.map(q), 23.0, 51.0)), &Frame::new(&f0));
|
||||
let (a0, l0) = angle_and_length(p0.map(u[0]), p0.map(u[1]));
|
||||
let mut worst: f64 = 0.0;
|
||||
for f in 1..20 {
|
||||
let p = pose(f);
|
||||
let img = frame(320, 240, p, 52.0, 0.01, f as u32, None);
|
||||
let r = tr.step(&Frame::new(&img));
|
||||
for k in 0..2 {
|
||||
worst = worst.max(dist(r[k].center, p.map(u[k])));
|
||||
}
|
||||
let (a, l) = angle_and_length(r[0].center, r[1].center);
|
||||
assert!((unwrap_degrees(0.0, a - a0) - p.rot).abs() < 0.5, "frame {f}: rotation {} vs {}", a - a0, p.rot);
|
||||
assert!((l / l0 - p.scale).abs() < 0.01, "frame {f}: scale {} vs {}", l / l0, p.scale);
|
||||
// The per-feature shape estimate follows too.
|
||||
assert!((r[0].rotation - p.rot).abs() < 1.0, "frame {f}: feature rotation {}", r[0].rotation);
|
||||
assert!((r[0].scale - p.scale).abs() < 0.02, "frame {f}: feature scale {}", r[0].scale);
|
||||
}
|
||||
eprintln!("worst error {worst:.4} px");
|
||||
assert!(worst < 0.25, "worst error {worst} px");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confidence_drops_on_occlusion_and_actions() {
|
||||
let pose = |f: usize| Pose { c: [110.0 + 2.0 * f as f64, 100.0], rot: 0.0, scale: 1.0 };
|
||||
let occ = |f: usize| (f == 5).then(|| [pose(f).c[0] - 12.0, pose(f).c[1] - 30.0, 40.0, 60.0]);
|
||||
let run = |action: ConfidenceAction| {
|
||||
let f0 = frame(240, 200, pose(0), 36.0, 0.01, 0, None);
|
||||
let opts = TrackOptions { action, ..Default::default() };
|
||||
let mut tr = Tracker::new(opts, &[spec(pose(0).c, 31.0, 61.0)], &Frame::new(&f0));
|
||||
(1..9)
|
||||
.map(|f| {
|
||||
let img = frame(240, 200, pose(f), 36.0, 0.01, f as u32, occ(f));
|
||||
tr.step(&Frame::new(&img))[0]
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let r = run(ConfidenceAction::Continue);
|
||||
assert!(r[3].confidence > 95.0, "{}", r[3].confidence);
|
||||
assert!(r[4].confidence < 70.0, "occluded frame confidence {}", r[4].confidence);
|
||||
let r = run(ConfidenceAction::Extrapolate);
|
||||
assert_eq!(r[4].status, Status::Extrapolated);
|
||||
assert!(dist(r[4].center, pose(5).c) < 0.5, "extrapolated {:?}", r[4].center);
|
||||
// Back on track after the occlusion.
|
||||
assert!(dist(r[6].center, pose(7).c) < 0.25 && r[6].status == Status::Tracked);
|
||||
let r = run(ConfidenceAction::Stop);
|
||||
assert_eq!(r[4].status, Status::Stopped);
|
||||
let r = run(ConfidenceAction::Adapt);
|
||||
assert_eq!(r[4].status, Status::Adapted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backward_and_whole_pixel() {
|
||||
let pose = |f: usize| Pose { c: [100.0 + 3.25 * f as f64, 100.0 + 1.5 * f as f64], rot: 0.0, scale: 1.0 };
|
||||
let last = 6;
|
||||
let fl = frame(240, 200, pose(last), 36.0, 0.0, 0, None);
|
||||
let opts = TrackOptions { subpixel: false, ..Default::default() };
|
||||
let mut tr = Tracker::new(opts, &[spec(pose(last).c, 31.0, 61.0)], &Frame::new(&fl));
|
||||
for f in (0..last).rev() {
|
||||
let img = frame(240, 200, pose(f), 36.0, 0.0, 0, None);
|
||||
let r = tr.step(&Frame::new(&img))[0];
|
||||
let want = pose(f).c;
|
||||
// Whole-pixel displacements of the start position.
|
||||
let d = [r.center[0] - pose(last).c[0], r.center[1] - pose(last).c[1]];
|
||||
assert!((d[0] - d[0].round()).abs() < 1e-9 && (d[1] - d[1].round()).abs() < 1e-9);
|
||||
assert!(dist(r.center, want) < 0.75, "frame {f}: {:?} vs {want:?}", r.center);
|
||||
}
|
||||
}
|
||||
|
||||
/// 1080p, one point: tracking cost per frame (frames are generated outside the timing).
|
||||
#[test]
|
||||
fn performance_1080p_single_point() {
|
||||
let w = 1920;
|
||||
let h = 1080;
|
||||
// A cheap textured frame (the full synthetic renderer is slow at 1080p in debug builds).
|
||||
let make = |dx: f64, dy: f64| {
|
||||
let mut img = Image::new(w, h);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let (fx, fy) = (x as f64 + 0.5 - dx, y as f64 + 0.5 - dy);
|
||||
let v = 0.5 + 0.2 * (fx * 0.31).sin() * (fy * 0.17).cos() + 0.15 * ((fx + fy) * 0.11).sin() + 0.1 * ((fx * 0.05).sin() * (fy * 0.23).sin());
|
||||
img.set(x, y, [v as f32, v as f32, v as f32, 1.0]);
|
||||
}
|
||||
}
|
||||
img
|
||||
};
|
||||
let frames: Vec<Image> = (0..6).map(|f| make(2.3 * f as f64, 1.1 * f as f64)).collect();
|
||||
let c0 = [960.0, 540.0];
|
||||
let s = PointSpec { center: c0, feature_size: [48.0, 48.0], search_offset: [0.0; 2], search_size: [128.0, 128.0] };
|
||||
let t0 = std::time::Instant::now();
|
||||
let mut tr = Tracker::new(TrackOptions::default(), &[s], &Frame::new(&frames[0]));
|
||||
let mut last = PointResult { center: c0, confidence: 0.0, rotation: 0.0, scale: 1.0, status: Status::Tracked };
|
||||
for f in frames.iter().skip(1) {
|
||||
last = tr.step(&Frame::new(f))[0];
|
||||
}
|
||||
let per = t0.elapsed().as_secs_f64() / 5.0;
|
||||
eprintln!("1080p single-point track: {:.2} ms/frame ({:.0} fps)", per * 1e3, 1.0 / per);
|
||||
assert!(dist(last.center, [c0[0] + 2.3 * 5.0, c0[1] + 1.1 * 5.0]) < 0.25, "{:?}", last.center);
|
||||
assert!(per < 0.1, "{per} s per frame");
|
||||
}
|
||||
Reference in New Issue
Block a user