Interactive Vision From Zero · Episode 19

Train Your Own Gesture

Train Your Own Gesture is Episode 19 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 19 · Interactive Vision From Zero · Season 3

Here is a magic trick you can pull on a stranger in ten seconds: show the laptop your secret handshake twice, show it a thumbs-up twice, and now it can tell them apart forever. No upload, no training run, no GPU spinning in some datacenter. You record a handful of examples of your gestures, the page fits a tiny classifier on the spot, and it starts naming them live. This is the browser version of a "teachable machine," and the whole thing is about a hundred lines of geometry.

The secret is that we are not learning from pixels. By Episode 19 you already have a hand reduced to 21 landmarks, and a gesture is just a shape those landmarks make. If we turn that shape into a short, normalized vector of numbers, then "recognize this gesture" becomes "which stored example is this closest to?" — a nearest-neighbor lookup. The demo below is already alive and teaching itself: with no camera it cycles a synthetic hand through three poses, auto-records a few of each, fits a k-NN classifier, and starts predicting. Press use my camera and the exact same machine recognizes yours.

0 fps
synthetic hand is teaching itself — no camera needed
🔒 runs on-device · nothing leaves your machine
k-NN · 0 samples
The live prediction = majority vote of the k nearest stored samples.

What you're looking at

One canvas, drawn twice a frame at up to 120fps. On the left, the live hand: the 21-landmark skeleton, mirrored so it moves with you. On the right, a little panel of everything the classifier knows — how many samples you have recorded per class, the feature vector as a row of bars, and the current prediction with a confidence meter. The synthetic hand puppets itself along a slow path and morphs between three named poses (a flat palm, a fist, and a point). When a pose holds steady, the demo quietly records a sample into that class, so within a few seconds you have a trained model with zero clicks. The badge reads k-NN · N samples and ticks up as it learns.

Two conventions carried from earlier episodes. Mirror: we map landmarks with screenX = (1 - x) * width so the on-screen hand is a selfie mirror — move right, it goes right. The same flip is applied to the synthetic hand so both input modes line up. Privacy: the camera path runs entirely on-device through MediaPipe in your browser; the only thing this page could ever "save" is a list of tiny number vectors, and those never leave the tab.

Stage 1 — The feature vector

You cannot feed raw landmarks to a classifier and expect it to work. If you record a fist in the top-left of the frame and then make the same fist in the bottom-right, every one of those 21 (x, y) pairs is different — same gesture, totally different numbers. A bigger hand (closer to the camera) shifts them again. The fix is to build a feature vector that is translation- and scale-invariant: subtract the wrist so position drops out, then divide by the hand's size so distance drops out. What survives is pure pose. Stage 1 shows that vector live as a row of bars — wave the hand around the frame and watch the bars stay put; only changing the shape moves them.

Stage 2 — Record class A

Recording is the entire "training set." Click A (or let the synthetic hand auto-record while it holds the palm pose) and the current feature vector is pushed into the array for class A. That's it — no labels file, no epochs. A "class" is just an array of feature vectors you've decided belong together. Capture five or ten so the class covers a little natural variation: a fist tilted slightly, a fist held a bit looser. The badge counts every sample as it lands.

Stage 3 — Record class B (and C)

Repeat for a second gesture, and a third. Now the feature space has clusters: all the palm vectors land near each other, all the fists land somewhere else, all the points in a third spot. The synthetic hand cycles through all three poses so every class fills in on its own. The art of a good training set is the same here as in any ML: enough samples, and roughly balanced across classes, so no single gesture dominates the vote.

Stage 4 — k-NN classify

This is where it becomes a recognizer. To classify the live hand, we measure the distance from its feature vector to every stored sample, take the k closest, and let them vote — the majority class wins. That is the whole k-nearest-neighbors algorithm. There is no model to train: the samples are the model. Slide k from 1 to 9 and feel the trade-off — k=1 snaps instantly but trusts one possibly-noisy neighbor; larger k is steadier but blurs small classes. The predicted label is drawn big over the hand.

Stage 5 — Confidence + smoothing

A bare label is brittle. Two upgrades make it feel solid. Confidence: turn the distance to the nearest neighbors into a 0–1 score — close match, high confidence; far from everything, low. We also fold in how unanimous the k votes were. Smoothing: raw per-frame predictions flicker at cluster boundaries, so we debounce — a new label only "commits" after it has won several frames in a row. The confidence bar and the committed label both show in this stage; watch the raw guess wobble while the committed one stays calm.

Stage 6 — Map to actions

A recognizer is only fun once it does something. Stage 6 wires each committed gesture to an action: cross the confidence threshold and the gesture fires once, popping a big emoji and a toast (palm → ✋ "halt", fist → ✊ "grab", point → 👉 "select"). The firing is edge-triggered on the debounced label, so it triggers on the transition into a gesture, not every frame you hold it. Swap the emoji for a keypress, a sound, a navigation — this is the hook into a real interface.

How the code works

Four small pieces: extract an invariant feature, record samples per class, classify by nearest neighbors, and turn the result into a stable, confident label. Everything below runs identically on the synthetic hand and on real MediaPipe output, because both are the same 21-landmark array.

(a) Feature extraction — make it translation + scale invariant

The single most important function in the episode. Subtract the wrist (landmark 0) so the gesture no longer depends on where the hand is, then divide by a size estimate (wrist→middle-knuckle distance) so it no longer depends on how big the hand is. We flatten the 21 normalized (x, y) offsets into a 42-number vector. Adding finger-curl angles would make it even more robust, but raw normalized offsets already generalize well:

// 21 landmarks → a 42-D vector that ignores position & scale.
function featureVector(lm) {
  const wrist = lm[0];
  const mid   = lm[9];                 // middle-finger MCP knuckle
  // hand size = wrist→knuckle distance (never zero in practice)
  const size = Math.hypot(mid.x - wrist.x, mid.y - wrist.y) || 1e-6;
  const v = [];
  for (const p of lm) {
    v.push((p.x - wrist.x) / size);    // subtract wrist → divide by size
    v.push((p.y - wrist.y) / size);
  }
  return v;                            // length 42, invariant to where/how-big
}

(b) Recording samples into per-class arrays

The "dataset" is a dictionary from class name to a list of feature vectors. Recording appends; clearing empties them. Notice there is no separate "fit" step — appending a sample is training a k-NN model.

const samples = { A: [], B: [], C: [] };   // each class = list of vectors

function record(cls, lm) {
  samples[cls].push(featureVector(lm));     // that's the whole "training"
}
function clearModel() {
  for (const c in samples) samples[c] = [];
}
// total count for the badge
const count = () => Object.values(samples).reduce((a, s) => a + s.length, 0);

(c) k-NN — distance to all samples, vote among the k nearest

Squared Euclidean distance to every stored vector (no sqrt needed — we only compare, and dropping it is faster). Sort, take the k closest, tally their labels, return the winner. For a few hundred samples this is instant every frame.

function dist2(a, b) {            // squared distance — monotone, so fine for ranking
  let s = 0;
  for (let i = 0; i < a.length; i++) { const d = a[i] - b[i]; s += d * d; }
  return s;
}

function classify(lm, k) {
  const v = featureVector(lm);
  const all = [];                            // {label, d} for every stored sample
  for (const cls in samples)
    for (const s of samples[cls]) all.push({ cls, d: dist2(v, s) });
  if (!all.length) return null;
  all.sort((p, q) => p.d - q.d);             // nearest first
  const near = all.slice(0, Math.min(k, all.length));
  const votes = {};
  for (const n of near) votes[n.cls] = (votes[n.cls] || 0) + 1;
  // label = majority; nearestD drives confidence in step (d)
  let best = null, bestV = -1;
  for (const c in votes) if (votes[c] > bestV) { bestV = votes[c]; best = c; }
  return { label: best, votes: bestV, k: near.length, nearestD: near[0].d };
}

(d) Confidence + debounce

Confidence blends two signals: how unanimous the k votes were, and how close the nearest sample is (mapped through a soft falloff so "miles from any cluster" reads as low). Debouncing keeps a label only after it has repeated for a few frames, killing boundary flicker, and fires an action on the rising edge.

let committed = null, candidate = null, streak = 0;
const NEED = 5;                  // frames a guess must hold before it commits

function smooth(res) {
  if (!res) { candidate = null; streak = 0; return committed; }
  // confidence: vote share × distance falloff (tune 8.0 to your feature scale)
  const share = res.votes / res.k;
  const closeness = Math.exp(-res.nearestD * 8.0);   // 1 = bullseye, →0 far away
  const conf = share * closeness;

  if (res.label === candidate) streak++; else { candidate = res.label; streak = 1; }
  if (streak >= NEED && conf > 0.35 && candidate !== committed) {
    committed = candidate;
    fireAction(committed);          // edge-triggered: once per transition
  }
  return { committed, conf };
}

Common pitfalls

  • Skipping normalization. The number-one reason a hand classifier "works at my desk and breaks everywhere else." Raw landmark coordinates encode where your hand was and how big it looked. Always subtract the wrist and divide by a size estimate — train invariant or don't train at all.
  • Too few samples. One example per class memorizes the exact pose and the exact angle. Record 5–10 with small natural wobble so the cluster has width.
  • k too large or too small. k=1 is twitchy and trusts a single possibly-mislabeled neighbor; k bigger than your smallest class lets the majority class outvote a correct rare gesture every time. Keep k odd (to avoid ties) and smaller than your per-class sample count.
  • Class imbalance. 50 fists and 3 points means the vote is biased toward fists near the boundary. Keep classes roughly even, or weight votes by inverse distance (see exercises) so a close point can beat several far fists.
  • Trusting the raw prediction. Per-frame k-NN flickers between neighboring classes at the edges. Debounce it (commit after N steady frames) and gate on confidence, or your actions will machine-gun.
  • Lost tracking. When the hand leaves frame MediaPipe returns no landmarks. Guard for null before extracting features; hold the last committed label rather than crashing or snapping to a wrong class.

Exercises

  1. Export / import the model. The whole "model" is the samples object — pure JSON. Add a button that does JSON.stringify(samples) to download it, and a file input that parses it back. Now you can train a gesture set once and ship it. (Bonus: store it in localStorage so it survives a reload.)
  2. Add a "none" reject class. Right now every frame gets forced into A, B, or C. Reject when the nearest distance is above a threshold (or confidence below one) and label it none — so an unknown hand shape stays silent instead of firing a random action.
  3. Weight votes by inverse distance. Replace the plain tally in classify with votes[cls] += 1 / (n.d + ε). Closer neighbors now count for more, which makes small, well-separated classes much harder for a big class to drown out. Compare against the unweighted version on an imbalanced set.

What's next

Episode 20 — GPU-Accelerated Vision Effects. We stop reading the hand and start painting with it: pipe fingertip position and pinch straight into a Three.js ShaderMaterial and let GLSL turn your hand into ripples, displacement, and reaction-diffusion at full frame rate. The classifier you just built becomes a way to switch effects with a gesture. Cross-links: the shaders series for the GLSL, and Episode 21 where the same hand pushes a cloud of Gaussian splats around.