Skip to content

Point tracker: refine in a 3x3 neighbourhood when the motion was small - #2351

Merged
bflatastic merged 2 commits into
storytold:mainfrom
vangel76:point-two-stage-search
Oct 29, 2026
Merged

bflatastic merged 2 commits into
storytold:mainfrom
vangel76:point-two-stage-search

Conversation

@vangel76

@vangel76 vangel76 commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The fine stage of the point tracker refined each of up to three seeds at every pyramid level in a 5x5 neighbourhood. When the best coarse match is reliable (NCC score >= 0.8) and lies within one top-level pixel of the motion prediction, it now searches a 3x3 neighbourhood; in every other case the 5x5 search stays. The decision is made once per step for all seeds.

Fixes #2349

This PR is stacked on #2339 (same function). Until #2339 merges, the diff against main also shows its commit; the change of this PR is the last commit only (lib.rs: SMALL_MOTION, RELIABLE_SCORE, 4 lines in the fine stage; tests.rs: one test).

Numbers

Single thread (RAYON_NUM_THREADS=1), 1080p, 16 points x 60 frames, perf stat -e instructions:u, work = total minus frame generation (188.25 G), three alternating runs per variant (counts agree to 6 digits):

bench #2339 + this PR
point 31.03 G 20.19 G (1.54x)
point with rotation and zoom 31.85 G 21.42 G (1.49x)

Why not simply +-1 everywhere

A plain +-1 gave 1.55x but lost tracks about twice as often when the camera jumped between frames (more than 8 px off: 31 -> 62, 93 -> 126 of 3776 measurements). The two conditions above keep +-2 exactly in those cases.

Accuracy

Synthetic ground truth, 64 points x 60 frames, 1080p; camera jitter 1x and 3x, noise 1x and 8x, translation and rotation+zoom. Number of measurements (of 3776) more than 0.5 / 2 / 8 px off:

case #2339 + this PR
point, jitter 1, noise 1 0 / 0 / 0 0 / 0 / 0
point, jitter 1, noise 8 571 / 57 / 0 571 / 57 / 0
point, jitter 3, noise 1 32 / 32 / 31 32 / 32 / 31
point, jitter 3, noise 8 320 / 31 / 31 320 / 31 / 31
rot+zoom, jitter 1, noise 1 74 / 55 / 48 74 / 55 / 48
rot+zoom, jitter 1, noise 8 374 / 133 / 50 374 / 133 / 50
rot+zoom, jitter 3, noise 1 87 / 68 / 62 87 / 68 / 62
rot+zoom, jitter 3, noise 8 250 / 156 / 93 250 / 157 / 93

Median and 90th-percentile errors are identical in all cases. This is synthetic material, not footage; the output is not bit-identical by design (it can differ where 3x3 finds a different minimum), but no case got worse.

Verification

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved tracking accuracy across different image scales and shapes.
    • Tracking now recovers more reliably from sudden motion, including when movement differs from the predicted path.
    • Refinement results remain consistent near image boundaries and when processing smaller image regions.

vangel76 and others added 2 commits October 24, 2026 23:07
The normalized cross-correlation only had a fast path for an exactly
identity shape, which tracked footage never has after the first frame, so
every candidate went through Plane::sample. All candidates of a search are
the reference centre plus integer offsets, so each template pixel has the
same fractional offsets for all of them. Build one table of taps per
(level, seed, shape) and score each candidate with integer-indexed lerps,
with one bounding-box check up front (outside the plane the old path is
used).

lk_refine only reads the level-0 gradients around the match, so compute
them for that window (with an interior fast path in Plane::gradients_in)
and fall back to the full gradients if the iteration leaves it.

The results are unchanged: same lerp form and accumulation order.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The fine stage searched a 5x5 neighbourhood per pyramid level and seed.
When the best coarse match is reliable (NCC score >= 0.8) and lies within
one top-level pixel of the motion prediction, a 3x3 neighbourhood is
enough; otherwise the 5x5 search stays.

Fixes storytold#2349

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between 9919048 and 4b31e21.

Files selected for processing: 3
  • crates/track/src/lib.rs
  • crates/track/src/plane.rs
  • crates/track/src/tests.rs

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.

Walkthrough

The point tracker now shares NCC scoring across candidate searches, conditionally narrows fine search, and computes Lucas–Kanade gradients around the template window with a full-plane fallback. Tests cover scorer equivalence, gradient behavior, and recovery from alternating position jumps.

Changes: Point Tracking

Layer / File(s) Summary
Candidate scoring and fine search
crates/track/src/lib.rs, crates/track/src/tests.rs
A shared scorer handles shaped-template NCC scoring and is used for coarse and fine candidates. Fine search uses a 3×3 neighborhood when the best coarse score is at least 0.8 and the candidate is within 1.0 pixel per axis of the prediction; otherwise it uses 5×5. Tests compare scorer results with NCC and check tracking through alternating position jumps.
Windowed gradient refinement
crates/track/src/plane.rs, crates/track/src/lib.rs, crates/track/src/tests.rs
Plane::gradients_in computes gradients inside an inclusive, clamped rectangle. Lucas–Kanade refinement uses local gradients and falls back to full-plane gradients when the refinement window leaves the cached region. Tests compare windowed and full-gradient results.

Priority: Low

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Other

Sequence Diagram(s)

sequenceDiagram
  participant PointState
  participant Scorer
  participant Grad
  participant Plane
  PointState->>Scorer: Score coarse candidates
  Scorer-->>PointState: Return candidate scores
  PointState->>Scorer: Score candidates in selected fine-search neighborhood
  Scorer-->>PointState: Return fine-search scores
  PointState->>Grad: Build local gradients for refinement
  Grad->>Plane: Compute gradients in the requested rectangle
  Plane-->>Grad: Return gradient planes
  Grad-->>PointState: Provide gradients to Lucas–Kanade refinement
Loading

Possibly related issues

  • Issue 2318: This PR includes shared tap scoring and gradients limited to the match window, which the issue describes.
  • Issue 2349: This PR implements conditional 3×3 fine search for reliable coarse matches near the motion prediction.

Possibly related PRs

  • storytold/effectcraft#2339: This PR continues the shared scorer and windowed-gradient changes by adding conditional fine-search sizing.

Suggested reviewers: echelon

Merge Risk: Minimal · up to 4b31e

No concrete issue remains that should prevent merging after normal checks.

Security architecture risk: Minimal · up to 4b31e

The reviewed changes optimize image tracking without introducing a new security boundary or privileged operation. The existing full-gradient behavior remains available, and refinement falls back to it before reading outside the computed window. No introduced or worsened material security risk was identified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — For the inspected paths, caller-supplied image and tracking inputs affect computation, allocations, and returned tracking values within the existing process. No new tenant, service, data-store, or privileged-resource exposure is established. External users of the public library API remain outside verified coverage.

Trust Boundaries and Controls

  • observed — The optimized scorer rejects unsupported tap coordinates or candidates whose taps leave the plane and then uses the existing NCC sampling path. The new windowed-gradient entrypoint does not grant additional authority; its result is derived only from the supplied Plane.

Resilience and Maintainability Implications

  • observed — Gradient state is local to a tracking step and passed by exclusive mutable borrow, preventing reuse across points or frames. Solver failures remain local; Stop returns before persistent mutation, Extrapolate intentionally advances the center, and successful tracking follows the existing state-update path. No new transactional interruption guarantee is introduced.
Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 27 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the primary change: using a 3x3 fine-stage search when motion was small. It matches the pull request objectives.
Linked Issues check Passed Issue #2349 requirements are implemented. The fine stage sets one search radius per step. It selects ±1 only when the best coarse NCC score is at least 0.8 and the first coarse seed is within 1.0 top-…
Out of Scope Changes check Passed The final commit changes the fine-stage decision and adds related tests. The shared scorer, windowed gradients, and Plane::gradients_in changes are from the disclosed stacked #2339 commit in reposit…
Full details: Linked Issues check

Explanation

Issue #2349 requirements are implemented. The fine stage sets one search radius per step. It selects ±1 only when the best coarse NCC score is at least 0.8 and the first coarse seed is within 1.0 top-level pixel per axis of the prediction. It retains ±2 otherwise and applies the radius to all seeds. The added jump-recovery test covers the fallback case. The reported suite, benchmark, and synthetic accuracy results satisfy the stated verification goals; lost-point counts and reported error percentiles do not worsen.

Full details: Out of Scope Changes check

Explanation

The final commit changes the fine-stage decision and adds related tests. The shared scorer, windowed gradients, and Plane::gradients_in changes are from the disclosed stacked #2339 commit in repository history. They provide the performance and validation support for the tracker change and are not unrelated work in this PR context.

Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@vangel76

Copy link
Copy Markdown
Contributor Author

This PR is one of 17 from a speed audit of crates/track and its callers (issues #2317-#2330, #2322, #2349). Overview of what each one measured, so the effect is visible in one place:

PR Area Measured (single thread, before -> after) Output
#2332 Subspace Warp plan() 22.3 G -> 4.8 G instructions (4.7x, Automatic); 33.7 G -> 5.2 G (6.5x, Enhanced); 24x on clean low-rank trajectories rounding level, at most 2.7e-6 px
#2331 KLT lk_point (Warp Stabilizer analysis, mask tracking) analysis 3.84 s -> 1.44 s (2.6x), mask tracking 1.57 s -> 0.95 s bit-identical
#2339 Point tracker (NCC taps, gradient window) 54.6 G -> 31.0 G instructions (1.76x) bit-identical
#2334 Face tracker polygon test 12.5 G -> 2.2 G instructions (5.7x) bit-identical
#2337 Mask tracker frame clone 4K: 3.42 s -> 2.19 s (-36 %); 1080p -5 % identical outline
#2335 Roto Brush propagate band crop 208.5 G -> 172.0 G instructions per 20 frames (-17.5 %) bit-identical
#2333 Roto Brush distance transform 3.04 G -> 2.80 G instructions (-8 %) bit-identical
#2346 Camera solve, long tracks (matrix-free Schur) 44.6 G -> 4.2 G instructions (10.6x), timed loop 1966 ms -> 216 ms practically identical (reprojection < 1e-9 px), direct fallback
#2342 Camera solve, short tracks (band Cholesky) 8.34 G -> 3.40 G instructions (2.46x) bit-identical
#2338 triangulate allocations 2.38 G -> 1.32 G instructions (1.81x) bit-identical
#2340 BA Jacobian on the stack 13.4 G -> 12.6 G instructions (-6.2 %) bit-identical
#2345 null_vector without unused SVD output -0.96 % instructions bit-identical
#2351 Point tracker, 3x3 refine when the motion was small (stacked on #2339) another 31.0 G -> 20.2 G instructions (1.54x) on top of #2339 not bit-identical by design, accuracy unchanged in all 8 ground-truth cases
#2348 Warp Stabilizer / Camera Tracker analysis lookup per render 0.73 ms -> 0.014 ms per call for 300 frames (about 50x) identical
#2347 Warp Stabilizer default plan computed twice first render 2313 ms -> 1156 ms (-50 % instructions) identical pixels
#2350 Warp analysis shares one luma pyramid 87.7 G -> 81.8 G instructions (-6.8 %) identical analysis JSON
#2341 Input validation (panics, NaN, allocation budget) correctness fix, +6.1 % instructions on valid input valid input unchanged

Notes:

@bflatastic
bflatastic merged commit 844e889 into storytold:main Oct 29, 2026
3 checks passed
@bflatastic

Copy link
Copy Markdown
Member

Merged, thank you @vangel76! It landed on main with a batch of community PRs, after a full workspace build and test run on Windows against the refactored main (fmt, strict clippy, about 4,100 tests, layers, assets and wasm).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Point tracker: refine in a 3x3 neighbourhood when the motion was small (two-stage search)

2 participants