Interactive Vision From Zero · Episode 15
Multi-Person: Track a Whole Room
Multi-Person: Track a Whole Room is Episode 15 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 .
Every demo so far has been about you — one hand, one face, one body. But a
camera doesn't see "you," it sees a frame, and a frame can hold a crowd.
Flip one option — numPoses: 2 — and MediaPipe hands you back an
array of skeletons. Suddenly the question isn't "where's the wrist," it's
"whose wrist, and is it still the same person it was last frame?" That second question is
the whole episode.
The demo below is alive right now, no camera, nothing downloaded: two synthetic bodies are walking in place, each with a stable colored ID badge that survives even when they cross paths. Step through the six stages to watch a pile of anonymous dots turn into named players P1 and P2, link up when they get close, and finally play a live mirror-match game. Then hit use my camera and grab a friend — the same two skeletons snap onto two real people. 🔒 on-device · nothing uploaded.
What you're looking at
The single-body episodes fed one array of 33 landmarks into drawPose. Here
the source — synthetic or camera — emits an array of those arrays:
[ pose0, pose1, … ], each pose still the familiar list of
{ x, y, z, visibility }. Everything downstream loops over that outer array, so
the code you wrote for one person scales to a room without changing how a single skeleton is
drawn.
Two synthetic walkers idle on first paint, swinging arms and legs out of phase so they look like two different people, not a mirror image. Drag your mouse to shove P1 around — including straight through P2 — to watch identity tracking fight (and sometimes lose) the moment two bodies overlap. The people slider clones up to six synthetic bodies so you can feel the cost and the roster grow. None of this needed a webcam or a network request.
Stage 1 — Draw all the skeletons
The first job of multi-person is almost free: stop reading poses[0] and
loop. MediaPipe returns result.landmarks as an array, one entry per
detected body, capped by numPoses. Iterate it and call your existing
single-pose draw for each:
// (a) Iterate the array of poses and draw each one
function onLandmarks(poses) { // poses: [[{x,y,z,visibility}×33], …N]
clear();
for (const pose of poses) {
drawSkeleton(pose); // the SAME draw you wrote for one body
}
}
// camera path — note numPoses, and that landmarks is already an array:
const res = landmarker.detectForVideo(video, performance.now());
onLandmarks(res.landmarks || []); // [] when the room is empty — guard it
That alone gets you two glowing skeletons. But they're anonymous: the array order is whatever the model felt like this frame, and it can — and does — reshuffle between frames. Colour by array index and the colours will strobe and swap. We need identity.
Stage 2 — Stable IDs: match each pose to the nearest previous one
The fix is tracking: remember last frame's bodies (their tracks), and this frame, hand each new detection to whichever old track it's closest to. "Closest" needs a single point per body — the centroid, the average of a few reliable landmarks (shoulders + hips is stable; faces and hands jitter). Then greedily pair nearest centroids, with a distance cap so a body that genuinely vanished doesn't get hijacked by a stranger on the far side of the frame:
// (b) Greedy nearest-centroid identity tracking
const MAX_MATCH = 0.18; // max centroid travel/frame (normalized units)
let tracks = []; // [{ id, cx, cy, missing }] survives across frames
let nextId = 1;
function centroid(pose) { // shoulders 11/12 + hips 23/24
let x = 0, y = 0, n = 0;
for (const i of [11, 12, 23, 24]) {
const p = pose[i];
if (p && (p.visibility ?? 1) > 0.5) { x += p.x; y += p.y; n++; }
}
return n ? { x: x / n, y: y / n } : null;
}
function assignIds(poses) {
const dets = poses.map(p => ({ pose: p, c: centroid(p) })).filter(d => d.c);
const used = new Set();
const out = [];
// 1) each detection grabs its nearest unused track within the cap
for (const d of dets) {
let best = null, bestDist = MAX_MATCH;
for (const tr of tracks) {
if (used.has(tr.id)) continue;
const dist = Math.hypot(d.c.x - tr.cx, d.c.y - tr.cy);
if (dist < bestDist) { bestDist = dist; best = tr; }
}
if (best) { // matched → keep its ID
best.cx = d.c.x; best.cy = d.c.y; best.missing = 0;
used.add(best.id);
out.push({ id: best.id, pose: d.pose });
} else { // no match → a new joiner
const tr = { id: nextId++, cx: d.c.x, cy: d.c.y, missing: 0 };
tracks.push(tr); used.add(tr.id);
out.push({ id: tr.id, pose: d.pose });
}
}
// 2) keep unmatched tracks alive briefly (occlusion), then drop them
tracks = tracks.filter(tr => used.has(tr.id) || ++tr.missing < 15);
return out; // [{ id, pose }] — id is stable frame to frame
}
Turn this stage on and the IDs stick: P1 stays P1 as it strolls. Drag P1
across P2 and watch the seam — when centroids pass within MAX_MATCH of each
other, greedy matching can briefly grab the wrong one. That swap is the headline pitfall,
and we'll name the real fix below.
Stage 3 — A color and a label per person
Once each body carries a stable ID, identity becomes cosmetic: hash the ID into
a palette and stamp a P{id} label above the head. Crucially this keys off the
tracked id, never the array index — that's the difference between calm,
constant colours and a disco:
// (c) Per-person color + label, keyed on the STABLE id (not array index)
const TEAM = ['#38bdf8', '#f472b6', '#34d399', '#fbbf24', '#a78bfa', '#fb7185'];
const colorFor = (id) => TEAM[(id - 1) % TEAM.length];
function drawPerson({ id, pose }) {
const col = colorFor(id);
drawSkeleton(pose, col); // tint the bones + dots
const head = toPixel(pose[0]); // landmark 0 = nose
ctx.fillStyle = col;
ctx.fillText('P' + id, head.x, head.y - 14); // floating P1 / P2 badge
}
Because colorFor reads the persistent ID, P1 is always blue and P2 always
pink — even after one of them walks out of frame and back in (they keep their slot until the
track ages out). A genuine newcomer gets the next free ID, and therefore the next colour.
Stage 4 — Interaction: a spark when two people touch
Two tracked bodies in the same coordinate space is all you need for the first multiplayer primitive: proximity. Compare a key landmark across every pair of people — here the wrists, the most "reach out and touch" joint — and when the gap drops under a threshold, draw a link and a spark. This is the seed of high-fives, hand-offs, tag, and conga lines:
// (d) Two-person interaction: link wrists that come close
const TOUCH = 0.12; // normalized distance threshold
const WRISTS = [15, 16]; // left + right wrist landmarks
function drawLinks(people) {
for (let a = 0; a < people.length; a++) {
for (let b = a + 1; b < people.length; b++) { // each unordered pair
for (const i of WRISTS) for (const j of WRISTS) {
const p = people[a].pose[i], q = people[b].pose[j];
const d = Math.hypot(p.x - q.x, p.y - q.y);
if (d < TOUCH) spark(toPixel(p), toPixel(q), 1 - d / TOUCH);
}
}
}
}
In synthetic mode the two walkers periodically drift their hands together and a bright arc snaps between them. With a friend on camera, reach out and bump fists — the link lights up. Note the loop is over pairs, so it already works for three or more: every couple in the room that touches gets its own spark.
Stage 5 — A 2-player game: mirror-match
Proximity is binary; a game wants a score. Mirror-match asks P2 to copy P1's pose, and rewards how well they line up. The trick is to compare shapes, not screen positions: re-center each body on its own centroid and scale by its torso height, then average the joint-to-joint distance. Subtract from 1 and you have a 0→100% similarity meter that ignores where each player stands:
// Pose similarity → a mirror-match score (centroid- and scale-normalized)
function poseSim(A, B) {
const ca = centroid(A), cb = centroid(B);
const sa = torsoLen(A), sb = torsoLen(B); // shoulder→hip distance
if (!ca || !cb || !sa || !sb) return 0;
const JOINTS = [11,12,13,14,15,16,23,24,25,26,27,28];
let sum = 0;
for (const i of JOINTS) {
const ax = (A[i].x - ca.x) / sa, ay = (A[i].y - ca.y) / sa;
const bx = (B[i].x - cb.x) / sb, by = (B[i].y - cb.y) / sb;
sum += Math.hypot(ax - bx, ay - by);
}
const avg = sum / JOINTS.length; // 0 = identical shape
return Math.max(0, 1 - avg); // → [0,1] similarity
}
A big arc shows the live match percentage between the first two players, and it pulses green as they sync up. (In synthetic mode the two walkers are deliberately out of phase, so the meter breathes between ~40% and ~90% — proof it's measuring shape, not luck.) Swap to pose-pong by mapping each player's wrist height to a paddle and you've got a second game from the same numbers.
Stage 6 — Scaling: N people and a roster
Nothing above assumed exactly two. Drag the people slider and the same
pipeline — iterate, track, colour, pair — fans out to a crowd, each body holding its own ID
and colour, with a live roster down the side listing who's on screen. On
the camera path you'd raise numPoses; just know it isn't free (next section).
This is the shape of every "track a room" feature — sports analytics, dance games, crowd
interactives — built from one array, one matcher, one palette.
Common pitfalls
- Identity swaps when people cross. Greedy nearest-match is fooled
when two centroids pass close together — IDs (and colours) can trade. The cheap defenses
are the
MAX_MATCHdistance cap and matching on a stable centroid (torso, not a flailing hand). The proper fix is global assignment — the Hungarian algorithm minimizes total matching cost across all pairs at once, instead of letting the first body greedily grab a track the second body needed. Real trackers also add motion prediction (a Kalman filter) and an appearance embedding so a body is matched by how it looks, not just where it is. numPosesis not free. Detection cost scales with the cap — every extra body is more work on the main thread each frame. SetnumPosesto the most you actually expect (2 for a duo) rather than a hopeful 10; an idle high cap burns frames for bodies that aren't there.- Occlusion drops a person. When one body walks behind another the
model can emit fewer poses for a frame or two, and a naive tracker deletes the track and
re-issues a fresh ID on return. Keep an unmatched track alive for a handful of frames
(the
missing < 15grace window above) so a brief disappearance doesn't reset their identity, colour, and score. - Mirror, still. It's selfie view: map with
screenX = (1 − x) · widthso reaching right moves the on-screen body right. Apply the flip to the synthetic bodies too, so synthetic and camera modes agree — and so "P2, mirror me" feels natural instead of inverted. - A new joiner must get a fresh ID. Don't recycle P1's slot for the
third person who walks in — that's how colours suddenly lurch. A detection with no track
within the cap is a newcomer: hand it
nextId++and let it claim the next free colour. - Empty room.
result.landmarksis[]when no one is in frame. Guard the loop (and your "match the first two players" code) so zero or one body doesn't throw.
Exercises
- Conga line. Instead of linking every touching pair, sort the people left-to-right by centroid X and draw a link from each person's hand to the next person's hand. Now the room forms one chain — a live conga line that reorders itself as people shuffle.
- Team colors. Split the centroid X at
0.5and tint everyone on the left one team colour, everyone on the right another — then count bodies per side into a tiny scoreboard. Watch a player switch teams by walking across the midline (and notice their stable ID stays put even as their colour flips). - High-five detector. Upgrade the wrist-proximity link into a gesture:
a high-five is two wrists that come close and are both raised above their
owner's shoulders (
wrist.y < shoulder.y) and moving toward each other. Fire a one-shot burst + sound only on the frame the gap crosses the threshold — add hysteresis so a held high-five doesn't machine-gun.
What's next
Episode 16 — the Season 2 body finale. We pull the whole season together — pose skeletons, avatars, rep counting, face filters, and this episode's multi-person identity tracking — into one capstone build, and look ahead to where body and face tracking go next: 3D world coordinates, temporal smoothing at scale, and shipping a real-time interactive to a room full of strangers. For the rendering side of "a crowd of moving bodies," the splat season (Gaussian Splatting From Zero) is the natural companion.