Interactive Vision From Zero · Episode 05

Gesture Recognition

Gesture Recognition is Episode 05 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 05 · Interactive Vision From Zero

Hold up a fist and the page says "fist." Point and it says "point." Two fingers up: "peace." Thumb out: "thumbs-up." No model training, no dataset, no labels you had to collect — just geometry. Each finger is either sticking out or curled in, and that single bit per finger is all the information we need.

Five fingers, one bit each, gives you a 5-bit "finger code" — a number from 00000 to 11111. We read the code straight off the 21 landmarks, look it up in a tiny table, and out pops a gesture name in real time. That finger code is the foundation of every hand-driven shortcut you've ever seen: it's how a flat hand means "stop," how a thumbs-up means "send," how the next episode will turn a pointing finger into a mouse cursor. Wave at the demo below — it's already cycling through gestures with no camera at all.

0 fps
move your mouse to puppet the hand · or use your camera
(autoplay on)
synthetic input · cycling gestures
🔒 runs on-device · nothing leaves your machine
5-bit finger code → gesture
Five bars: how extended each finger is, live from the landmarks.

What you're looking at

The skeleton in the demo is the same 21-landmark hand we've used all series — each joint is one {x, y, z} point in normalized image space. With no webcam, a synthetic hand drives it, and on autoplay it cycles through a playlist — open palm, fist, point, peace, thumbs-up, OK — about every 1.5 seconds, so you can watch the classifier light up different labels without lifting a finger. Move your mouse and you take over the hand's position; click use my camera and your real hand feeds the exact same code path. Synthetic and real are indistinguishable downstream — that's the whole point of working in landmark space.

One convention to call out now, because it confuses everyone: the view is mirrored, like a selfie. We map landmarks to the screen with screenX = (1 - x) * width so that moving your hand to your right moves the on-screen hand to your right. We flip the synthetic hand the same way so both modes agree. If your hand ever appears to go the wrong direction, a forgotten 1 - x is the first suspect.

Stage 1 — Per-finger curl bars

Before we can say "is this finger out or in," we need a continuous measure of how extended each finger is. The five bars on the left of the demo show exactly that: a value from 0 (fully curled) to 1 (fully extended) for thumb, index, middle, ring, and pinky, recomputed every frame.

The trick for the four "normal" fingers is beautifully simple. A finger sticking straight out puts its tip farther from the wrist than its PIP knuckle (the middle joint). Curl the finger and the tip swings back in toward the wrist, eventually closer than the PIP. So we just compare two distances — tip-to-wrist versus PIP-to-wrist — and normalize. No angles, no model, no calibration. Watch a bar drop as the demo curls that finger into a fist.

Stage 2 — Binary fingers (the 5-bit code)

A bar is nice, but a gesture is a discrete thing — you don't want "73% peace." So we threshold each bar with the curl threshold slider: above it, the finger counts as extended (a 1); below it, curled (a 0). Five booleans in finger order [thumb, index, middle, ring, pinky] become a five-character string like 01100 — index and middle up, everything else down. That's peace, encoded as a number.

This is the conceptual heart of the episode. We've compressed a 63-number hand (21 points × 3 coords) down to five bits — 32 possible hand-shapes — and thrown away everything else. Position, rotation, exact angles: gone. What's left is just enough to name a gesture, and small enough to use as a lookup key. Slide the threshold and watch bits flip; you're tuning the boundary between "out" and "in."

Stage 3 — The thumb is special

If you apply the tip-vs-PIP test to the thumb, it lies to you. The thumb doesn't curl toward the wrist the way the other fingers do — it folds sideways across the palm. Its tip can stay roughly the same distance from the wrist whether it's sticking out or tucked in, so the radial test reads it as "always extended." Make a fist in the demo on Stage 3 and you'll see the naive thumb bit stuck on 1 while the others correctly fall to 0.

The fix is to measure the thumb against the side of the hand instead of the wrist. When the thumb is out, its tip (landmark 4) is far from the pinky knuckle (landmark 17, the far side of the palm); when it's tucked in, the tip swings close to that knuckle. So thumb-extension = distance from tip-4 to MCP-17, normalized by hand size. Stage 3 shows both readings side by side — the broken radial one and the corrected sideways one — so you can see the fix land.

Handedness matters here. On a left hand the thumb sits on the opposite side, so "far from the pinky knuckle" still works — but anything that hard-codes "thumb is on the left" will flip. MediaPipe tells you which hand it sees; lean on that rather than assuming.

Stage 4 — Classify: code → gesture

Now the easy part. We have a clean 5-bit code; we map it to a name with a plain object — no machine learning anywhere. Open palm is 11111, fist is 00000, point is 01000, peace is 01100, thumbs-up is 10000. "OK" is the one exception that needs a touch more than the bit vector: it's a pinch (thumb tip touching index tip) with the middle, ring, and pinky extended, so we special-case it by checking the thumb–index distance. The big label in the demo is the winner. Cycle through and watch it call each one.

Stage 5 — Debounce: stop the strobe

Raw landmarks jitter. Near a threshold, a single finger's bit can flicker 0,1,0,1 for a few frames, and the label strobes between two gestures — deeply unconvincing. The fix is the same one keyboards use for noisy contacts: debounce. We only commit a new gesture once we've seen it for N consecutive frames; until then we keep showing the last committed one. Crank the debounce frames slider up and the label gets rock-steady (but a hair slower to react); crank it to 1 and you'll see the raw flicker return. That tradeoff — latency versus stability — is yours to tune.

Stage 6 — Map to action

A label is just a string until it does something. Stage 6 wires each committed gesture to a visible effect: a thumbs-up fires an emoji burst and a "command sent" toast, peace and fist and point each swing the accent color, OK flashes a confirmation. This is the actual payload of gesture recognition — the recognized name is a key into a table of actions, exactly like a keyboard maps a scan-code to a character. Once you can turn a hand-shape into a reliable command, you can drive anything: media controls, slide decks, a game, or in the next episode, the page itself.

How the code works

Four pieces do all the work: a per-finger extension test (with the thumb special case), assembling the bits, the lookup table, and the debounce state machine. Here they are for real.

(a) fingerExtended() — including the thumb

We normalize every distance by a hand-size reference (wrist to middle knuckle) so the numbers don't change when the hand moves closer or farther. The four normal fingers use the radial tip-vs-PIP test; the thumb uses the sideways tip-to-pinky-knuckle test.

// landmark indices
const WRIST = 0, MID_MCP = 9, PINKY_MCP = 17;
const TIPS = [4, 8, 12, 16, 20];   // thumb,index,middle,ring,pinky
const PIPS = [2, 6, 10, 14, 18];   // thumb uses MCP(2) as its mid-joint

const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);

// returns 0..1: how extended finger f is (0 = curled, 1 = straight)
function fingerExtended(lm, f) {
  const handSize = dist(lm[WRIST], lm[MID_MCP]) || 1e-6;

  if (f === 0) {
    // THUMB: it folds sideways, NOT toward the wrist.
    // Measure tip(4) distance from the far side of the palm, pinky-MCP(17).
    // tucked-in ≈ 0.15·handSize, splayed-out ≈ 0.65+ → map that span to 0..1.
    const open = dist(lm[4], lm[PINKY_MCP]) / handSize;
    return clamp01((open - 0.15) / 0.5);   // tuned span → 0..1
  }

  // FINGERS: tip farther from wrist than PIP ⇒ extended.
  const tipD = dist(lm[TIPS[f]], lm[WRIST]) / handSize;
  const pipD = dist(lm[PIPS[f]], lm[WRIST]) / handSize;
  return clamp01((tipD - pipD) / 0.55 + 0.5);
}

const clamp01 = (v) => v < 0 ? 0 : v > 1 ? 1 : v;

(b) Building the 5-bit vector

Threshold each continuous value into a bit, then join into a string we can use as a map key. Order is fixed — thumb, index, middle, ring, pinky — so the same shape always yields the same code.

// curls: [thumb,index,middle,ring,pinky] each 0..1   threshold: slider value
function fingerCode(curls, threshold) {
  const bits = curls.map(v => (v >= threshold ? 1 : 0));
  return { bits, code: bits.join('') };   // e.g. [0,1,1,0,0] → "01100"
}

(c) The code → gesture lookup

A flat object. Adding a gesture is adding a row. "OK" can't be expressed as a pure bit code (it needs the pinch distance), so we test it separately before the lookup.

const GESTURES = {
  '11111': 'open palm',
  '00000': 'fist',
  '01000': 'point',
  '01100': 'peace',
  '10000': 'thumbs-up',
  '00001': 'pinky',
};

function classify(lm, curls, code) {
  // OK = pinch (thumb tip ~ index tip) with middle/ring extended
  const handSize = dist(lm[0], lm[9]) || 1e-6;
  const pinch = dist(lm[4], lm[8]) / handSize;
  if (pinch < 0.35 && curls[2] > 0.5 && curls[3] > 0.5) return 'OK';
  return GESTURES[code] ?? '…';   // unknown shape → ellipsis
}

(d) The debounce / commit state machine

Keep a candidate and a counter. Every frame, if the raw reading matches the candidate, increment; otherwise reset the candidate. Only when the counter reaches N do we commit — promoting the candidate to the displayed gesture and firing its action exactly once.

const debouncer = {
  candidate: '…', count: 0, committed: '…',
  // returns the committed gesture, and whether it JUST changed this frame
  feed(raw, frames) {
    if (raw === this.candidate) this.count++;
    else { this.candidate = raw; this.count = 1; }

    let changed = false;
    if (this.count >= frames && raw !== this.committed) {
      this.committed = raw;          // promote after N stable frames
      changed = true;                // fire the action exactly once
    }
    return { gesture: this.committed, changed };
  }
};

Notice the single downstream path: synthetic frames and camera frames both arrive as a 21-point hand, run through the same onLandmarks(hand), and nothing below it knows or cares where the hand came from. That's why the demo is alive before you ever grant camera access — and why your real hand works the instant you do.

Common pitfalls

  • Treating the thumb like a finger. The radial tip-vs-PIP test reports the thumb as permanently extended, because it folds sideways, not inward. Test it against the pinky-MCP (or the angle at the thumb IP) instead, as in Stage 3.
  • Handedness flips the thumb. Left and right hands mirror, so the thumb's "far side of the palm" swaps sides. Use MediaPipe's reported handedness rather than assuming a side, or your thumb logic will invert on the other hand.
  • One threshold doesn't fit every hand. Finger proportions vary; a curl threshold that's crisp for you may read a child's hand or a very flat palm wrong. Expose it (we did) or auto-calibrate from a known open-palm frame.
  • Jitter near the threshold. A bit parked right at the boundary flickers and strobes the label. Debounce (Stage 5), or add hysteresis with separate on/off thresholds, as we did for pinch in Episode 03.
  • Occluded fingers give garbage landmarks. A finger hidden behind the palm, or a hand half out of frame, produces guessed, unstable points — and bad bits. Guard for low-confidence or off-screen landmarks and don't trust a code built from them.
  • Camera needs HTTPS or localhost. Opened from file://, getUserMedia is silently blocked; the catch keeps the synthetic demo running so the page never breaks.

Exercises

  1. Rock / paper / scissors. Map fist → rock, open palm → paper, peace → scissors, then add a second hand (numHands: 2) and a tiny rules table to declare a winner each round. You've built a referee out of two 5-bit codes.
  2. A custom gesture. Add "call me" (10001 — thumb and pinky out) or "spiderman"/rock-on and give each its own row in GESTURES. Notice some shapes collide in 5 bits and need an extra geometric test, just like OK did — that's the natural limit of a pure bit vector.
  3. Drive a fake media player. Drop a play/pause button and a track label in the page, then have committed gestures act as shortcuts: fist = pause, open palm = play, thumbs-up = next track. Use the changed flag from the debouncer so each gesture fires the command once, not every frame.

What's next

Episode 06 — Control the DOM. We stop naming what the hand is doing and start using it: a pointing finger becomes a real cursor you can move across the page, a pinch becomes a click, and holding the pinch becomes a drag. The finger code you built today becomes the mode switch — point to move, pinch to grab — and the page becomes something you operate with your bare hand in the air.