apopt.comCBE 493R Data-Driven Athletics

Course / Tutorials / Week 8 / CS-10

Case study CS-10 · Week 8 · about 60 min · Foundation

Pose estimation, frame by frame

Run a pose model on every frame of a running clip, turn it into a table of 17 keypoints, check it three ways without a ground truth, and decide what the clip can and cannot measure.

  1. 1Gather (used)
  2. 2Statistics (used)
  3. 3Visualize (used)
  4. 4Cleanse (used)
  5. 5Features
  6. 6Balance
  7. 7Scale
  8. 8Split
  9. 9Deploy (used)
  1. Ask (this week)
  2. Collect (this week)
  3. Check (this week)
  4. Interpret
  5. Coach (this week)
  6. Reassess

5 of 7 cells run in this page. The rest need a model that does not run in the browser: run them in the notebook on your computer or in Colab (File → Upload notebook); their output from the course build is shown, and the files they write are published so the later cells still run here. Helpful first: Q-22 Detect a person in one image, Q-23 Read a video frame by frame and save every tenth frame, Q-24 Seventeen keypoints for one frame, as a table.

The decision

A runner sends a short phone clip and asks for a knee angle and a cadence. Before measuring anything, decide whether the clip can support those numbers at all. The way to find out is to run a pose model on every frame and look hard at what it returns.

Predict first

A pose model finds a person in a clear, well-lit running clip. In what share of the keypoints do you expect it to be confident (0.5 or more): about half, about three quarters, or nearly all?

The raw data

Data dictionary
FieldMeaningUnitRangeMissing
frameframe number from 0count0–21row absent if no person
<joint>_x, <joint>_ykeypoint position, 17 joints (nose … r_ankle)pixels from the top-left corner; y grows downward0–1920, 0–10800 when the model has no estimate
<joint>_cthe model's confidence in that keypoint0 to 10–1none

What can be wrong with it: the header gives the stored frame rate, which may not be the rate the camera filmed at; the clip is short; and the runner is not square to the camera. None of that is visible until the frames are turned into numbers. The pose model files (yolo26n-pose.pt, yolo26s-pose.pt) download themselves the first time the notebook runs.

Step by step

Step 1 · Gather: what is in the file?

A video is a stack of pictures and a clock. Before any model runs, read the clock: how many frames, how many per second, how big. The clip is the short running clip from the Data-Driven Engineering course. Steps 1 and 2 run in a notebook on your computer or in Colab, because the pose model does not run inside a web page here; from Step 3 on, everything runs in this page from the table that Step 2 writes.

Step 1 · Read the clip's header

Runs in the notebook (needs a model that does not run in the browser). Output from the course build:

import cv2

cap = cv2.VideoCapture("runner.mp4")
fps = cap.get(cv2.CAP_PROP_FPS)
n = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
w, h = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print(f"{n} frames at {fps:.0f} fps = {n / fps:.2f} s, {w} x {h} pixels")
cap.release()
22 frames at 30 fps = 0.73 s, 1920 x 1080 pixels

Twenty-two frames: a short clip, which makes it a good first one. Everything a pose model does to it fits in a table of 22 rows. (The header gives the stored frame rate. Chapter 8 shows clips filmed at 120 frames per second and stored at 30; check your own clips the same way.)

Step 2 · Run a pose model on every frame

The loop below is the whole of frame-by-frame pose estimation. For each frame: run the model, keep the most confident person, and write one row: the frame number, the x and y of 17 keypoints in pixels, and the model's confidence in each, from 0 to 1. It also writes an annotated copy of the video for you to watch (local/runner_pose.mp4, on your computer only). Two model sizes are run, the smallest (n) and the next (s), so Step 6 can compare them.

Step 2 · Frame by frame: model, keypoints, table

Runs in the notebook (needs a model that does not run in the browser). Output from the course build:

import os
import time
import pandas as pd
from ultralytics import YOLO

NAMES = ["nose", "l_eye", "r_eye", "l_ear", "r_ear", "l_shoulder", "r_shoulder", "l_elbow", "r_elbow",
         "l_wrist", "r_wrist", "l_hip", "r_hip", "l_knee", "r_knee", "l_ankle", "r_ankle"]
os.makedirs("clean", exist_ok=True)
os.makedirs("local", exist_ok=True)
for size in ["n", "s"]:
    model = YOLO(f"yolo26{size}-pose.pt")
    cap = cv2.VideoCapture("runner.mp4")
    out = cv2.VideoWriter(f"local/runner_pose_{size}.mp4", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
    rows, ms, i = [], [], 0
    while True:
        ok, frame = cap.read()
        if not ok:
            break
        t0 = time.perf_counter()
        r = model(frame, verbose=False, device="cpu")[0]
        ms.append(1000 * (time.perf_counter() - t0))
        out.write(r.plot())                               # the frame with the skeleton drawn on it
        if r.keypoints is not None and len(r.boxes):
            best = int(r.boxes.conf.argmax())             # the most confident person
            xy, conf = r.keypoints.xy[best].tolist(), r.keypoints.conf[best].tolist()
            rows.append([i] + [v for p in xy for v in p] + conf)
        i += 1
    cap.release(); out.release()
    cols = ["frame"] + [f"{k}_{a}" for k in NAMES for a in "xy"] + [f"{k}_c" for k in NAMES]
    pd.DataFrame(rows, columns=cols).round(2).to_csv(f"clean/keypoints_{size}.csv", index=False)
    print(f"yolo26{size}-pose: person found in {len(rows)} of {i} frames, "
          f"median {sorted(ms)[len(ms) // 2]:.0f} ms per frame on this computer's CPU")
yolo26n-pose: person found in 22 of 22 frames, median 117 ms per frame on this computer's CPU
yolo26s-pose: person found in 22 of 22 frames, median 310 ms per frame on this computer's CPU

Watch local/runner_pose_n.mp4 on your computer: the skeleton is drawn on every frame. The timings are for the computer that built this page; yours will differ, but the ratio between the two sizes will be similar. From here on, everything runs in this page, from the two tables.

Step 3 · One frame, seventeen keypoints

Open the table and turn the first row into a short table of its own: one line per keypoint.

PythonStep 3 · Read one frame as 17 keypoints

Type a prediction to enable Run.

Show the expected result without running
(22, 52) (rows = frames with a person; columns = frame + 17 × (x, y) + 17 confidences)
frame 0:
                  x       y  confidence
nose         828.51  175.35        0.92
l_eye        837.70  152.25        0.97
r_eye        833.37  156.69        0.09
l_ear        881.94  154.93        0.99
r_ear        889.72  163.31        0.01
l_shoulder   922.55  231.54        0.99
r_shoulder   917.78  245.07        0.98
l_elbow     1025.95  309.58        0.98
r_elbow      860.23  310.68        0.74
l_wrist      990.73  444.91        0.99
r_wrist      818.97  321.27        0.89
l_hip        911.26  500.50        1.00
r_hip        957.41  523.75        1.00
l_knee       695.67  586.93        1.00
r_knee      1026.03  725.43        1.00
l_ankle      666.18  815.18        1.00
r_ankle     1237.05  769.90        0.98

Pixel y grows downward: the nose has the smallest y, the ankles the largest. Code that forgets this draws people upside down and reports upward speeds as negative.

Step 4 · Statistics: how sure is the model, joint by joint?

PythonStep 4 · Confidence by keypoint over all frames

Show the expected result without running
            mean   min
r_eye       0.06  0.03
r_ear       0.20  0.01
nose        0.53  0.13
l_eye       0.59  0.04
r_wrist     0.76  0.07
r_elbow     0.83  0.36
l_wrist     0.87  0.29
l_ear       0.93  0.53
l_elbow     0.96  0.80
r_ankle     0.98  0.95
l_ankle     0.98  0.96
r_knee      0.99  0.97
l_knee      0.99  0.97
r_shoulder  0.99  0.98
l_shoulder  1.00  0.98
l_hip       1.00  1.00
r_hip       1.00  1.00
keypoints below 0.5 confidence: 69 of 374

Step 5 · Visualize: the skeleton, without the pixels

Draw the keypoints themselves, joined into a stick figure, for four frames, and plot the two ankles' height over the clip. A plot made from the table is the model's view of the runner: whatever it shows is what any later number will be built on. Faint points are the ones the model was unsure of.

PythonStep 5 · Stick figures and ankle traces

Show the expected result without runningLeft: four stick figures of the runner at frames 0, 7, 14 and 21, drawn from the keypoints. Right: left and right ankle height in pixels across the 22 frames.

Two things stand out before any number is computed. The stick figure shrinks from frame 0 to frame 21: the runner is moving away from the camera, so a pixel does not stand for the same distance in every frame (Chapter 8, "Scale"). And the ankle traces have single-frame spikes, the right ankle at frame 4 and the left at frame 10, where the trace jumps and comes straight back. At those frames both ankle labels landed on the same foot.

Step through the clip one frame at a time in the viewer below. It draws the same table, with the frame number and each joint's confidence.

Loading the keypoint table…

Step 6 · Cleanse: gate, despike, and check one model against another

Three checks, none of which needs a ground truth. First, points the model was unsure of are set to missing (a confidence gate). Second, a point more than a quarter of a leg length away from the median of itself and its two neighbors is a spike: it jumped away for one frame and came back. It is set to missing too. Third, the two model sizes give two estimates of every point; where they disagree by many pixels, at least one is wrong.

PythonStep 6 · Confidence gate and model agreement

Type a prediction to enable Run.

Show the expected result without running
set to missing by the 0.5 gate: 69 points
leg length (hip-knee-ankle) in the image: 250 px; spikes over 63 px set to missing:
[('l_ankle', 10), ('r_ankle', 4)]
median disagreement between models n and s, pixels:
r_ankle    19.4
r_wrist    15.0
r_knee     13.8
l_ankle    12.0
l_knee     11.7
l_wrist    10.8

Step 9 · Deploy: is this clip good enough, and for what?

A measurement is good enough when its error is small next to the change you care about. Two quick tests decide what this clip can support.

PythonStep 9 · What can this clip measure?

Show the expected result without running
one frame = 33 ms; a 200 ms contact = 6 frames; one frame of error = 17% of it
contacts found: left 1, right 2 in 0.73 s
enough for cadence? no: a cadence needs several strides

The verdict has three parts. The hips, knees and ankles are found with high confidence in every frame, so a joint angle at one chosen instant is usable, as long as the frame is not one of the spikes. The clip is too short for cadence or for an average over strides, and at 30 frames per second a contact time carries a 17% one-frame error. And because the runner moves away from the camera, no single pixel-to-meter scale holds for the whole clip. That is the action: film 10 seconds or more, at 60 or 120 frames per second, from the side and square to the path, before measuring anything that repeats.

How good is the number?

There is no ground truth here, so the checks are internal: the model's own confidence, the smoothness of each trace from frame to frame, and agreement between two model sizes. The two sizes differ by a median of 12 to 19 pixels at the ankles and knees, about 5 to 8% of the 250-pixel leg. That is the floor of the error in any position measured from this clip, before the scale problem (the runner moves away from the camera) is even considered. Chapter 8 calls these the first two of four levels of error.

Action card

Action card
Finding
This clip supports a joint angle at one chosen instant, not a cadence or a contact time.
Evidence
22 frames (0.73 s) hold only three foot contacts; one frame is 17% of a 200 ms contact; the runner shrinks across the clip, so no single scale holds.
How sure
High for the verdict; the hips, knees and ankles are found with confidence 0.95 or more in every frame.
Action
Refilm 10 s or more at 60 or 120 frames per second, from the side and square to the path, with the phone still.
Test again
Run the same checks on the new clip before measuring anything.

Track it

Nothing to add to the athlete record yet: this study checks the clip, not the athlete. Note the filming protocol you settle on (protocol_version), because every later video measurement in the record depends on it.

Open your athlete record

With your own data

Replace runner.mp4 with your own clip and run the notebook from the top. Keep any video that shows a face in the local/ folder: share only the keypoint table, which shows no one.

Check the AI

Asked for "the runner's cadence from this clip", an assistant wrote:

> The left ankle reaches its lowest point at frames 3 and 10, so one stride takes > 7 frames = 0.23 s, which gives a cadence of 60/0.23 × 2 = 516 steps per minute.

What is wrong with it?

Frame 10 is one of the spikes where the left-ankle label jumped to the right foot, so the "stride" is half a stride at best; and 22 frames cannot give a reliable cadence anyway. A cadence of 516 steps per minute is also far outside anything a human runs (sprinters reach about 300): a range check would have caught it.

Check yourself

  1. Why does pixel y grow downward in a keypoint table?

  2. The face keypoints have low confidence in this clip. Should the whole clip be rejected?

  3. How long is one frame at 60 frames per second, and what share of a 200 ms contact is it?

    % of the contact

  4. The two model sizes disagree by 19 pixels at the right ankle. What does that tell you?

0 of 4 answered · 0 right the first time

Challenge: Your own clip, two ways

Film yourself or a partner running past the camera twice: once as this clip was filmed (short, at an angle) and once to the Chapter 8 protocol (side view, square to the path, phone still, 10 s or more, the highest frame rate the phone offers). Run this tutorial's notebook on both.

  1. Read the header of each clip and say whether the stored frame rate matches the filmed rate (Chapter 8, two clocks).
  2. Build both keypoint tables with two model sizes and report the confident share, the spikes, and the median disagreement at the knees and ankles.
  3. Count foot contacts in each and compute a cadence where the clip allows it.
  4. Write the verdict for each clip in the three-part form of Step 9.

Hand in

How it is judged

Hints

    The solution unlocks after you make an attempt. Comparing your own attempt with it is where the learning happens.

    The same method in another field

    The same steps turn any video into a table: tracking a part on a conveyor, a gauge needle in a plant, a crack opening in a materials test. The Data-Driven Engineering pages on object detection and video data start from the same frame loop.

    Acknowledgements

    The running clip is from the Data-Driven Engineering course, which compares four YOLO versions on it. Pose estimation uses Ultralytics YOLO (AGPL-3.0); the course code is MIT.

    References

    Built 2026-11-30 with Python packages numpy 2.5.5, pandas 3.1.1, matplotlib 3.11.2, ultralytics 8.4.219, cv2 5.1.0. In the browser the same code runs on Pyodide, so the last digit can differ.