# CS-11: From keypoints to a knee angle over a stride

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

Web page: https://apopt.com/course/tutorials/cs11-knee-angle/ · Data: https://apopt.com/data/tutorials/cs11-knee-angle/

## The decision

A runner wants to know how tightly the knee folds in swing, because a coach has said "fold it
more". Before anyone coaches it, decide whether a knee-angle curve from this clip is a
measurement or a picture: which parts of the curve are known to a few degrees, and which
are not.

## Predict first

A pose model is confident (0.95 or more) about every hip, knee and ankle. If you average a few cycles of the knee angle, how wide do you expect the error band to be: about ±2°, about ±5°, or ±10° or more?

## The raw data

- `raw/form3_30fps_yolo26x-pose.csv`: keypoints of every frame of a hand-drawn runner seen from the side, YOLO26x (117 rows, 52 columns) Chapter 8's example table, also published with the book's data (`book/ch08-pose`). The clip is an animated drawing, not a person.
- `raw/form3_30fps_yolo26n-pose.csv`: the same clip with the nano model, YOLO26n (117 rows) Same source.
- `raw/form3_30fps_yolo26s-pose.csv`: the same clip with the small model, YOLO26s (115 rows; two frames without a person) Same source.

| Field | Meaning | Unit | Range | Missing |
|---|---|---|---|---|
| frame | frame number from 0 at 30 frames per second | count | 0–116 | 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 | none in this file |
| <joint>_c | the model's confidence in that keypoint | 0 to 1 | 0–1 | none |

What is wrong with it: the model's left and right legs swap back and forth (12 jumps of more
than 40° in one frame in the x model's left knee alone); 37 of the 117 rows repeat the drawing
before, because the animation was drawn on twos; and the animation plays far slower than a
real run, so its clock cannot be used for times. None of this shows in the confidence column.

### Step 2 · Statistics: three model sizes, one clip

The input is a keypoint table, not a video: one row per frame, 17 keypoints with x, y and a
confidence. Chapter 8's running example is a hand-drawn runner, animated and seen from the
side (`form3_30fps.mp4`, 117 frames at 30 frames per second), and the book publishes its
keypoints from five YOLO26 pose model sizes. Three are used here: n (nano, the smallest),
s (small) and x (extra large). A knee angle needs three points on each leg, so profile those
first: how many frames, how sure the model is of each hip, knee and ankle, and one more check
that every video deserves, whether consecutive frames are really different pictures.

*Predict first:* Which model size will have the fewest leg points below 0.3 confidence?

```python
import numpy as np
import pandas as pd

LEG = [f"{s}_{j}" for s in "lr" for j in ("hip", "knee", "ankle")]
tables = {m: pd.read_csv(f"raw/form3_30fps_yolo26{m}-pose.csv") for m in "nsx"}
for m, kp in tables.items():
    conf = kp[[f"{k}_c" for k in LEG]]
    xy = kp[[c for c in kp.columns if c.endswith(("_x", "_y"))]].to_numpy()
    held = (np.abs(np.diff(xy, axis=0)).max(axis=1) < 3).sum()   # no point moved 3 px
    print(f"{m}: {len(kp)} of 117 frames, leg points below 0.3: {(conf < 0.3).to_numpy().sum()}, "
          f"median leg confidence {np.median(conf):.2f}, frames repeating the one before: {held}")
```

Output:

```
n: 117 of 117 frames, leg points below 0.3: 2, median leg confidence 0.98, frames repeating the one before: 37
s: 115 of 117 frames, leg points below 0.3: 6, median leg confidence 0.98, frames repeating the one before: 31
x: 117 of 117 frames, leg points below 0.3: 0, median leg confidence 0.99, frames repeating the one before: 37
```

All three sizes are confident about the legs; x is the only one with no leg point below 0.3
and no missing frame. The last column is the surprise: more than a quarter of the rows repeat
the frame before. The animation was drawn "on twos", each drawing held for two frames, so the
clip holds about 15 new pictures a second, not 30. That does not break a knee angle, but it
halves the real time resolution, and a frame count read from this clip overstates it.

### Step 3 · Visualize: the raw knee angles

The knee angle is the included angle at the knee between the thigh (knee to hip) and the shank
(knee to ankle), from the dot product of the two vectors (Section 3.2). 180° is a straight leg.
Plot it for both legs as the model labelled them, before any cleaning.

```python
import matplotlib.pyplot as plt

def knee_angle(kp, side):
    hip, kn, an = (kp[[f"{side}_{j}_x", f"{side}_{j}_y"]].to_numpy() for j in ("hip", "knee", "ankle"))
    u, v = hip - kn, an - kn                                      # thigh and shank from the knee
    cos = (u * v).sum(1) / np.linalg.norm(u, axis=1) / np.linalg.norm(v, axis=1)
    return np.degrees(np.arccos(np.clip(cos, -1, 1)))

kx = tables["x"]
left, right = knee_angle(kx, "l"), knee_angle(kx, "r")
jumps = (np.abs(np.diff(left)) > 40).sum()
print(f"left knee: {left.min():.0f} to {left.max():.0f} deg; frame-to-frame jumps over 40 deg: {jumps}")

fig, ax = plt.subplots(figsize=(8, 3.2))
ax.plot(kx["frame"], left, "o-", ms=3, lw=1, label="labelled left")
ax.plot(kx["frame"], right, "s--", ms=3, lw=1, label="labelled right")
ax.set(xlabel="frame (30 per second)", ylabel="knee angle (deg, 180 = straight)")
ax.legend(loc="lower center", bbox_to_anchor=(0.5, 1.0), ncol=2, frameon=False)
plt.tight_layout()
```

Output:

```
left knee: 44 to 172 deg; frame-to-frame jumps over 40 deg: 12
```

![Knee angle of the left and right leg against frame number for the x model. The two traces jump back and forth between two smooth curves, crossing many times.](https://apopt.com/course/tutorials/cs11-knee-angle/c03-1.png)

Each trace jumps between two smooth curves. Those are not knee movements: a knee cannot change
by 40° or more in one frame, 33 ms, and back again. They are **left–right swaps**: the model's
"left knee" sits on one leg in some frames and on the other leg in others. In a sketch the
two legs are drawn alike, so the model has almost nothing to tell them apart (Chapter 8,
"Cleaning Keypoints").

### Step 4 · Cleanse: gate, go side-blind, smooth

Three rules, written before looking for the answer:

1. **Gate.** A knee angle needs all three of its points at 0.3 confidence or more, the
   threshold most of the apps use. Below that, the angle is missing, never zero.
2. **Side-blind.** Since the labels cannot be trusted, stop asking which leg is which. At
   every frame take the **more bent** of the two knees. In running, that is the swinging leg
   for most of each step, and its tightest bend is the *peak swing flexion*, a standard measure
   (it is a column, `lkneeswing`, in the CS-13 treadmill data).
3. **Smooth over 0.1 s.** A centered average over 3 frames, the canvas app's rule at 30 frames
   per second (0.1 × 30 = 3), taken only where at least two of the three frames have a value.

```python
import os

def gated_knee(kp, side, gate=0.3):
    ok = kp[[f"{side}_{j}_c" for j in ("hip", "knee", "ankle")]].min(axis=1) >= gate
    return np.where(ok, knee_angle(kp, side), np.nan)

def swing_knee(kp):
    full = kp.set_index("frame").reindex(range(117)).reset_index()   # missing frames stay missing
    bent = np.fmin(gated_knee(full, "l"), gated_knee(full, "r"))      # the more bent knee
    smooth = pd.Series(bent).rolling(3, center=True, min_periods=2).mean()
    return pd.DataFrame({"frame": full["frame"], "t_s": full["frame"] / 30,
                         "bent_knee_deg": bent.round(1), "smoothed_deg": smooth.round(1)})

os.makedirs("clean", exist_ok=True)
series = {m: swing_knee(kp) for m, kp in tables.items()}
for m, s in series.items():
    s.to_csv(f"clean/swing_knee_{m}.csv", index=False)
    print(f"{m}: {s['bent_knee_deg'].isna().sum()} frames without an angle; "
          f"largest frame-to-frame change {s['smoothed_deg'].diff().abs().max():.0f} deg after smoothing")
```

Output:

```
n: 0 frames without an angle; largest frame-to-frame change 32 deg after smoothing
s: 2 frames without an angle; largest frame-to-frame change 34 deg after smoothing
x: 0 frames without an angle; largest frame-to-frame change 35 deg after smoothing
```

### Step 5 · Features: find the strides, then average them

Period first, events second (Chapter 9). The autocorrelation of the smoothed series finds the
lag at which the pattern repeats, searched between 0.4 and 1.5 s. Each tightest bend is then
taken as one event, no closer than 0.6 of a period to the last, and a window of one period is
cut around each event, so every cycle is lined up on its peak swing flexion.

*Predict first:* The included angle at peak swing flexion in sprinting is small (a tightly folded leg). Will the cycles agree within 5°, 10° or 20°?

```python
from scipy.signal import find_peaks

def cycles(s):
    y = s["smoothed_deg"].to_numpy()
    z = np.nan_to_num(y - np.nanmean(y))
    ac = np.correlate(z, z, "full")[len(z) - 1:] / (z @ z)
    lag = 12 + int(np.argmax(ac[12:46]))                         # 0.4 to 1.5 s at 30 fps
    ev, _ = find_peaks(-np.nan_to_num(y, nan=180), distance=int(0.6 * lag))
    half = lag // 2
    ev = [int(e) for e in ev if half <= e < len(y) - half]        # whole windows only
    return lag, ev, np.array([y[e - half:e + half + 1] for e in ev])

found = {m: cycles(s) for m, s in series.items()}
for m, (lag, ev, cyc) in found.items():
    peak = cyc[:, len(cyc[0]) // 2]
    print(f"{m}: period {lag} frames = {lag / 30:.2f} s; {len(ev)} cycles at frames {ev}; "
          f"peak flexion {', '.join(f'{p:.0f}' for p in peak)} deg")
```

Output:

```
n: period 34 frames = 1.13 s; 3 cycles at frames [23, 57, 95]; peak flexion 51, 49, 60 deg
s: period 14 frames = 0.47 s; 7 cycles at frames [14, 30, 46, 58, 74, 83, 96]; peak flexion 94, 89, 56, 74, 100, 142, 74 deg
x: period 34 frames = 1.13 s; 3 cycles at frames [25, 47, 81]; peak flexion 51, 55, 63 deg
```

Two of the three sizes agree on the period, 34 frames (1.13 s), and both find three whole
cycles, though not at the same frames after the first. The s model does not agree at all: its
series is so broken by swaps that the autocorrelation finds a repeat less than half as long,
and peak flexions from 56° to 142°. That is a reason to look at a series before trusting its
period, and the reason the rest of this study uses x, with n as the check.

Two more checks on the period. First, a side-blind series cannot tell one leg's fold from the
other's, so the pattern it repeats is a **step** (one foot to the other), and a stride for one
leg needs labels you trust; here, a cycle is the repeat of the side-blind pattern. Second,
compare it with a real runner: Chapter 9's treadmill runner takes a whole stride, two steps, in
0.70 s. A cycle of 1.13 s means the animation plays far slower than any real run. Times read
from this clip mean nothing; angles do not depend on the clock, so they can still be read.

Now the curve the coach asked for: the cycles laid over each other, their mean, and a band of
one standard deviation either side.

```python
lag, ev, cyc = found["x"]
pct = np.linspace(-50, 50, cyc.shape[1])                       # % of the cycle from the event
mean, sd = np.nanmean(cyc, axis=0), np.nanstd(cyc, axis=0, ddof=1)
curve = pd.DataFrame({"pct_cycle": pct.round(1), "mean_deg": mean.round(1), "sd_deg": sd.round(1)})
curve.to_csv("clean/knee_curve_x.csv", index=False)
print(f"x: {len(ev)} cycles; peak flexion {mean[len(mean) // 2]:.0f} ± {sd[len(sd) // 2]:.0f} deg; "
      f"median band half-width {np.median(sd):.0f} deg")
nmean = np.nanmean(found["n"][2], axis=0)
print(f"n: peak flexion {nmean[len(nmean) // 2]:.0f} deg; mean |x - n| over the cycle "
      f"{np.nanmean(np.abs(mean - nmean)):.0f} deg")

fig, ax = plt.subplots(figsize=(6.4, 3.6))
for c in cyc:
    ax.plot(pct, c, color="gray", lw=0.8)
ax.fill_between(pct, mean - sd, mean + sd, color="C0", alpha=0.25, label="x: mean ± 1 SD")
ax.plot(pct, mean, color="C0", lw=2.5, label=f"x: mean of {len(ev)} cycles")
ax.plot(pct, nmean, "k--", lw=1.5, label="n: mean")
ax.set(xlabel="% of cycle from peak swing flexion", ylabel="knee angle (deg, 180 = straight)")
ax.legend(loc="lower right", fontsize=8)
plt.tight_layout()
```

Output:

```
x: 3 cycles; peak flexion 56 ± 6 deg; median band half-width 14 deg
n: peak flexion 53 deg; mean |x - n| over the cycle 17 deg
```

![Knee angle of the more bent knee over one cycle, centered on peak swing flexion, for the x model: each cycle as a thin line, their mean as a thick line, and a shaded band of plus and minus one standard deviation; the n model's mean as a dashed line.](https://apopt.com/course/tutorials/cs11-knee-angle/c09-1.png)

The curve has the shape you would expect around a fold: the knee closes to its tightest bend
and opens again. Read the band as carefully as the line. At the event itself the three cycles
agree well, 56 ± 6° (51, 55 and 63°), and the nano model's mean, 53°, is inside that. Away
from the event they do not: the median half-width of the band is 14°, and the two models'
means differ by 17° on average over the cycle. The band mixes three things this clip cannot
separate: real differences between drawn cycles, keypoint placement error, and the side-blind
rule switching from one leg to the other. So the one number this clip supports is the angle
at peak swing flexion; the rest of the curve is a picture, not a measurement. In flexion terms
(180° minus the included angle) that is a fold of about 124°.

One more limit applies to every angle in this study. It is an angle **in the image plane**,
measured on a flat picture. It equals the joint angle only when the leg moves in a plane
square to the camera (Section 3.9), and a keypoint is where an annotator would click, not the
joint's center (Section 8.3). For a hand-drawn runner there is no true joint at all. The
method transfers to a real clip unchanged; the numbers belong to this drawing.

## How good is the number?

Three checks, none needing a ground truth. **Cycle to cycle:** at peak swing flexion the
three cycles of the x model agree to a standard deviation of 6° (51, 55 and 63°); over the
whole cycle the median band is ±14°. **Model to model:** the nano model's peak flexion, 53°,
sits inside that band, but its mean curve differs from the x model's by 17° on average, and
the s model finds a different period altogether. **Meaning:** these are angles in the image
plane (Section 3.9) between dots placed where an annotator would click (Section 8.3), so even
a perfect band would bound a picture's angle, not the knee's. With three cycles the band is
itself rough; ten or more cycles from a real clip would tighten it.

## Track it

One row per session once you have a real clip: `date, test=run-form-3.5, metric=knee_swing_min_deg,
value, unit=deg`, with the model size in `device` or `note` and the camera setup in
`protocol_version`, because a change of model or camera moves this number by itself.

## With your own data

Replace the three raw tables with your own (from CS-10's local cells) and run from Step 2.
Only the keypoint tables leave your computer.

## The same method in another field

Averaging many noisy cycles of a repeating process into one curve with a band is how
engineers read a pump's pressure over a revolution or an engine's cylinder pressure over a
cycle. The Data-Driven Engineering page on
[pose estimation](https://apmonitor.com/dde/index.php/Main/PoseEstimation) computes joint
angles from the same kind of table.

## Acknowledgements

Keypoint tables from Chapter 8 of *Data-Driven Athletics*, made with Ultralytics YOLO26
(AGPL-3.0) from the book's example animation.

## Action card

- **Finding:** From this clip, only the knee angle at peak swing flexion is a measurement, about 56° included (a fold of about 124°).
- **Evidence:** Three cycles agree to ±6° at the fold and two model sizes agree within it; elsewhere the band is ±14° and the models differ by 17°.
- **Sure:** Moderate for the fold, low for the rest of the curve; three cycles, one drawn clip, image-plane angles.
- **Action:** Coach the fold only if a real clip, filmed square from the side at 60 fps or more, shows it outside its own band.
- **Retest:** Film 10 s or more of steady running, the same way each time, and compare the fold with its band.

## Challenge: Your own knee, filmed for it

Repeat this study on a real clip: yourself or a partner running on a treadmill or past the
camera, filmed square from the side at 60 frames per second or more for at least 10 s.

1. Build keypoint tables with two model sizes (the local cells of CS-10) and profile the leg points as in Step 2, including a check for repeated frames.
2. Count the left–right swaps in the labelled knee series and fix leg identity or go side-blind; say which you chose and why.
3. Find the cycles from the period, line them up on peak swing flexion and plot the mean with a ±1 standard deviation band for both models.
4. Report the angle at peak swing flexion with its band, and say which other parts of the curve, if any, your clip supports.

Deliverables:

- a notebook that runs top to bottom from the two tables
- the curve with its band, with both models
- a five-line action card

## References

- Chapter 3 of *Data-Driven Athletics*: The angle from three points; What One Camera Sees.
- Chapter 8 of *Data-Driven Athletics*: Cleaning Keypoints; How Good Is the Number? Four Levels of Error.
- Data-Driven Engineering: [YOLO model comparison (pose estimation)](https://apmonitor.com/dde/index.php/Main/PoseEstimation).

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