Interactive Vision From Zero · Episode 23

Robustness & Performance

Robustness & Performance is Episode 23 of Interactive Vision From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 23 · Interactive Vision From Zero · Season 3

Here is the gap between a demo and a product. A demo tracks your hand and everyone says "wow." A product tracks your hand for an hour, on a mediocre laptop, in bad lighting, while the cursor never once jitters, never snaps to the corner when you walk out of frame, and never drops below a smooth frame rate. Raw landmarks coming off a model are noisy and occasionally absent. Everything that makes them feel solid is engineering you add on top — and almost none of it is glamorous.

This episode is about that unglamorous layer. The star is the One-Euro filter: a tiny, ~15-line smoother that is buttery-smooth when your hand is still and snappy-responsive when it moves fast — beating the naive lerp that forces you to choose one or the other. We'll also survive lost tracking (hold the last good pose and decay, then re-acquire) and budget performance so the model never starves the frame. The demo below is alive with no camera: we inject jitter into a synthetic hand, so you can see raw-vs-smoothed side by side right now. 🔒 runs on-device · nothing leaves your machine.

0 fps
move your mouse to puppet the hand · or autopilot
🔒 on-device · synthetic input running
MediaPipe Hands · 21 landmarks · synthetic
Raw landmarks with injected jitter. This is what a model actually hands you.

What you're looking at

One synthetic hand, drawn (when a stage compares them) as two ghosts: the dim red one is the raw signal with jitter baked in; the bright cyan one is the filtered output. Drag your mouse to puppet the palm, or leave it and a slow Lissajous flies the hand around so the comparison stays live. The jitter slider sets how shaky the raw signal is; mincutoff and beta are the two knobs of the One-Euro filter (Stage 3 onward). The FPS readout doubles as a latency/dropped-frame meter in the perf stages.

The hand is mirrored like a selfie: we map landmarks to screen with screenX = (1 - lm.x) * width so moving your hand right moves the on-screen hand right. The synthetic hand and the real camera feed go through the exact same onLandmarks(hand) path, so everything you tune here works unchanged on real data the moment you hit "use my camera."

Stage 1 — Raw landmarks with injected jitter

This is the honest baseline: the landmark stream as a model actually emits it. Each frame we add a small random offset to every point — sub-pixel to a few pixels — and the whole hand shimmers. It's not broken; it's normal. A neural network re-estimates positions every frame from scratch, so even a perfectly still hand wobbles by a pixel or two. Bind a cursor to a fingertip raw and it buzzes like a fly. Crank the jitter slider up to feel how bad it gets in poor lighting; this is the enemy every later stage fights.

Stage 2 — Naive lerp / EMA smoothing (smooth, but laggy)

The first instinct, and it works… sort of. Each frame, blend a fraction of the way from the last output toward the new raw point: an exponential moving average. With a small blend factor the shimmer vanishes — the hand goes glassy-smooth. But now move it fast: the smoothed hand lags behind, trailing the raw one like it's underwater. That's the tradeoff baked into a fixed smoothing factor: more smoothing means more lag. You can have steady or you can have responsive, not both. This single tradeoff is the reason the One-Euro filter exists.

Stage 3 — The One-Euro filter (the win)

Here's the trick. Instead of a fixed smoothing factor, make the cutoff frequency adapt to how fast the point is moving. When the hand is slow, use a low cutoff → heavy smoothing → rock-solid stillness. When the hand is fast, raise the cutoff → light smoothing → it tracks instantly. Watch the bright cyan (One-Euro) sit dead-still next to the shivering raw red when the hand idles — then snap to it the instant you whip the mouse across. Steady and responsive. That is the whole pitch, and it's about fifteen lines of code.

Stage 4 — Lost tracking → hold + recover

Real cameras drop the hand: it leaves the frame, a hand-off occlusion happens, the model returns null. The naive response — and the most common bug — is to read a missing landmark as {x:0, y:0} and snap the hand to the top-left corner. Awful. Instead: when frames go missing, hold the last good pose and gently decay its confidence (we fade it out). When tracking returns, ease back in. In this stage we periodically simulate a dropout — the hand keeps its last pose, dims, and recovers smoothly. The cursor never teleports.

Stage 5 — Performance budget

The model is the most expensive thing in your frame. Run it wrong and the page janks. The rules: one model instance (creating landmarkers is slow and leaks GPU memory), runningMode: 'VIDEO' (lets MediaPipe reuse temporal state instead of treating each frame as a cold start), the GPU delegate, and — when the device can't keep up — throttle inference: run the model at, say, 30 Hz while still rendering and filtering at full rate. This stage shows a synthetic inference cost and a live FPS/latency readout; nudge the jitter and watch the budget. The filter runs every frame regardless, so motion stays smooth even when inference is throttled.

Stage 6 — A robustness dashboard

Everything at once, live: raw jitter vs the smoothed output, a measured latency number, the frame rate, and the dropped-frame handler doing its hold-and- recover dance — all on one screen. This is the view you'd keep open while shipping. If a real product feels "solid," it's because someone watched a panel like this until every needle sat where it should.

How the code works

Four pieces carry the whole episode: the One-Euro filter (the star), the lerp/EMA we compare it against, the lost-tracking hold-and-recover, and the performance budget. Let's read each one.

(a) The One-Euro filter

A One-Euro filter smooths a single scalar (one coordinate). It's a low-pass filter whose cutoff frequency rises with the signal's speed. Two pieces: a generic one-pole LowPass, and the One-Euro wrapper that picks the cutoff each frame from the estimated velocity. The two knobs are minCutoff (smoothness at rest — lower is smoother) and beta (how aggressively it speeds up with motion — higher is more responsive):

// One pole of exponential smoothing. alpha derived from a cutoff freq + dt.
function alpha(cutoff, dt) {
  const tau = 1 / (2 * Math.PI * cutoff);   // time constant
  return 1 / (1 + tau / dt);                 // 0..1 blend factor
}

class OneEuro {
  // minCutoff: smoothness at rest. beta: responsiveness to speed. dCutoff: smooth the speed itself.
  constructor(minCutoff = 1.0, beta = 0.01, dCutoff = 1.0) {
    Object.assign(this, { minCutoff, beta, dCutoff, xPrev: null, dxPrev: 0, tPrev: null });
  }
  filter(x, t) {                            // x = raw value, t = seconds
    if (this.xPrev === null) { this.xPrev = x; this.tPrev = t; return x; }
    const dt = Math.max(1e-3, t - this.tPrev);
    const dx = (x - this.xPrev) / dt;                       // raw velocity
    const dxHat = this.dxPrev + alpha(this.dCutoff, dt) * (dx - this.dxPrev);
    const cutoff = this.minCutoff + this.beta * Math.abs(dxHat);   // speed → cutoff
    const xHat = this.xPrev + alpha(cutoff, dt) * (x - this.xPrev);
    this.xPrev = xHat; this.dxPrev = dxHat; this.tPrev = t;
    return xHat;
  }
}

That's it. The magic line is cutoff = minCutoff + beta * |velocity|: slow motion ⇒ tiny cutoff ⇒ heavy smoothing; fast motion ⇒ big cutoff ⇒ near pass- through. To smooth a landmark you keep one OneEuro per coordinate (x and y, and z if you use it). The exercises scale this up to a whole 21-point hand.

(b) Lerp / EMA — for contrast

The thing One-Euro beats. A fixed blend factor: cheap, one line, and permanently stuck choosing between smooth and responsive:

// Exponential moving average. a small → smooth but laggy; a large → jumpy.
function lerpSmooth(prev, x, a = 0.18) {
  return prev + a * (x - prev);   // same a whether still or sprinting → the tradeoff
}

(c) Lost tracking — hold, decay, recover

When the model returns nothing, don't reset to zero. Keep the last good pose, fade a confidence value toward 0, and reset it to 1 the moment a hand reappears. Downstream code reads confidence to dim, pause, or gate actions — never to teleport:

let lastGood = null, confidence = 0;

function onFrame(hand, dt) {           // hand may be null (lost)
  if (hand) {
    lastGood = hand;
    confidence = Math.min(1, confidence + dt * 4);   // re-acquire (ease in)
  } else {
    confidence = Math.max(0, confidence - dt * 1.5); // decay while lost
  }
  if (confidence > 0 && lastGood) {
    draw(lastGood, confidence);    // hold last pose, dimmed by confidence
  }
  // confidence === 0 → truly gone; show an idle / "show me your hand" hint
}

(d) Performance budget — one model, throttle, delegate

Keep exactly one landmarker, in VIDEO mode, on the GPU. Then decouple inference rate from render rate: render and filter every frame, but only run the model when enough time has passed (and back that interval off when frames get expensive):

// Created ONCE — never per frame. VIDEO mode + GPU delegate are the cheap wins.
landmarker = await HandLandmarker.createFromOptions(fileset, {
  baseOptions: { modelAssetPath: HAND_TASK, delegate: 'GPU' },
  runningMode: 'VIDEO', numHands: 1,
});

let inferEvery = 1 / 30, sinceInfer = 0, lastHand = null;

function tick(dt, t) {
  sinceInfer += dt;
  if (usingCamera && sinceInfer >= inferEvery) {   // throttle the EXPENSIVE call
    sinceInfer = 0;
    const res = landmarker.detectForVideo(video, performance.now());
    lastHand = res.landmarks?.[0] || null;
  }
  onFrame(lastHand, dt);            // filter + draw EVERY frame → motion stays smooth
}

Common pitfalls

  • Lerp lag vs One-Euro (the core lesson). A fixed-factor EMA can be smooth or responsive, never both — pick a small factor and fast motion drags; pick a large one and stillness shivers. One-Euro escapes the dilemma by making the smoothing depend on speed. If you only take one thing from this episode, take this.
  • One-Euro params, demystified. minCutoff controls smoothness at rest — lower = calmer hands, but too low adds lag even when slow. beta controls responsiveness to speed — higher = snappier on fast motion, but too high lets jitter leak back in during quick moves. Tune minCutoff first against a still hand, then raise beta until fast motion stops lagging.
  • Lost tracking → don't snap to 0. A missing landmark is not {x:0,y:0}. Reading it as origin teleports your cursor to the top-left corner the instant tracking blips. Always guard for null, hold the last good pose, and decay — never reset to zero.
  • Model on the main thread eats your budget. The landmarker is the heaviest call in the loop. Create it once, use runningMode:'VIDEO' and the GPU delegate, and throttle inference independently of rendering. Never construct a landmarker inside the render loop.
  • Over-smoothing kills responsiveness. It's tempting to crank smoothing until the hand is glass — then the whole interface feels mushy and laggy. Smoothing is a budget you spend against latency. Spend the minimum that hides the jitter, and let One-Euro give the rest back during motion.

Exercises

  1. Smooth a whole 21-point hand. Build a HandFilter that holds 21×2 (or 21×3) OneEuro instances and maps a raw hand to a smoothed hand each frame. Feed it the synthetic jittered hand and confirm the entire skeleton goes calm — not just one fingertip. (Hint: lazily create filters keyed by `${i}-${axis}`.)
  2. A "tracking quality" meter. Combine the confidence value with the recent average raw velocity to produce a 0–100 quality score, and draw it as a bar. Make it dip when you simulate dropouts and when jitter is high — the kind of HUD a QA engineer lives in.
  3. Adaptive throttling under load. Measure frame time; when it exceeds your budget (say 8 ms over two frames), raise inferEvery to run the model less often, and lower it again when there's headroom. Prove that motion stays smooth even as inference rate drops, because the filter still runs every frame.

What's next

Episode 24 — the capstone. We take everything across all three seasons — the 21-landmark hand, the gesture vocabulary, the smoothing and robustness from this episode, the 3D and shader and splat cross-overs — and assemble one cohesive, shippable interactive vision experience. The filter and lost-tracking handling you just built are load-bearing there: the capstone has to feel solid, and this is the episode that earns it.