Interactive Vision From Zero · Episode 11
Rep Counter
Rep Counter is Episode 11 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 .
Point a webcam at yourself, drop into a squat, stand back up — and watch a number tick: 1. That's the whole promise of this episode. We're building the thing every fitness app charges a subscription for, in about forty lines of plain JavaScript, running entirely on your machine. No wearable, no sensor, no account. Just the 33-point body pose from the last two episodes, a little trigonometry, and a state machine that knows the difference between "going down" and "coming up."
The demo below is already counting. A synthetic body is doing squats and jumping jacks on a loop, and the big counter ticks every time it completes one — with no camera on. That's deliberate: the rep logic is the star, and you can watch it work before you ever grant a webcam. Flip the exercise dropdown to switch between squats and jacks, drag the depth slider to demand deeper reps, then hit use my camera and start working out. The same counter that's ticking for the synthetic body will tick for you.
What you're looking at
That's a body — synthetic, built from the same 33-landmark structure MediaPipe Pose emits, so every line of counting code below runs unchanged on a real webcam. It's alive on first paint with no camera: the figure squats down and stands up (or fires off jumping jacks) on a gentle loop, and the counter climbs as it completes each rep. Switch the exercise and the same body changes its motion to match. When you're ready, hit use my camera and the identical pipeline starts reading your real body instead — same angles, same state machine, same counter.
One convention up front, because it's the number-one source of "why is it backwards"
confusion: this is a selfie view, so we mirror the X axis. On screen we
plot every landmark at (1 - x) * width, and we apply that same flip to the
synthetic body, so leaning right moves the on-screen figure right. Camera and synthetic
modes stay in lockstep. (Counting itself doesn't care about the mirror — an angle is an
angle — but the drawing does.)
The badge in the corner is the entire episode in one word: reps. Everything below is earning the right to trust that number — to make it tick exactly once per honest rep, never twice, never on a half-rep. Step through the six stages with the dropdown.
Stage 1 — A joint angle
Counting reps starts with one measurement: the angle at a joint. A squat is really a story about your knee angle — wide open when you stand (near 180°), folded shut when you're deep in the hole (down toward 70°). So we take three landmarks — hip (23), knee (25), ankle (27) — and compute the angle at the middle one. This stage just draws that: an arc at the knee and a live degree readout that breathes as the synthetic body bobs. No counting yet, no thresholds — just proof that we can turn three dots into one honest number. Switch the exercise to jumping jack and the measured joint moves to the shoulder (11), between hip and elbow, because that's the angle a jack opens and closes.
Stage 2 — The up/down state machine
One angle isn't a rep — a rep is a trip: down, then back up. So we add a tiny
state machine with exactly two states, "up" and "down". When
the angle drops below a low threshold we enter "down"; when
it climbs back above a high threshold we return to "up".
The two thresholds are deliberately different — that gap is hysteresis,
and it's the whole trick. This stage draws both threshold lines on the angle meter and
lights up the current state. Watch the marker cross down through the low line into
down, then rise through the high line back to up. Drag the depth
slider and watch the low line move: that's how "how deep counts" is set.
Stage 3 — Count squats
Now we wire the state machine to a counter. The rule is dead simple and it's the heart
of every rep tracker ever shipped: increment on the up edge — the single
frame the state flips from down back to up. One full
down→up cycle, one rep. Because the increment only fires on the transition (not while
you're held down, and not while you're standing), you get exactly one count per squat. A
big number lands center-screen and pulses on each rep. Stand the synthetic body up halfway
and it never counts — you have to complete the trip. That's hysteresis quietly doing its
job.
Stage 4 — Jumping jacks
The beautiful part: the counting machine doesn't know or care what exercise it's counting. Switch to jumping jack and nothing about the state machine changes — we just feed it a different angle. A jack lives in the arm spread: the angle at the shoulder between the hip and the elbow, which swings wide as your arms go up and folds shut as they come down. Same low/high thresholds (rescaled for this joint's range), same up-edge increment, separate counter. The synthetic body throws real jacks — arms up, legs out, arms down — and the jack counter climbs. One state machine, any exercise: that's the payoff of measuring angles instead of positions.
Stage 5 — Form feedback
A counter that rewards garbage reps is a bad coach. So we track the achieved range of each rep — how far the angle actually traveled between the top and the bottom — and judge it. Go deep enough and the rep counts with a green "good rep!"; cut it short and you get "go deeper" and no count. A depth bar fills as you descend so you can see exactly how close to the bottom you are. This is the line between a toy and a tool: the machine now enforces a minimum range, which kills the cheat of tiny bouncy half-reps. Drag the depth slider up to demand more; the synthetic body's reps will start getting rejected until they're deep enough.
Stage 6 — Workout HUD
Finally, the dashboard. We surround the rep count with the things that make a set feel like a workout: a set count (every N reps closes a set), a tempo readout in seconds-per-rep (measured from the time between up edges — too fast and you're bouncing, too slow and you're resting), and a line of encouragement that reacts to your pace and form. It's the same numbers from the stages before, arranged the way an actual coach app would show them. Let the synthetic body run and the HUD fills in: reps climb, sets tick over, the tempo settles, and the encouragement keeps pace.
How the code works
The whole tracker is four small pieces: a three-point angle function, a hysteresis rep state machine, the wiring that points the chosen exercise's joints at the counter, and the form check that grades the achieved range. None of it is longer than a paragraph.
(a) The three-point joint angle
The angle at landmark B formed by A–B–C is the angle between
two bone vectors: B→A and B→C. The clean, wrap-safe way to get
it is atan2 on each vector and subtract — then fold the result into
[0, 180] so it never jumps from 359° to 1°. We work in normalized landmark
space; angles don't care about pixels or aspect ratio.
// angle at B (degrees) for the corner A–B–C, using two bone vectors + atan2
function jointAngle(A, B, C) {
const a = Math.atan2(A.y - B.y, A.x - B.x); // direction B→A
const c = Math.atan2(C.y - B.y, C.x - B.x); // direction B→C
let deg = (c - a) * 180 / Math.PI; // signed difference
deg = Math.abs(deg); // we only want magnitude
if (deg > 180) deg = 360 - deg; // fold the wrap: keep it in [0,180]
return deg;
}
(b) The rep state machine (hysteresis)
This is the reusable core. It owns one bit of state — are we currently down?
— plus the lowest angle seen during the current descent (for the range check). You enter
down only when the angle drops below low, and you count only when
it rises back above high. Because low < high, a value
shivering near one line can never double-count: it has to cross the whole dead-band and
complete the cycle.
// low < high. Go BELOW low to enter "down"; rise ABOVE high to finish a rep.
function makeRepCounter() {
let isDown = false, reps = 0, minAngle = 180;
return function update(angle, low, high, minRange) {
let counted = false, rejected = false;
if (!isDown && angle < low) { // top → bottom: begin the rep
isDown = true; minAngle = angle;
} else if (isDown) {
minAngle = Math.min(minAngle, angle); // track how deep we got
if (angle > high) { // bottom → top: the rep is over
isDown = false;
const range = high - minAngle; // achieved depth this rep
if (range >= minRange) { reps++; counted = true; } // deep enough → count
else rejected = true; // partial rep → reject
}
}
return { reps, isDown, minAngle, counted, rejected };
};
}
(c) Wiring the chosen exercise's joints → counter
An exercise is just a recipe: which three landmarks to measure and what low/high thresholds to use. Swapping exercises swaps the recipe; the counter is untouched. Here squats read the knee corner and jacks read the shoulder corner — and we average left and right so a slightly turned body still tracks cleanly.
// MediaPipe Pose indices: 11/12 shoulders, 13/14 elbows, 23/24 hips, 25/26 knees, 27/28 ankles
const EXERCISES = {
squat: { // knee angle: hip–knee–ankle, wide standing, folds toward ~70° deep
left: [23, 25, 27], right: [24, 26, 28], low: 110, high: 125, full: 55,
},
jack: { // arm spread: hip–shoulder–elbow, wide ~160° up, ~20° down
left: [23, 11, 13], right: [24, 12, 14], low: 60, high: 120, full: 70,
},
};
function measure(lm, ex) {
const [a1,b1,c1] = ex.left, [a2,b2,c2] = ex.right;
// skip a side whose joints are low-visibility; average what we trust
const L = vis(lm, a1,b1,c1) ? jointAngle(lm[a1], lm[b1], lm[c1]) : null;
const R = vis(lm, a2,b2,c2) ? jointAngle(lm[a2], lm[b2], lm[c2]) : null;
if (L == null && R == null) return null; // nothing trustworthy → skip the frame
return L == null ? R : R == null ? L : (L + R) / 2;
}
(d) Form feedback from the achieved range
The state machine already hands back counted vs rejected and
the minAngle it reached. Form feedback is just reading those: a live depth
bar from the current angle, and a verdict on each completed rep. The depth slider feeds
minRange, so "how deep counts" is a knob, not a magic constant.
function onLandmarks(lm) { // ONE path for synthetic + camera
const ex = EXERCISES[currentExercise];
const angle = measure(lm, ex);
if (angle == null) return; // low-visibility frame: hold state, draw nothing new
// depth slider (0..1) scales the required range between a token dip and a full rep
const minRange = ex.full * (0.45 + 0.5 * depthSlider);
const r = counter(angle, ex.low, ex.high, minRange);
// live depth: how far through the rep's full travel are we right now?
depthPct = clamp((ex.high - angle) / ex.full, 0, 1);
if (r.counted) feedback = 'good rep!';
if (r.rejected) feedback = 'go deeper';
repCount = r.reps;
}
(e) Same path for synthetic and camera
The counter takes an angle and returns a struct. It has no idea
whether the 33 landmarks behind that angle came from a math function or a neural net
reading your webcam. That's the architecture of the whole series: one
onLandmarks(pose) path, fed by whichever source is live. The synthetic driver
is told to do reps — we oscillate a squat/jack amount — so the counter ticks
before any camera is on.
const POSE_TASK =
'https://storage.googleapis.com/mediapipe-models/pose_landmarker/' +
'pose_landmarker_lite/float16/1/pose_landmarker_lite.task';
function loop(now) {
let pose;
if (usingCamera && landmarker && video.readyState >= 2) {
const res = landmarker.detectForVideo(video, now);
pose = res.landmarks?.[0] || null; // null when no body in frame
} else {
const phase = (Math.sin(now * 0.0022) + 1) / 2; // 0..1 rep oscillation
const opts = currentExercise === 'jack' ? { jack: phase } : { squat: phase };
pose = syntheticPose(now * 0.001, autoPos(now), opts); // driven to DO reps
}
if (pose) onLandmarks(pose); // ONE downstream path for both
render(now);
requestAnimationFrame(loop);
}
Common pitfalls
- Doing the angle math by hand and getting the wrap wrong. Subtracting
raw coordinates or using
acosof a dot product without clamping blows up at the edges (a domain error, or a flip from 179° to 181° that your thresholds read as two crossings). Use two bone vectors,atan2on each, subtract, then fold into[0,180]— exactly the helper above. It never throws and never jumps. - Double-counting. A single threshold counts every time the noisy
angle wiggles across it — you'll get three reps from one squat. The fix is two ideas
together: separate enter (
low) and exit (high) thresholds for a dead-band, and require a fulldown → upcycle before incrementing. Count on the up edge only, never on the held state. - Measuring the wrong joint for the exercise. Squats live in the knee (hip–knee–ankle); jacks live in the shoulder (hip–shoulder–elbow); curls live in the elbow (shoulder–elbow–wrist). Point the counter at the joint that actually opens and closes for that movement, or the angle barely changes and nothing counts.
- Partial reps sneaking through. If you only check "did the angle cross back," a tiny bounce near the top counts as a rep. Track the deepest angle reached during the descent and require a minimum achieved range before you count. That single check turns a rep counter into a rep judge.
- Low-visibility joints. When a knee leaves frame or an arm crosses the
body, MediaPipe still returns a landmark — with a low
visibilityand a wild position. Feeding that to the angle math produces garbage crossings. Checkvisibility(skip a side below ~0.5), and if neither side is trustworthy, skip the whole frame and hold the last state rather than counting noise. - Camera only works on localhost / HTTPS. Opening the file via
file://silently blocksgetUserMedia. The synthetic demo still counts away; serve overlocalhostto try the webcam.
Exercises
- Add push-ups. A push-up is the elbow angle:
shoulder–elbow–wrist (
[11,13,15]/[12,14,16]), open at the top (~165°), folded at the bottom (~80°). Add anEXERCISES.pushupentry with those joints and thresholds, drop it in the exercise dropdown, and you've added a whole movement without touching the counter — proof the architecture holds. - Build a tempo metronome. You already stamp the time on each up edge. Turn that into a target: pick a goal seconds-per-rep, and tint the depth bar green when the rep lands within the window, red when you're bouncing or stalling. Now the counter coaches pace, not just count — the difference between reps and good reps.
- Score rep quality from smoothness. Record the angle samples across one rep and measure how jerky the path was (e.g. the variance of frame-to-frame angle change). A smooth, controlled descent scores high; a flaily, jerky one scores low. Show a 0–100 quality score per rep — the start of real form analysis from nothing but landmarks.
What's next
Episode 12 — Face Mesh & AR Filters. We swap the 33-point body for the 468-point face mesh and start anchoring things to your face: glasses that sit on the bridge of your nose, a crown on your forehead, a mask that tracks as you turn your head. Same rules as always — alive on first paint via a synthetic face, MediaPipe lazy-loaded behind your camera, one shared landmark path — but now the payoff is the Snapchat filter you've used a thousand times, built from scratch. The state-machine instinct you just built carries straight over: in Episode 13 a blink and a mouth-open become triggers, detected with the very same hysteresis you used to count a squat.