Interactive Vision From Zero · Episode 13
Gaze, Blink & Mouth
Gaze, Blink & Mouth is Episode 13 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 .
Last episode we decorated the face. This one we listen to it. Your eyes already point at what you care about; your blinks are crisp, deliberate clicks; your mouth opens on command. Wire those three signals to actions and the face becomes a controller you never have to hold: blink to shoot, look to aim, open your mouth to act. No mouse, no keyboard — just a webcam and the dozen landmarks we already know how to find.
The demo below is alive the instant it loads, with no camera and nothing downloaded. A synthetic face is blinking, glancing around, and opening its mouth on a timer — and the detectors are firing on it right now: the blink counter ticks, the gaze arrow swings, the mouth meter fills. That's the whole point — every signal you'll wire to your own face is already proven against math-driven dots. Click use my camera and the exact same EAR, gaze, and mouth pipeline reads you instead.
🔒 The camera button runs the model entirely in your
browser. No frame is ever uploaded; nothing leaves your machine.
Until you press it, the demo uses a synthetic face and makes zero network requests.
What you're looking at
Three independent signals, each pulled from the same face struct we built in Episode 12, each turned into something you can act on:
- Blink — from the eye-aspect-ratio (EAR): the vertical lid gap divided by the horizontal eye width. Eyes open, EAR is high; eyes shut, it collapses. Cross a threshold downward and you've blinked.
- Gaze — from where the iris sits inside the eye box. Iris pushed to the left edge → you're looking left. Up, down, right, all the same. It's a tiny offset, normalized by eye size, turned into a direction.
- Mouth-open — from the lip gap (upper lip to lower lip), divided by the face size so it means the same thing near or far. Past a threshold, the mouth is "open" — a big, unmistakable, hands-free button.
Step the stage dropdown to build them up one at a time, then map them to actions, then play a tiny game with them. The two sliders let you tune the blink and mouth thresholds live — you'll feel why that matters in a moment.
The landmarks these three signals ride on
We don't need all 468 (or 478) points — just the handful around each eye and the lips. From Episode 12's named-feature table, here are the ones that carry today's signals:
Two ratios do all the work. EAR = (lid gap) ÷ (eye width) gives a
number near 0.3 for an open eye and near 0.05 for a closed one —
and because it's a ratio, it's the same whether your face fills the frame or sits across
the room. Mouth openness = (lip gap) ÷ (face size) is the same trick for
the mouth. Ratios are how you build detectors that don't break when you lean in.
Stage 1 — Eye landmarks + EAR
Start by seeing the number. This stage draws each eye — its four key points and a box around them — and prints the live EAR for the left and right eye. Watch the synthetic face blink: both numbers dive toward zero for a few frames, then snap back. That dip is the entire blink signal. Everything after this is "notice when the number crosses a line." If you only remember one formula from this episode, make it EAR = lid gap ÷ eye width.
Stage 2 — Blink detection
Now we turn the dip into an event. When EAR drops below the blink threshold (the slider), that's a closed eye; when it comes back up, that's one blink — and the screen flashes and a counter ticks. The subtle part is the refractory window: once we count a blink we ignore EAR for ~250 ms, so a single slow closure can't register as five blinks. Drag the threshold and you'll feel the trade-off: too high and every glance counts; too low and real blinks are missed. This is why good face controls calibrate.
Stage 3 — Gaze direction
Where are you looking? Find the iris center, measure how far it sits from the center of the eye box, and normalize by the eye's width and height. That gives a little vector: push it left and you're looking left, up and you're looking up. We draw an arrow from the face that follows your gaze. (Heads-up: real iris landmarks need the 478-point model — the Face Landmarker provides them; if you only had the 468-point mesh you'd approximate gaze from the eye corners. More on that in the pitfalls.) Remember the mirror: in the selfie view, your left is screen-right.
Stage 4 — Mouth-open
The simplest signal and the most reliable. Measure the gap between the upper and lower lip, divide by the face size, and you get a 0→1 "openness." A meter fills as the synthetic mouth opens; cross the mouth threshold (slider) and it latches to OPEN. Because it's normalized by face size, the same threshold works whether you're close or far. Mouth-open is the big red button of face control: hard to trigger by accident, easy to do on purpose.
Stage 5 — Map to actions
Three signals, three actions, wired up. A blink spawns a pulse (think "shoot"); your gaze aims a reticle that glides around the screen; mouth-open charges a beam that grows the longer you hold it. This is the abstraction that matters: a detector emits an event or a value, and the app decides what it means. Swap "spawn a pulse" for "jump," "fire," or "next slide" and you've got a different app with the same plumbing.
Stage 6 — A tiny face-controlled toy
Put it together into a little game. Targets drift in; look to aim the reticle, and blink or open your mouth to fire at whatever it's over. Hit a target, score a point. It's deliberately tiny, but it's a complete face-only control loop — aim with gaze, act with a blink or a mouth-open, get feedback, repeat. On the synthetic face it even plays itself a little, because the gaze and blink signals keep firing. Plug in your camera and you're the controller.
How the code works
Same spine as the whole series: one onLandmarks(face) path
feeds both the synthetic face and the real camera. The synthetic driver hands us a named
struct (with an animated iris offset, blink, and mouth-open); the camera path builds the
identical struct from the raw landmark array. Below that line, the blink, gaze, and
mouth code can't tell which it got.
(a) Eye-aspect-ratio (EAR) from the eye landmarks
EAR is one division: the vertical lid gap over the horizontal eye width. Both come
straight from the named features — the gap is stored as eye.open, the width is
the distance from the eye's inner corner to its outer corner. Dividing makes it
scale-invariant, so one threshold fits every distance:
// EAR = vertical lid gap ÷ horizontal eye width. Ratio ⇒ distance-invariant.
const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
function earFor(eye) {
// eye.open = lid gap (dist of upper↔lower lid landmark)
// eye.width = eye width (dist of inner↔outer corner)
return eye.width > 1e-5 ? eye.open / eye.width : 0;
}
// On the camera path the two distances come from the 468-array directly:
// left.open = dist(lm[159], lm[145]); // upper lid ↔ lower lid
// left.width = dist(lm[33], lm[133]); // outer corner ↔ inner corner
const ear = (earFor(face.leftEye) + earFor(face.rightEye)) / 2;
(b) Blink = EAR below threshold, with a refractory window
The naive "EAR < threshold ⇒ blink" counts one long closure as dozens of blinks. The fix is a tiny state machine: only count the transition from open to closed, then refuse to count again until a refractory window has passed. That window is the single line that turns a noisy threshold into clean, one-per-blink events:
let eyesClosed = false, lastBlink = -1e9, blinks = 0;
const REFRACTORY = 250; // ms — ignore new blinks this long after one
function updateBlink(ear, threshold, now) {
if (!eyesClosed && ear < threshold && now - lastBlink > REFRACTORY) {
eyesClosed = true; // open → closed: this is THE blink
blinks++; lastBlink = now;
return true; // fire the action (shoot / click)
}
if (eyesClosed && ear > threshold + 0.03) {
eyesClosed = false; // closed → open: re-arm (note hysteresis)
}
return false;
}
(c) Gaze from the iris offset inside the eye box
Gaze is the iris position relative to the eye, normalized by eye size so it's a clean −1→+1 in each axis. Center of the eye is the midpoint of the inner and outer corner; subtract that from the iris, divide by half the eye width (and a bit of height), and you have a direction vector. Mirror X so "look left" reads left in the selfie view:
// gaze ∈ [-1,1]² (x: -1 looking right-of-screen … +1 left; we flip for selfie)
function gazeFor(eye) {
const halfW = eye.width / 2;
const dx = (eye.iris.x - eye.c.x) / (halfW || 1e-5); // iris offset, normalized
const dy = (eye.iris.y - eye.c.y) / (halfW || 1e-5);
return { x: dx, y: dy };
}
// Average both eyes, then flip X for the mirror (selfie view):
const g = gazeFor(face.leftEye), h = gazeFor(face.rightEye);
const gaze = { x: -(g.x + h.x) / 2, y: (g.y + h.y) / 2 };
(d) Mouth-open = lip gap ÷ face size
Same ratio trick as EAR, aimed at the lips. The lip gap is the distance from the upper
lip landmark to the lower lip; faceSize is any stable span — we use the
interocular distance. One threshold then works at any distance:
// mouthOpen ∈ 0..1-ish ; faceSize = interocular distance (a stable ruler)
const faceSize = dist(face.leftEye.c, face.rightEye.c);
const mouthOpen = faceSize > 1e-5 ? face.mouth.open / faceSize : 0;
const isOpen = mouthOpen > mouthThreshold; // the hands-free "button"
// On camera: face.mouth.open = dist(lm[13], lm[14]) (upper lip ↔ lower lip)
(e) The FaceLandmarker, loaded lazily
MediaPipe is never imported at the top of the file — only inside the
camera button's handler, wrapped in try/catch so any failure (no webcam,
denied permission, file://) falls back to the synthetic face. The Face
Landmarker ships the iris points we need for gaze, so we read
result.faceLandmarks[0] and build the same struct:
const MP_URL = 'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.18';
const MP_WASM = MP_URL + '/wasm';
const FACE_TASK = 'https://storage.googleapis.com/mediapipe-models/' +
'face_landmarker/face_landmarker/float16/1/face_landmarker.task';
async function enableCamera() {
try {
const { FaceLandmarker, FilesetResolver } = await import(/* @vite-ignore */ MP_URL);
const fileset = await FilesetResolver.forVisionTasks(MP_WASM);
landmarker = await FaceLandmarker.createFromOptions(fileset, {
baseOptions: { modelAssetPath: FACE_TASK, delegate: 'GPU' },
runningMode: 'VIDEO', numFaces: 1, outputFaceBlendshapes: false,
});
const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' } });
video = document.createElement('video');
video.srcObject = stream; video.playsInline = true; await video.play();
usingCamera = true;
} catch (err) {
setStatus('camera unavailable — staying on synthetic (' + err.name + ')');
usingCamera = false; // graceful fallback; demo keeps running
}
}
Common pitfalls
- Your blink threshold is wrong for the next person. Absolute EAR varies with eye shape, glasses, and camera angle — one person's open-eye EAR is another's half-shut. Don't hard-code a magic number: either expose it (the slider here) or calibrate at startup — sample EAR for a second of open eyes, set the threshold to, say, 65% of that. Relative beats absolute every time.
- One blink counts as ten. Without a refractory window, every frame EAR sits below threshold fires another blink, so a single slow closure spams the action. Count only the open→closed transition and then ignore EAR for ~200–300 ms. A little hysteresis on the re-arm (require EAR back above threshold + a margin) stops flicker right at the line.
- Gaze is dead or jittery without the iris model. The iris landmarks
(
468/473) only exist on the 478-point model — MediaPipe's Face Landmarker includes them, but a bare 468-point mesh does not. Without iris points you can only approximate gaze from eye-corner geometry (much coarser). If gaze never moves, you're probably reading an index that isn't there. - It works up close and breaks across the room. You compared a raw pixel distance to a threshold. Always normalize: EAR by eye width, mouth by face size. Ratios are distance-invariant; raw distances are not.
- "Look left" goes right. The selfie mirror again. We flip X in
toPixelfor drawing and flip the gaze vector's X, so your left maps to screen-left. Mirror one and not the other and the reticle fights you. - Lost tracking nukes the detectors. When the face leaves the frame the
array is empty; reading
lm[159]throws. Guard fornulland just skip the frame — don't let a missing face crash the loop or reset your blink counter.
Exercises
- Wink detector. Instead of averaging both eyes' EAR, compare them. If the left EAR is below threshold while the right stays well above (or vice versa), that's a wink — a per-eye trigger. Map a left wink and a right wink to two different actions. Watch the asymmetry threshold; eyes don't blink perfectly together.
- Dwell-to-click with gaze. Instead of blinking, hover the gaze reticle over a target and hold it there. Accumulate dwell time while the reticle stays inside the target (reset if it leaves); when dwell passes ~700 ms, fire a "click." Draw a little radial progress ring so the user sees the dwell filling. This is how eye-tracking accessibility tools work.
- Eyebrow-raise trigger. Add a third gesture: measure the distance from the eye (e.g. the upper-lid landmark) up to the eyebrow, normalize by face size, and fire when it jumps above its resting value. Use the same threshold-plus-refractory pattern as the blink. Now you have brows, eyes, and mouth — three independent face buttons.
What's next
Episode 14 — Become a Cloud of Light: the Body Particle Silhouette. We leave the face and go full-body again, but instead of drawing a skeleton we fill your silhouette with thousands of drifting particles that move when you move — the body as a living, glowing point cloud. (And yes, it leans on the same splat instincts from Gaussian Splatting From Zero.)