# CS-10: Pose estimation, frame by frame

Data-Driven Athletics tutorial · Week 8 · Chapter 8 · about 60 min · workflow steps: Gather, Statistics, Visualize, Cleanse, Deploy

Web page: https://apopt.com/course/tutorials/cs10-pose-frame-by-frame/ · Data: https://apopt.com/data/tutorials/cs10-pose-frame-by-frame/

## 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

- `runner.mp4`: a 22-frame running clip, 1920 × 1080 pixels at 30 frames per second From the Data-Driven Engineering course page [YOLO model comparison](https://apmonitor.com/dde/index.php/Main/PoseEstimation); downloaded from there, not copied here.

| Field | Meaning | Unit | Range | Missing |
|---|---|---|---|---|
| frame | frame number from 0 | count | 0–21 | row absent if no person |
| <joint>_x, <joint>_y | keypoint position, 17 joints (nose … r_ankle) | pixels from the top-left corner; y grows downward | 0–1920, 0–1080 | 0 when the model has no estimate |
| <joint>_c | the model's confidence in that keypoint | 0 to 1 | 0–1 | none |

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 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.

*Predict first:* The clip lasts under a second at 30 frames per second. How many frames will it have?

```python
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()
```

Output:

```
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.

*Predict first:* Which model will be faster per frame, n or s, and by roughly how much?

```python
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")
```

Output:

```
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.

*Predict first:* Which keypoints do you expect the model to be least sure about in a side view?

```python
import pandas as pd

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"]
kp = pd.read_csv("clean/keypoints_n.csv")
print(kp.shape, "(rows = frames with a person; columns = frame + 17 × (x, y) + 17 confidences)")
row = kp.iloc[0]
one = pd.DataFrame({"x": [row[f"{k}_x"] for k in NAMES], "y": [row[f"{k}_y"] for k in NAMES],
                    "confidence": [row[f"{k}_c"] for k in NAMES]}, index=NAMES)
print(f"frame {int(row['frame'])}:")
print(one.round(2).to_string())
```

Output:

```
(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?

```python
conf = kp[[f"{k}_c" for k in NAMES]]
conf.columns = NAMES
summary = conf.describe().T[["mean", "min"]].sort_values("mean")
print(summary.round(2).to_string())
print(f"keypoints below 0.5 confidence: {(conf < 0.5).to_numpy().sum()} of {conf.size}")
```

Output:

```
            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.

```python
import matplotlib.pyplot as plt

BONES = [("l_shoulder", "r_shoulder"), ("l_shoulder", "l_elbow"), ("l_elbow", "l_wrist"),
         ("r_shoulder", "r_elbow"), ("r_elbow", "r_wrist"), ("l_shoulder", "l_hip"), ("r_shoulder", "r_hip"),
         ("l_hip", "r_hip"), ("l_hip", "l_knee"), ("l_knee", "l_ankle"), ("r_hip", "r_knee"), ("r_knee", "r_ankle")]

def stick(ax, r, dx=0, color="C0"):
    for a, b in BONES:
        ax.plot([r[f"{a}_x"] + dx, r[f"{b}_x"] + dx], [r[f"{a}_y"], r[f"{b}_y"]], color=color, lw=2,
                alpha=0.3 if min(r[f"{a}_c"], r[f"{b}_c"]) < 0.5 else 1)
    ax.plot(r["nose_x"] + dx, r["nose_y"], "o", color=color)

fig, ax = plt.subplots(1, 2, figsize=(10, 3.8), gridspec_kw={"width_ratios": [1.4, 1]})
for j, f in enumerate([0, 7, 14, 21]):
    r = kp[kp["frame"] == f]
    if len(r):
        stick(ax[0], r.iloc[0], dx=-r.iloc[0]["l_hip_x"] + 450 * j, color=f"C{j}")
        ax[0].text(450 * j, kp["l_ankle_y"].max() + 60, f"frame {f}", ha="center")
ax[0].invert_yaxis(); ax[0].set_aspect("equal"); ax[0].axis("off")
ax[1].plot(kp["frame"], kp["l_ankle_y"], "o-", label="left ankle")
ax[1].plot(kp["frame"], kp["r_ankle_y"], "s--", label="right ankle")
ax[1].invert_yaxis(); ax[1].set(xlabel="frame", ylabel="ankle y (pixels, up is up)"); ax[1].legend()
plt.tight_layout()
```

![Left: 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.](https://apopt.com/course/tutorials/cs10-pose-frame-by-frame/c09-1.png)

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.

### 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.

*Predict first:* Which joint will the two models disagree on most, in pixels?

```python
import numpy as np

GATE = 0.5
gated = kp.copy()
for k in NAMES:
    low = gated[f"{k}_c"] < GATE
    gated.loc[low, [f"{k}_x", f"{k}_y"]] = np.nan
print(f"set to missing by the {GATE} gate: {int(gated[[f'{k}_x' for k in NAMES]].isna().sum().sum())} points")

leg = np.hypot(kp["l_hip_x"] - kp["l_knee_x"], kp["l_hip_y"] - kp["l_knee_y"]).median() + \
      np.hypot(kp["l_knee_x"] - kp["l_ankle_x"], kp["l_knee_y"] - kp["l_ankle_y"]).median()
spikes = []
for k in NAMES:
    for a in "xy":
        v = gated[f"{k}_{a}"]
        mid = v.rolling(3, center=True, min_periods=2).median()   # this frame and its two neighbors
        jump = (v - mid).abs() > leg / 4
        spikes += [(k, int(f)) for f in gated.loc[jump, "frame"]]
        gated.loc[jump, [f"{k}_x", f"{k}_y"]] = np.nan
gated.to_csv("clean/keypoints_n_clean.csv", index=False)
print(f"leg length (hip-knee-ankle) in the image: {leg:.0f} px; spikes over {leg / 4:.0f} px set to missing:")
print(sorted(set(spikes)))

ks = pd.read_csv("clean/keypoints_s.csv")
both = kp.merge(ks, on="frame", suffixes=("_n", "_s"))
dist = pd.Series({k: np.hypot(both[f"{k}_x_n"] - both[f"{k}_x_s"], both[f"{k}_y_n"] - both[f"{k}_y_s"]).median()
                  for k in NAMES}).sort_values(ascending=False)
print("median disagreement between models n and s, pixels:")
print(dist.head(6).round(1).to_string())
```

Output:

```
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.

* **Timing.** At 30 frames per second each frame is 33 ms. A running contact lasts about
  200 ms, so it spans about 6 frames, and one frame of error is about 17% of it.
* **Counting.** Cadence needs several steps. Count the ground contacts in the clip from the
  cleaned ankle traces: a contact is where an ankle is near its lowest point (largest y).

```python
frame_ms = 1000 / 30
print(f"one frame = {frame_ms:.0f} ms; a 200 ms contact = {200 / frame_ms:.0f} frames; "
      f"one frame of error = {frame_ms / 200:.0%} of it")
contacts = {}
for side in ["l", "r"]:
    y = gated[f"{side}_ankle_y"].interpolate(limit=2)
    low = y > y.max() - 0.15 * (y.max() - y.min())              # within 15% of the lowest point
    contacts[side] = int((low & ~low.shift(fill_value=False)).sum())
print(f"contacts found: left {contacts['l']}, right {contacts['r']} in {len(kp) / 30:.2f} s")
print("enough for cadence?", "no: a cadence needs several strides" if sum(contacts.values()) < 6 else "yes")
```

Output:

```
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.

## 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.

## 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.

## 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](https://apmonitor.com/dde/index.php/Main/ObjectDetection) and
[video data](https://apmonitor.com/dde/index.php/Main/VideoData) 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.

## 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.
- **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.
- **Retest:** Run the same checks on the new clip before measuring anything.

## 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.

Deliverables:

- the two notebooks with their outputs
- a table comparing the two clips on the checks
- two action cards, one per clip

## References

- Data-Driven Engineering: [YOLO model comparison (pose estimation)](https://apmonitor.com/dde/index.php/Main/PoseEstimation).
- Ultralytics YOLO documentation: [pose estimation](https://docs.ultralytics.com/tasks/pose/).
- Chapter 8 of *Data-Driven Athletics*: A Video Is a Table; From Pixels to Keypoints; Cleaning Keypoints; Four Levels of Error.

---
Text CC BY 4.0, code MIT. IRSRI Sports Research Institute.
