<!-- Generated by book/tools/make-index.py from the book source. -->

> Hedengren, J. (Ed.) (2027). Chapter 8: Seeing Movement: Video and Pose Estimation. In *Data-Driven Athletics: Measuring, Modeling and Coaching Human Performance with Video and Wearable Data* (pp. 211–235). IRSRI Sports Research Institute. CC BY 4.0.

**Question.** The app drew a skeleton over my video. How far is each dot from the real joint, and which of the numbers can I act on?

**Objectives.**
- Explain frame rate, shutter and resolution, and choose them for a task.
- Tell the stored frame rate of a clip from the rate it was filmed at, and correct every time and speed for the difference.
- Explain what a pose model returns and what its confidence does and does not mean.
- Run a pose model on a clip in Python, put the keypoints in a table and draw the skeleton.
- Set a scale from pixels to meters and state its error.
- Name the four levels of error between a real joint and a reported number, and sort results into three levels of trust.

# 8 Seeing Movement: Video and Pose Estimation

Every app in Part III of this book does the same three things before it
shows you a number. It reads a video one frame at a time. It runs a
*pose model* on each frame, which places dots on the joints. Then it
does geometry on the dots: an angle, a distance, the time between two
events. This chapter teaches those three steps once, so that Chapters 9
and 10 can use them without stopping to explain.

The running example is a short clip from the book's example set: a sketched
runner, drawn by hand and animated, seen from the side
(`form3_30fps.mp4`, 117 frames). A drawing is a fair test. It has the
outline of a person but none of the texture of skin and cloth, which is
exactly the kind of picture a pose model may never have seen in training. A
second clip, a back flip filmed in slow motion against an evening sky
(`jump1_120fps.mp4`), shows what slow motion does to time.

The goal is not to make you distrust video. It is to let you say, for any
number an app gives you, how good it is and why.

## 8.1 A Video Is a Table

A digital video is a stack of still pictures called *frames*. Each frame
is a grid of *pixels*, and each pixel holds three numbers for red, green
and blue. A phone in portrait mode records 1080 pixels across and 1920
down, so one frame holds about two million pixels. The frames are shown one
after another at a fixed *frame rate*, counted in frames per second
(fps).

Think of the video as a table with one row per frame. The row number is
time. If the frame rate is $f$, frame $k$ starts at

$$t_k = \frac{k}{f}, \qquad \Delta t = \frac{1}{f}$$

and the time between two frames, $\Delta t$, is the finest step in time the
video can resolve. At 30 fps one frame lasts 33.3 ms;
at 60 fps, 16.7 ms; at 240 fps,
4.17 ms. A foot that touches the ground for
0.20 s appears in six frames at 30 fps and in 48 at
240 fps.

**Example 8.1: Time between two events.**

A sprinter's foot leaves the ground in frame 112 and lands again in frame
129 of a clip filmed at 60 fps. The flight lasts
$(129-112)/60 = 17/60 = \SI{0.283}{\second}$. Either event could be off by
up to one frame, so the time is good to about $\pm\SI{17}{\milli\second}$,
or $\pm6\%$. At 240 fps the same two events would be 68 frames apart
and the time would be good to about $\pm1.5\%$.

### 8.1.1 Two clocks: the stored rate and the capture rate

Here is the trap that catches almost everyone once. A phone in slow-motion
mode may film at 120 or 240 fps, and then save the file so it plays
back at an ordinary 30 fps. Nothing is lost: every one of the 120
frames filmed in a second is kept. They are simply shown at 30 a second, so
one real second takes four seconds to play. That is what slow motion
*is*.

The file therefore carries two frame rates that you must keep apart:

- the *stored frame rate* (or file rate), written in the file's
header, which is the playback clock; and

- the *capture frame rate*, the rate the camera really recorded at,
which is the clock of the real world.

Every time, rate or speed you report must use the capture rate. A duration
read off the playback clock must be multiplied by

$$\text{real time} = \text{file time} \times
  \frac{f_\text{stored}}{f_\text{capture}}$$

The apps call the ratio $f_\text{stored}/f_\text{capture}$ the real-time
scale; it is 1 when the two rates agree and $30/120 = 0.25$ for a
120 fps capture saved at 30 (shared/frame-rate.ts).

The book's example clips show how common the trap is. Their names give the
rate they were filmed at; their headers say something else. Listing 8.1
reads every header with OpenCV.

**Listing 8.1.** Read the stored frame rate of each example clip (`code/clip_headers.py`).

```python
import glob, os
import cv2

for path in sorted(glob.glob("examples/*")):
    cap = cv2.VideoCapture(path)
    fps = cap.get(cv2.CAP_PROP_FPS)
    n = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    print(f"{os.path.basename(path):18s} {fps:6.2f} fps {n:4d} frames {n/fps:5.2f} s")
```

Part of the output:

```text
form2_60fps.mp4     30.00 fps  362 frames 12.07 s
golf1_60fps.mp4     30.00 fps  133 frames  4.43 s
jump1_120fps.mp4    30.00 fps  148 frames  4.93 s
jump2_120fps.mp4    30.00 fps  190 frames  6.33 s
tennis1_60fps.mp4   30.00 fps  137 frames  4.57 s
softball_1000fps.MOV 33.19 fps  621 frames 18.71 s
```

Every MP4 in the set is stored at 30.00 fps, including the ones named
60 and 120. The back flip in `jump1_120fps.mp4` lasts
$148/30 = \SI{4.93}{\second}$ on the playback clock, but it was filmed at
120 fps, so the real flip, from arm swing to landing, took
$148/120 = \SI{1.23}{\second}$. (The softball clip is a screen recording of a
slow-motion replay; its header rate, 33.19, belongs to neither the camera nor
any standard.) Check that the frames are distinct, too: in
`jump2_120fps.mp4` every sixth frame repeats the one before it (32
of 190), so if the capture rate was 120, six file frames span only five
capture intervals, and a count of file frames at $1/120$ of a second each
overstates a duration by about a fifth.

> **Check it by hand: The slow-motion error.**
> 
> A jumper is in the air for 60 frames of a clip whose header says
> 30 fps. Read naively, the flight lasts $60/30 = 2.00 s$,
> and the height from flight time, $h = g t^2/8$ (Chapter 3), is
> $9.81 \times 2.00^2/8 = 4.91 m$: higher than a basketball rim.
> The clip was filmed at 120 fps. The real flight is
> $60/120 = 0.50 s$ and the height is
> $9.81\times0.50^2/8=0.307 m$. Time is wrong by the ratio of the
> rates, 4; height goes with time squared, so it is wrong by $4^2 = 16$.
> *Confirm it:* open the Jump app (https://apopt.com/jump/jump.php), load a slow-motion
> clip, and change the frame rate from the detected value to the rate you
> filmed at. The flight time drops by the ratio of the two rates.

How do the apps handle this? The policy is in shared/frame-rate.ts
and is the same in every app. The app reads the stored rate from the file's
header (lines 54–143). If it cannot, it assumes 60 fps (line 335).
You can override it with the rate you filmed at, chosen from 24, 25, 30, 50,
60, 120, 240, 480, 960 or 1000 (line 341). When the rate in use is below
59.94 fps the app shows a quiet note, and still analyzes the clip
(lines 338 and 378–381):
This video is 30 fps, so quick moments can fall between frames. If it was
filmed in slow motion (for example 120 or 240 fps) and saved at 30 fps,
choose the recorded frame rate so times and speeds are correct.

No app can tell from the file alone that a 30 fps file was filmed at
120. Only you know. That is why the capture rate appears in every app lab in
this book as “the setting that matters.”

*Figure 8.1. Slow motion stores every captured frame but plays them at the stored rate. Twelve frames captured in 0.1 s at 120 fps play over 0.4 s at 30 fps, on one time axis. Dashed lines join each captured frame to the moment it is shown. A time read off the playback clock must be multiplied by $30/120$.*

> **Engineer's note: Where the stored rate lives in the file.**
> 
> An MP4 or MOV file is a set of nested boxes. The video track's media header
> (`mdhd`) gives a *timescale*, the number of clock ticks per
> second, and its time-to-sample table (`stts`) gives how many ticks
> each frame lasts. The stored rate is
> $f = N \times timescale/total ticks$ for $N$ frames, which is
> exactly what shared/frame-rate.ts computes (lines 129–138). A
> slow-motion file and a normal one differ only in these numbers; the pictures
> are the same. Some phones also write the capture rate in other metadata, but
> not in a standard place, so the apps do not rely on it.

> **Key idea.**
> 
> Keep three rates apart. The *stored* rate is the playback clock. The
> *capture* rate is the real clock, and every time, rate and speed uses it.
> The *sampling* rate is how often the app runs the pose model, which may
> be every frame or fewer. Confusing the first two is the commonest large error
> in phone video analysis, and it can be a factor of 4 or 8 in time and 16 or 64
> in a height.

## 8.2 Filming for Measurement

A pose model can only find what the camera recorded. Most errors you can
remove at all, you remove before you press record. Five choices matter.

\paragraph{Square to the motion.} Put the camera's line of sight at right angles
to the plane the movement happens in. A runner, a jumper or a knee bending is
filmed from the side; a pelvis tilting side to side is filmed from the front or
behind. Section 8.8 shows how fast an angle goes wrong as the
camera turns away from square.

\paragraph{Still, level and far enough back.} Use a tripod or a stack of books.
A moving camera turns every position into position minus camera motion. Stand
the camera back and zoom with your feet, not the lens: a camera close to a
moving athlete sees the near limb larger than the far one, and the scale changes
as the athlete moves toward or away from it. Put the lens at about the height of
the part you care about: hip height for running, waist height for a jump.

\paragraph{Light and shutter.} The *shutter time* is how long each frame
collects light. A foot moving at 10 m/s smears across
17 cm in a $1/60$ s exposure, but only
1 cm in $1/1000$ s. Phones choose the shutter
themselves and lengthen it in dim light, so good light buys short shutters and
sharp limbs. Outdoors in daylight is best; a dim gym is worst.

\paragraph{Resolution and framing.} Keep the whole body in the frame for the
whole movement, but let it fill as much of the frame as it can. A joint that is
48 px from its neighbor is placed less precisely, in angle terms, than
one that is 300 px away. Do not use digital zoom; it enlarges pixels
without adding detail.

\paragraph{Clothing and a reference.} Close-fitting clothing in a color that
contrasts with the background lets the model see the outline of the limbs.
Loose shorts hide the hip and knee. If you will need meters, put something of
known length in the plane of the movement: a meter stick on the floor along
the running line, a lane marking, a court line
(Section 8.6).

*Figure 8.2. A setup for measuring from the side: camera still, square to the movement, far enough back to keep the whole body in frame, with a reference of known length in the plane of the movement. The tripod scene is a generated illustration.*

> **Limits and cautions: Filming other people.**
> 
> A video of a person is personal data. Film yourself first. Before you film a
> teammate or an athlete, say what the clip is for, who will see it and when
> it will be deleted, get their written consent, and accept a no. For anyone
> under 18, a parent or guardian gives written consent and the athlete gives
> their own assent, and no image of a minor leaves the team. Keep other people out of the frame, and do not
> share a clip, or give it to an outside AI service, without the athlete's
> agreement. The consent form in Appendix E covers these points.

Each app turns these rules into one or two lines. Table 8.1
quotes them from the apps' source.

*Table 8.1. Capture instructions shown by apps used in this chapter, quoted from the source.*

| App | Instruction |
|---|---|
| Jump | “Film one jump from the side, with the whole body in frame from the start to the landing.” “Keep the phone still, on a tripod at about waist height, at 60 fps or more if it offers it.” “Every frame of the video is analyzed. For slow motion, choose the rate you recorded at.” |
| Running | “Film from the side or from behind, with 10 to 30 seconds of steady running.” “Keep the whole body in the frame and the phone still, at about hip height.” |
| Range of motion (knee) | “Place the affected leg closest to the camera.” “Complete 3 slow bends and straightens.” “Hold each comfortable endpoint for about 1 second.” |
| Range of motion (shoulder) | “Face the camera with both arms and hips visible.” “Raise both arms out to the sides, then lower.” |
| Hip drop | “Wear a bright band flat around the waist, in a color nothing else in the frame shares.” “Film from the front or from behind with a fixed, level camera and even light.” |

## 8.3 From Pixels to Keypoints

A pose model is a *neural network*: a long chain of simple arithmetic
steps whose millions of coefficients were tuned, not written by hand. The
tuning is called *training*. People drew dots by hand on the joints of
people in hundreds of thousands of photographs, and the coefficients were
adjusted, step by small step, until the network's dots landed close to the
hand-drawn ones. The most used set of such photographs is COCO, which marks 17
*keypoints* on each person: the nose, and the left and right eyes, ears,
shoulders, elbows, wrists, hips, knees and ankles .

Three consequences follow from how a model is made.

First, a keypoint is *where a person would have clicked*, not the joint's
center of rotation. Annotators click on the visible bump of a knee or the
crease of a hip. Needham and colleagues compared several pose models with
marker-based motion capture and found the models' hip and knee points sat
about \SIrange{30}{50}{\milli\metre} from the laboratory joint centers, with
smaller differences at the ankle .

Second, for each keypoint the model returns a *confidence*, a number from
0 to 1. It is the model's own score of how sure it is that the point is
visible and where it put it. It is *not* a measured probability that the
point is within some distance of the truth. Figure 8.3
shows a small model placing a knee and an ankle mid-shin with confidences of
0.99. Confidence is useful for throwing out bad frames, but high confidence
does not prove a point is right.

Third, a model does best on pictures like the ones it learned from: upright
people, in ordinary clothes and light, seen whole. It does worse on postures
that are rare in photographs (upside down in a flip, a swimmer's arm under
water), on limbs hidden behind the body (*occlusion*), on loose clothing,
and on bodies that differ from the training set .
Our sketched runner is an outline, not a photograph, and the flip is a black
silhouette that turns upside down. Both are fair tests of this third point.

Table 8.2 lists the failures you will meet most often,
what each looks like in the overlay, and what to do about it.

*Table 8.2. Common pose-model failures in sport video and what to do about them.*

| Failure | What you see | What to do |
|---|---|---|
| Occlusion | The far arm or leg jumps or sits on the near one | Film the side you measure; report that side only |
| Left–right swap | A knee angle that flips between two values from stride to stride | Fix leg identity over the clip; compare side-blind |
| Rare posture | Points lost or scattered when the body is inverted, folded or horizontal | Use a larger model; mark key frames by eye |
| Motion blur | Wrists and feet trail or vanish in fast phases | More light, a shorter shutter, a higher capture rate |
| Loose clothing | Hip and knee drift inside baggy shorts or a hoodie | Close-fitting clothes in a contrasting color |
| Second person | The skeleton jumps to a coach or teammate | One athlete in frame; others well behind |
| Silhouette or poor light | Low confidence across the board | Light the athlete from the camera side |

> **Body science: A joint is not a dot.**
> 
> A knee is not a hinge with a fixed pin. As it bends, the thigh bone rolls and
> glides on the shin bone, so the axis it turns about moves by several
> millimeters. The hip is a ball deep inside the pelvis, covered by muscle; the
> skin over it moves when the leg moves. A marker on the skin, a hand-drawn dot
> and a model's keypoint are three different stand-ins for a joint center that
> nobody can see from outside. Laboratory systems estimate it from several
> markers and a model of the bones; a phone video gives you one surface dot. For
> angles in the plane of a side view this matters by a few degrees; for small
> frontal-plane tilts it can matter more than the signal.

### 8.3.1 How the models find people

Pose models come in three designs. A *top-down* model first draws a box
around each person, then finds the keypoints inside each box, usually by
computing a “heat map” for each keypoint and taking its hottest
spot . A *bottom-up* model finds every
knee, every hip and so on in the whole picture first, then works out which
belong to the same person . A
*single-stage* model does both at once, returning boxes and keypoints in
one pass through the network . The YOLO pose
models used in this book are single-stage; MoveNet, the apps' default, is
designed for one person per frame . For sport
the design matters less than two practical facts: whether the model keeps
track of the right person when several are in view, and how fast it runs.

### 8.3.2 Model size against speed

Most model families come in sizes. A bigger model has more coefficients, is
more accurate on the benchmark it was tested on, and is slower.
Table 8.3 gives the five sizes of the YOLO26 pose model.
The accuracy column is the standard COCO score (mean average precision, 0 to
100, higher is better) published with the
models ; the speed columns are measured in
a browser on one fast laptop with a graphics processor, as used by the apps
(YOLO/BENCHMARK.md).

*Table 8.3. YOLO26 pose models: benchmark accuracy, size and time per frame in the browser (one $640640$ input, graphics-processor backend, measured 2026-07-15).*

| Size | COCO pose score | Parameters (millions) | Time per frame (ms) | Frames a second |
|---|---|---|---|---|
| n | 57.2 | 2.9 | 11.1 | 90 |
| s | 63.0 | 10.4 | 16.5 | 60 |
| m | 68.8 | 21.5 | 28.3 | 35 |
| l | 70.4 | 25.9 | 33.9 | 30 |
| x | 71.6 | 57.6 | 60.7 | 16 |

Going from n to s adds 5.8 points of accuracy for 5.4 ms a
frame; going from l to x adds 1.2 points for 27 ms. That
is why the apps offer all five but start YOLO at size s
(shared/model-catalog.ts line 22). Time per frame adds up: a
12 s clip filmed at 60 fps is 720 frames, about
12 s of work for size s on that laptop; the same clip filmed at
240 fps is 2880 frames and about 48 s. A phone is slower.

## 8.4 Pose Estimation in Python

You can run the same family of models yourself in a few lines, with the open
Ultralytics library .
Listing 8.2 reads a clip frame by frame, runs the pose model,
keeps the most confident person in each frame, and writes one row per frame:
the frame number, an $x$ and $y$ in pixels for each of the 17 keypoints, and
17 confidences. The weights file is named in one place, so you can change the
model size by changing one line, or by passing a name on the command line.

**Listing 8.2.** Keypoints of every frame into a table (`code/pose_table.py`).

```python
import sys
from ultralytics import YOLO
import pandas as pd

WEIGHTS = sys.argv[1] if len(sys.argv) > 1 else "yolo26n-pose.pt"
CLIP = sys.argv[2] if len(sys.argv) > 2 else "form3_30fps.mp4"
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"]

model = YOLO(WEIGHTS)
rows, ms = [], []
for i, r in enumerate(model(CLIP, stream=True, verbose=False, device="cpu")):
    ms.append(r.speed["inference"])               # milliseconds for this frame
    if r.keypoints is None or len(r.keypoints) == 0:
        continue                                  # no person found
    best = int(r.boxes.conf.argmax())             # most confident person
    xy = r.keypoints.xy[best].tolist()            # 17 points, pixels
    conf = r.keypoints.conf[best].tolist()        # 17 confidences, 0 to 1
    rows.append([i] + [v for p in xy for v in p] + conf)

cols = ["frame"] + [f"{n}_{a}" for n in NAMES for a in "xy"] + [f"{n}_c" for n in NAMES]
df = pd.DataFrame(rows, columns=cols)
df.round(3).to_csv(f"{CLIP[:-4]}_{WEIGHTS[:-3]}.csv", index=False)
print(f"{WEIGHTS}: {len(df)} of {i + 1} frames with a person, "
      f"median {sorted(ms)[len(ms) // 2]:.0f} ms a frame")
print(df[["l_knee_c", "l_ankle_c", "nose_c"]].describe().loc[["mean", "min"]].round(2))
```

Run with the nano model and then the small one, on a 20-core processor with no
graphics card (Ultralytics 8.4.219, weights `yolo26n-pose.pt` and
`yolo26s-pose.pt`), the listing prints:

```text
yolo26n-pose.pt: 117 of 117 frames with a person, median 72 ms a frame
      l_knee_c  l_ankle_c  nose_c
mean      0.98       0.90    0.89
min       0.83       0.41    0.47
yolo26s-pose.pt: 115 of 117 frames with a person, median 192 ms a frame
      l_knee_c  l_ankle_c  nose_c
mean      0.97       0.83    0.82
min       0.80       0.23    0.04
```

Your times will differ with your computer; the keypoints and confidences
should match to the second decimal. On a processor without a graphics card
the small model takes between two and three times as long as the nano model, in line with
its 3.6 times as many parameters.

### 8.4.1 Comparing two model sizes

Which output is right? The nano model found a person in every frame and is
more confident on average. That tells you nothing about which points are
closer to the joints. To compare, put the two tables side by side
(code/compare_sizes.py) and measure, for each keypoint and each
frame, the distance between the two models' dots. On the sketched runner the
two models' noses agree to a median of 7.6 px, their left hips to
26.8 px, their left knees to 44.7 px and their left ankles to
82.3 px, against a shoulder–hip–knee–ankle chain about
707 px long. The disagreement grows down the leg.

Part of it is not about placement at all. In a side view the two legs cross
twice a stride, and a model can label the near leg “left” in one frame and
“right” in the next. In 30% of frames the nano model's left ankle sat
closer to the small model's *right* ankle. If you ignore which side is
which, the ankle disagreement drops from 82 px to 48 px. This
is the *left–right swap*, and every gait app has to deal with it
(Section 8.7).

Once keypoints are in a table, any angle is a few lines of array arithmetic.
Listing 8.3 computes the left knee's included angle in
every frame from both tables at once.

**Listing 8.3.** The left knee angle in every frame from two models (`code/knee_series.py`, shortened).

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

def knee(df, side="l"):
    hip, kn, an = (df[[f"{side}_{j}_x", f"{side}_{j}_y"]].values
                   for j in ("hip", "knee", "ankle"))
    u, v = hip - kn, an - kn                       # vectors from the knee
    cos = (u * v).sum(1) / np.linalg.norm(u, axis=1) / np.linalg.norm(v, axis=1)
    return pd.Series(np.degrees(np.arccos(np.clip(cos, -1, 1))), index=df["frame"])

a = knee(pd.read_csv("form3_30fps_yolo26n-pose.csv"))
b = knee(pd.read_csv("form3_30fps_yolo26s-pose.csv"))
d = (a - b).dropna().abs()
print(f"median left knee angle: n {a.median():.1f}, s {b.median():.1f} deg")
print(f"frames compared {len(d)}, median |n - s| {d.median():.1f} deg, "
      f"frames differing by more than 10 deg: {(d > 10).sum()}")
```

```text
median left knee angle: n 133.6, s 127.2 deg
frames compared 115, median |n - s| 10.7 deg, frames differing by more than 10 deg: 65
```

Two models, one clip, and the left knee angle differs by more than \ang{10} in
65 of 115 frames. The median angles over the clip differ by \ang{6.4}. A
coach comparing a knee angle from one model last month with one from another
model today would be comparing the models, not the runner. Keep the model the
same from session to session, and record it.

*Figure 8.3. Frame 30 of the sketched-runner clip with the keypoints of (left) YOLO26n and (right) YOLO26s. The runner faces left. Solid lines join the runner's left-side keypoints, dashed lines the right side. The nano model places both ankles mid-shin and the right knee in the thigh, with confidences of 0.94 to 0.99; the small model follows both legs to the feet. Drawn by `code/draw_skeleton.py` from the tables of Listing 8.2.*

Figure 8.3 shows the worst kind of disagreement. In frame
30, as the runner drives the front knee up, the nano model loses both legs:
its ankles sit mid-shin. Every one of those points has confidence 0.94 or
more. The small model gets the legs right. Notice what this does to the
numbers. The left knee's included angle is \ang{90.8} from the nano model and
\ang{89.4} from the small one, an agreement that is pure luck; the right knee
is \ang{137.1} against \ang{159.5}. One frame, one wrong model, and a
\ang{22} error with nothing in the confidence to warn you. The only defenses
are to look at the skeleton drawn on the video, and to compare models.

Table 8.4 runs all five sizes on both clips
(code/sizes_table.py). On the flip, no model finds a person in every
frame, and bigger models find more. On the runner, the medium model misses ten
frames that the nano model finds. Average confidence does not rise with model
size: confidences from different models are on different scales and cannot be
compared with each other.

*Table 8.4. Five YOLO26 pose sizes on two example clips: frames in which a person was found, mean confidence over all keypoints, and share of keypoints below 0.3. CPU time per frame on the computer used for Listing 8.2.*

|  | 3cSketched runner (117 frames) | 3cBack flip (148 frames) |  |  |  |  |
|---|---|---|---|---|---|---|
| Size | Found | Mean conf. | Below 0.3 | Found | Mean conf. | Below 0.3 |
| n (72 ms) | 117 | 0.84 | 10.5% | 94 | 0.65 | 21.4% |
| s (190 ms) | 115 | 0.79 | 14.7% | 88 | 0.58 | 32.0% |
| m (430 ms) | 107 | 0.77 | 16.2% | 104 | 0.60 | 23.8% |
| l (580 ms) | 117 | 0.83 | 12.3% | 112 | 0.62 | 24.5% |
| x (1060 ms) | 117 | 0.79 | 14.4% | 125 | 0.58 | 29.9% |

### 8.4.2 A confidence trace

Plotting one keypoint's confidence against frame number is the quickest
health check of a clip. Figure 8.4 does it for the left
ankle (code/conf_trace.py). On the runner the trace sits near 1 with
short dips where the legs cross, which are the frames where swaps happen. On
the flip it starts empty, because neither model finds a person while the
athlete swings the arms and leaves the ground, then wobbles while the body is
inverted, and stops again on landing, when the legs disappear into the dark
foreground. A dotted line marks 0.3, the threshold most of the apps use.

*Figure 8.4. Left-ankle confidence frame by frame for YOLO26n (solid line, circles) and YOLO26s (dashed line, squares). Tick marks below zero mark frames in which that model found no person (upper row n, lower row s). The dotted line is the 0.3 threshold. (a) The sketched runner. (b) The back flip, filmed at 120 fps and stored at 30, so the 148 frames span 1.23 s of real time.*

> **Check the AI: A plausible listing with one flaw.**
> 
> Asked for code to time a jump from a slow-motion clip, an assistant wrote
> `fps = cap.get(cv2.CAP_PROP_FPS)` and then
> flight = (landing - takeoff) / fps. The code runs, and on a
> 30 fps phone clip it is right. On every slow-motion clip it is wrong by
> the ratio of the rates, because `CAP_PROP_FPS` reads the stored rate.
> The fix is one line: take the capture rate from the person who filmed the clip,
> and use it in the division. Ask the assistant which rate its code assumes,
> and test it on a clip whose answer you know.

## 8.5 In the Browser

The apps at \apopt{} run the same kind of model inside the web page, on your
phone or laptop. The video never leaves the device: it is read from the file
you choose, analyzed by the page, and the results are drawn and saved where
you are. Three reasons make this the right design for athlete video. Video of
a person is personal data, and data that is never uploaded cannot leak from a
server. It works in a gym with poor internet. And it costs nothing to run for
a whole team.

Which model runs? Say it plainly: *the apps default to MoveNet Thunder*,
a single-person model with the same 17 COCO
keypoints  (form/src/App.tsx line
282; canvas/src/lib/pose-estimation.ts line 152). They also offer
the YOLO26 pose models in all five sizes, starting at s, and BlazePose, a
33-landmark model that adds heels and toes 
(form/src/lib/pose-estimation.ts lines 71–145). The book's Python
listings use YOLO because it is open, it runs the same way on any computer,
and it is one of the apps' options, so you can compare like with like.
Exercise 8.10 asks you to compare the apps' default with
YOLO on your own clip.

Two details of the browser models matter when you compare with Python. The
YOLO models in the page see each frame shrunk to $640\times640$ pixels, with
bands added to keep its shape (form/src/lib/pose-estimation.ts lines
531 and 683–696), as Ultralytics does by default. And the apps keep only the most
confident person whose score is above 0.25 (line 800). If two people are in
the frame and the wrong one is more confident, the app follows the wrong one;
film one athlete at a time.

> **Status: 2026.**
> 
> {Models in the apps}
> MoveNet Lightning and Thunder (default), BlazePose Heavy, and YOLO26 pose in
> sizes n, s (the YOLO default), m, l and x. YOLO runs on the graphics processor
> through WebGPU where the browser supports it, and on the processor otherwise.
> Models are replaced from time to time; each app's report names the model
> that produced it, so record it with your results.

## 8.6 Scale: From Pixels to Meters

A pose model works in pixels. Angles and times need nothing else. A length or a
speed in meters needs a *scale*, the number of pixels per meter, $s$, in
the plane where the movement happens:

$$s = \frac{\text{length in pixels}}{\text{length in meters}}, \qquad
  \text{distance in meters} = \frac{\text{distance in pixels}}{s}$$

There are three common ways to get $s$, and each carries its own error.

\paragraph{A known object.} Lay a meter stick on the ground along the line of
the movement, film it, and measure its length in pixels. The canvas app does
exactly this: you draw a line along the object and type its length
(canvas/src/lib/coordinates.ts lines 30–33).

**Example 8.2: Scale from a meter stick.**

A 1.00 m stick spans 412 px in the frame, so
$s = \SI{412}{\px\per\metre}$. A foot that moves 300 px between two
frames has moved $300/412 = \SI{0.728}{\metre}$. If you misplace each end of
the stick by 4 px, and both errors lengthen it, the stick reads
420 px and every distance is off by $8/412 = 1.9\%$, about 2%. If
the two end errors are independent, their combined standard deviation is
$\sqrt{2}\times4/412 = 1.4\%$. A longer reference, or one measured over
several frames, makes this smaller.

The larger error is usually not in the pixels but in the depth. The scale is
true only at the distance of the object you measured. If the stick lies
0.5 m nearer the camera than the athlete's path, and the camera is
5 m from the path, the stick looks $5/4.5 = 1.11$ times as large,
so the scale is 11% too high and every distance on the athlete comes out
$4.5/5 = 0.90$ of its true length: 10% short. Put the reference exactly in the
plane of the movement.

\paragraph{The athlete's own height.} If you know the athlete's
*stature* (standing height), the body is its own ruler. The model has no
point on the top of the head or the sole of the foot, so the app measures a
span it can see and corrects for the part it cannot. The Jump app uses the
span from the eyes to the lower ankle, multiplied by 1.115, or from the nose,
multiplied by 1.126, because by standard body proportions those spans are
about 0.897 and 0.888 of stature (jump/src/lib/metrics.ts lines
1005–1019). It takes the 85th percentile of the frame-by-frame values (line
534), because a bent knee shortens the span and a tall reading is more likely
to be an upright one. The span you can see also depends on posture, on the
model's head and ankle points and on the stature you type: entering
1.75 m for an athlete who is 1.80 m makes every
distance $1.75/1.80 = 0.972$ of its true length, 2.8% short.

The Running app uses the same share: it divides the median nose-to-ankle
span by 0.888 of stature (form/src/lib/metrics.ts lines 3340–3374).
With a span of 800 px on a 1.80 m runner both apps
compute 500 px/m. An earlier version of the Running app
divided by the full stature, 444 px/m, so every length it
reported was 12.6% long; comparing the two apps' rules side by side exposed
the difference, and the Running app was changed. A share of 0.888 is still an
average body, not your athlete's, and neither rule is “the” answer until it
is checked against a tape measure, which is the point of
Exercise 8.8.

\paragraph{Court, field and pool markings.} Sports surfaces are rulers that
someone has already measured. A tennis court is 23.77 m long and
8.23 m wide for singles, and each service line is
6.40 m from the net . In a basketball
court the far edge of the free-throw line is 5.80 m from the inner
edge of the end line . In a competition pool the
lanes are 2.5 m apart center to center, the dark line on the bottom
of each lane ends 2.0 m from each wall in a cross line, and the lane
ropes change color 15 m from each end
wall . Two marks in the plane of the
movement give a scale; marks at different distances from the camera give
different scales, and the difference tells you how much perspective matters
in your shot.

**Example 8.3: Scale from a tennis court.**

A camera behind the baseline looks down the court at a player waiting to
return serve. At the baseline the two singles sidelines are 1150 px
apart. They are 8.23 m apart on the court, so the scale at the
baseline is $1150/8.23 = \SI{139.7}{\px\per\metre}$. The player moves
300 px sideways along the baseline: $300/139.7 = \SI{2.15}{\metre}$.
The scale holds for movement along the baseline, because the player is in that
plane. It does not hold for the net, 11.89 m farther away, where the
same sidelines look much closer together; that change is a direct measure of
how strongly perspective acts in your shot.

> **Limits and cautions: A scale lives in one plane.**
> 
> A scale is valid only at the distance from the camera where it was set. An
> athlete who runs toward the camera grows in the frame, so a fixed scale reads
> a shorter and shorter stride. A wide-angle phone lens also bends straight
> lines near the edges of the frame. Keep the movement across the middle of the
> frame, square to the camera, and set the scale in that plane. Report lengths
> and speeds with their scale method, and treat them as the least trustworthy
> numbers from a single camera (Section 8.9).

## 8.7 Cleaning Keypoints

Raw keypoints are noisy. The four steps below turn them into something a
metric can use, and each has a cost.

\paragraph{A confidence threshold.} A point below a threshold is treated as
missing, not as zero. Most of the apps use 0.3: the canvas app's default
threshold (canvas/src/lib/project-config.ts line 23), the Running
app's keypoints for scale and angles (form/src/lib/metrics.ts line
3379), and the skeleton drawing, which leaves out a bone if either end is
below 0.3 (form/src/lib/pose-estimation.ts line 931). A higher
threshold throws away more frames; a lower one lets more wrong points in. As
Figure 8.3 showed, no threshold catches a wrong point the
model is sure of.

\paragraph{Gaps.} A metric that needs a missing point returns no value, rather
than an invented one. Some apps fill short gaps by drawing a straight line
between the points on either side (linear interpolation), which is reasonable
over a frame or two and misleading over a stride.

\paragraph{Left–right swaps.} Because a side view sees one leg behind the
other, the model's “left knee” may jump to the right knee and back. The
Running app fixes which leg is which over the whole clip before it computes
anything (form/src/lib/pose-processing.ts lines 35–52), so a swap in
one frame cannot cut a stride in half.

\paragraph{Smoothing.} Averaging each point over a few neighboring frames
removes frame-to-frame jitter. The width of the averaging window should be set
in seconds, not frames, so that a clip filmed at 30 and one at
240 fps are smoothed the same. The canvas app averages over
$0.1\,f$ frames, rounded to an odd number and at least 3
(canvas/src/lib/smoothing.ts lines 42–53), and never averages
across a frame where the point was below threshold. The Running app smooths
its torso and arm points over $7/60$ of a second, rounded to an odd number of
frames from 5 to 29 (form/src/lib/pose-processing.ts lines 102–113
and 280–289). Table 8.5 shows that a limit in frames
still shows through: at 30 fps the Running app's 5-frame minimum
spans 0.17 s, not 0.12. Earlier versions set the limits in
frames alone, a minimum of 7 in the Running app (0.23 s at
30 fps, twice the aim) and a maximum of 15 in the canvas app (only
0.06 s at 240 fps); a table like this one is how the
problem was found.

*Table 8.5. Smoothing windows in frames and seconds at four capture rates, from the rules in the app source.*

| Capture rate | 30 | 60 | 120 | 240 |
|---|---|---|---|---|
| Canvas (frames / s) | 3 / 0.100 | 7 / 0.117 | 13 / 0.108 | 25 / 0.104 |
| Running (frames / s) | 5 / 0.167 | 7 / 0.117 | 13 / 0.108 | 27 / 0.113 |

Smoothing has a price. A window of 0.1 s rounds off anything
shorter: the instant of foot strike, the snap of a wrist at release. So the
apps keep two versions. Pictures are drawn from the *raw* points, so the
skeleton you see is exactly what the model said; some metrics use the
*filtered* points. If a drawn skeleton looks wrong, the number built from
it is suspect, smoothed or not.

## 8.8 How Good Is the Number? Four Levels of Error

Between a real joint and a number in a report, error can enter at four levels.
Separating them matters because each is reduced by a different means, and one
of them by none.

\paragraph{1. Landmark placement.} The model puts the dot in the wrong place.
This includes the systematic offset of a few centimeters between a keypoint
and a joint center , frame-to-frame jitter,
swaps, and the gross failures of Figure 8.3. Light,
framing, clothing, a better model, and looking at the overlay reduce it. Its
effect on an angle depends on how long the segment is in the picture.

> **Check it by hand: Angle error from point error.**
> 
> A shank spans 150 px in the frame. If the ankle point is
> 5 px off, sideways to the shank, the shank's direction changes by
> $\arctan(5/150) = \ang{1.91}$. The same 5 px on a 300 px
> shank costs \ang{0.95}. A pelvis is narrower still: two hip points
> 100 px apart, each with 5 px of independent vertical error,
> give a tilt error of $\sqrt{2}\times5/100 = 0.071$ radians, or \ang{4.05}:
> as large as the pelvic drop a coach is looking for. That is why the Hip drop
> app does not use pose keypoints at all.

> **Engineer's note: Where $2\,/w$ comes from.**
> 
> Two points a horizontal distance $w$ apart define a tilt
> $\alpha = \arctan(\Delta y/w)\approx\Delta y/w$ for small angles. If each
> point's height has an independent error with standard deviation $\sigma$, the
> difference $\Delta y$ has standard deviation $\sqrt{\sigma^2+\sigma^2} =
> \sqrt2\,\sigma$, because variances of independent errors add. So the tilt has
> a standard deviation of $\sqrt2\,\sigma/w$ radians; multiply by $180/\pi$ for
> degrees. Doubling $w$ halves the error, which is the whole argument for a long
> waist band instead of two hip points.

\paragraph{2. Projection.} A camera flattens three dimensions into two. A
segment tilted by $\psi$ out of the picture plane looks shorter by a factor
$\cos\psi$: 1.5% at \ang{10}, 6.0% at \ang{20}, 13.4% at \ang{30}.
An angle between two segments changes too. Take a knee bent to an included
angle of \ang{120} (thigh vertical), filmed from the side; turn the camera
\ang{20} off square and the picture shows \ang{121.6}; at \ang{40} off, it
shows \ang{127.0}. At \ang{150} the same turns give \ang{151.5} and
\ang{156.1}; a \ang{90} knee with the thigh \ang{45} forward reads \ang{93.6} and \ang{105.1} (Figure 8.5, code/projection.py). Only camera placement reduces
projection error. It is why side-view (sagittal) angles agree with laboratory
systems much better than front-view (frontal) or twisting (transverse)
angles .

*Figure 8.5. Projection error in a knee's included angle when a side-view camera turns away from square, for three knee positions in the sagittal plane (`code/projection.py`). The error is small within about 10, grows roughly with the square of the turn, and depends on how the segments are oriented, not only on the angle between them.*

\paragraph{3. Event placement.} A time is the difference between two frames
chosen by a rule: first frame the foot is off the ground, frame of greatest
knee bend. Each event can be one frame early or late, so one frame,
$1/f_\text{capture}$, is the floor on timing error, and a rule that is
confused by noise can be off by more. The wrong capture rate is an event
error that multiplies every time in the report.

\paragraph{4. Interpretation.} The last level is the inference you draw from a
correct number, and it is the only one that a better camera, model and rule
leave exactly where they were. A knee angle on a screen is not the angle
between the bones. A tilted waist band is not the pelvis. A movement is not a
force: Straub and Powers found that the knee's inward angle in a front-view
video predicted the knee's frontal-plane load only weakly to moderately during
landing and cutting, and not at all during
stepping . None of the apps measures pain,
strength or injury risk, and none of their outputs is a diagnosis.

> **Key idea.**
> 
> Ask where a number could have gone wrong, level by level: was the dot in the
> right place, was the camera square, was the event in the right frame, and does
> the number mean what you are about to say it means? Fix the first three with
> better filming and checking. The fourth is fixed only by care in what you
> claim.

How large are these errors in practice? Published comparisons of single-camera
pose with laboratory motion capture give a feel, not a guarantee for your
clip. In side-view walking video, one study found mean absolute errors of
about 0.02 s in timing, 0.05 m in step length, and
\ang{4} to \ang{7} in hip, knee and ankle angles .
Another found hip angles within about \ang{4} to \ang{5} for the better
models, MoveNet Thunder among them .
Multi-camera systems do better .
Every one of these numbers belongs to the system that was tested; none of the
apps in this book has been validated in the same way. The free checks in this
chapter, a printed protractor, a meter stick, a frame count, are how you
measure the error on *your* setup.

## 8.9 Three Levels of Trust

The four levels do not weigh equally on every result. That gives a simple
ordering of what to trust, in Table 8.6.

*Table 8.6. Three levels of trust for single-camera results, after the error levels each inherits.*

| Level | What it includes and why | Examples |
|---|---|---|
| 1. Most trusted | Counts, durations and ratios of like quantities. No scale; landmark error enters only through the event rule; insensitive to camera distance. Needs the right capture rate. | Repetitions, cadence, contact time, duty factor, completion time |
| 2. Next | Angles in the plane the camera is square to. No scale; landmark error enters in full; projection error only as far as the movement leaves the plane. | Knee flexion from the side, trunk lean, elbow range of motion |
| 3. Least trusted | Front-view tilts, and anything in meters. All four levels, the projection level largest, plus the scale error. | Pelvic drop, knee inward angle, stride length, jump height from position, speed |

Read the table as a rule for decisions. Act on a level-1 number after
checking the frame rate. Act on a level-2 number after checking the camera
was square and the overlay sits on the limbs. Treat a level-3 number as a
trend within one athlete, filmed the same way each time, and check it against
a tape measure or a marked line before you compare it with anyone else's.

## 8.10 Is This Video Good Enough?

Before you analyze a clip, or before you believe the report, spend two minutes
on five checks. Each takes one look and catches a different level of error.

- **The clock.** What rate was it filmed at, and what does the file
say? If they differ, set the capture rate in the app. (Event level.)

- **The view.** Is the camera still and square to the movement, and
is the whole body in frame for the whole movement? (Projection level.)

- **The person.** In what share of frames was a person found, and does
a confidence trace like Figure 8.4 stay above the
threshold through the part you care about? (Landmark level.)

- **The overlay.** Step through the key frames with the skeleton drawn
on: does every dot you will use sit on the right limb, on the right side?
(Landmark level, the part confidence misses.)

- **The claim.** Does the number you want belong to a level of trust
that supports the decision you will make with it? (Interpretation level.)

**Example 8.4: Two clips through the five checks.**

The *sketched runner*: filmed and stored at 30, so the clock is right but
one frame is 33 ms, coarse for foot contact; side view,
camera still, whole body in frame; a person in 115 or 117 of 117 frames,
depending on the model; but the overlay shows frames, such as frame 30, where
the nano model loses both legs at high confidence. Verdict: good enough for
cadence and for trunk angles; knee angles only with the small model, after
looking at the overlay.

The *back flip*: filmed at 120 and stored at 30, so every time must be
multiplied by 0.25; side view, still camera; but no model finds the athlete in
every frame, and the legs vanish into the dark foreground at takeoff and
landing. Verdict: fine for the time from the top of the arm swing to landing in
real seconds, if you mark those frames by eye; not good enough for an automatic
flight time, because the frames that define takeoff and touchdown are the ones
the model cannot see.

## 8.11 Measure Anything

Most apps report a fixed list of measures. The canvas app
(https://apopt.com/canvas/) lets you write your own. A measure is an expression over
named keypoints, using a few functions (canvas/src/lib/formula.ts):
`angle(a, b, c)` is the included angle at $b$; `distance(a, b)`
is a length; `line_angle(a, b)` is the tilt of the line from $a$ to
$b$; and `midpoint`, `abs`, `min`, `max`,
`sqrt`, `pow` and `round` do the rest. Eight common joint
angles are built in, such as `left_knee_angle`, which is
`angle(left_hip, left_knee, left_ankle)`
(canvas/src/lib/angle-definitions.ts line 9). Some examples:

- knee flexion: `180 - angle(left_hip, left_knee, left_ankle)`;

- side-to-side knee difference: `abs(left_knee_angle - right_knee_angle)`;

- ankle gap: `distance(left_ankle, right_ankle)`, in meters once a
scale is drawn.

Each value carries the lowest confidence of its inputs, so a measure is only as
trustworthy as its weakest point, and an angle with a segment too short to have
a direction is returned as missing, not as a number
(canvas/src/lib/variables.ts lines 331 and 392–403). The whole set
of definitions, with the model, the threshold, the frame rate and the scale,
saves to a file. That file, not the number, is what you keep: it lets you or
anyone else run the same measure on next month's video.

**Example 8.5: A knee angle by hand and by app.**

In frame 30 of the sketched runner, YOLO26s puts the left hip, knee and ankle
at $(512, 946)$, $(294, 1025)$ and $(384, 1264)$ pixels. The vectors from the
knee are $\mathbf{u} = (218, -79)$ to the hip and $\mathbf{v} = (90, 239)$ to
the ankle. Their dot product is $218\times90 + (-79)\times239 = 739$; their
lengths are 231.9 and 255.4. So

$$\cos\theta = \frac{739}{231.9\times255.4} = 0.0125,\qquad \theta = \ang{89.3},$$

and the knee flexion is $180-89.3 = \ang{90.7}$. Print
Figure 8.3, lay a protractor on the right-hand panel,
and you should read the same angle within a degree or two. *Confirm it:*
code/checks.py prints \ang{89.3}; in the canvas app, choose YOLO26s,
load the clip and read `left_knee_angle` at frame 30. Expect a few
degrees of difference, because the browser model sees a resized frame.

### 8.11.1 Two fixed cases: range of motion and hip drop

The Range of motion app (https://apopt.com/rom/) is the canvas idea with the measures
chosen for you. It reports knee and elbow *flexion* as 180 minus the
included angle (rom/src/lib/rom-analysis.ts lines 278 and 282), so a
straight knee is \ang{0} and an included angle of \ang{55} is \ang{125} of
flexion. It finds the repetitions, takes the largest flexion in each, and
reports the range; it grades nothing.

The Hip drop app (https://apopt.com/hip/hip.php) is the exception that proves the
rule of the byhand box above. Two hip keypoints are too close together to
give a pelvic tilt of a few degrees, so the app does not use a pose model. You
wear a bright band around the waist; the app finds it by color, fits a
rectangle to it, and reports its tilt as $\arctan$ of the slope between its two
ends (hip/src/lib/analysis.ts lines 58–60). A band
400 px long instead of two points 100 px apart cuts the angle
error by four. The price is that the app measures the band, not the bones, and
a band worn at a different height next week is a different measure.

**Example 8.6: A pelvic tilt by hand and by app.**

In one frame of a front-view clip, the right end of the waist band sits
32 px lower than the left end, and the ends are 400 px apart.
The slope is $32/400 = 8.0\%$ and the tilt is $\arctan(0.080) = \ang{4.57}$
(`hip/src/lib/analysis.ts` lines 58–60 convert a slope in percent to
degrees the same way). Had the tilt come from two hip keypoints
100 px apart with 5 px of error each, its uncertainty alone
would be about \ang{4}; from the band it is about a quarter of that. Two
cautions apply when you compare with the app. The app levels its readings by
subtracting the clip's median tilt, which removes a tilted camera but also any
steady lean; and its ratings (Elite up to \ang{5} for men and \ang{7} for women,
Pro up to \ang{7} and \ang{9}; `hip/src/lib/analysis.ts` lines 31–34)
are product choices, not clinical norms. *Confirm it:* pause the Hip drop
app's annotated video at the frame of greatest drop, measure the band's ends in
pixels on a screenshot, and compare your angle with the app's trace.

## 8.12 Build Step B-8: Your Own Overlay

This week's step for your own app is the fourth check above, in code: a page
that plays a video, steps one frame at a time, and draws the keypoints from a
results file over each frame. Listing 8.4 is the heart of
it, the two pure functions, kept free of the page so they can be tested in Node.

**Listing 8.4.** Frame number from time, and the skeleton drawing (`code/b8-overlay/overlay.js`, shortened).

```javascript
export const EDGES = [[5, 7], [7, 9], [6, 8], [8, 10], [5, 6], [5, 11], [6, 12],
  [11, 12], [11, 13], [13, 15], [12, 14], [14, 16]];

export function frameAt(seconds, fps) {
  return Math.floor(seconds * fps + 1e-6);  // frame k covers [k/fps, (k+1)/fps)
}

export function drawPose(ctx, pose, minConf) {
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  if (!pose) return 0;
  const ok = (i) => pose.conf[i] >= minConf;
  ctx.lineWidth = 6; ctx.strokeStyle = '#0369A1';
  let drawn = 0;
  for (const [i, j] of EDGES) {
    if (!ok(i) || !ok(j)) continue;          // skip a bone with a doubtful end
    ctx.beginPath(); ctx.moveTo(...pose.points[i]); ctx.lineTo(...pose.points[j]);
    ctx.stroke(); drawn += 1;
  }
  return drawn;
}
```

Two details decide whether the overlay lines up. First, step on the
*stored* clock: the CSV counts frames in the file, so frame $k$ is at
$k/f_\text{stored}$ whatever the capture rate. Seek to the middle of the frame,
$(k+0.5)/f_\text{stored}$, not its start, because a seek that lands exactly on
a frame boundary can show the previous frame. Second, size the drawing canvas
in video pixels and let the page scale it with the video, so a dot at
$(294, 1025)$ in the CSV lands on the knee at any screen size. The full page,
with file pickers and buttons, is in code/b8-overlay/; its test file
checks `frameAt` and the parsed knee of frame 30 and prints “bones drawn
at frame 30: 12 of 12”. Exercise 8.20 gives the
requirements.

## 8.13 Telling the Athlete

Your athlete filmed a set of knee bends after a layoff and the Range of motion
app reports \ang{118} of knee flexion on the left and \ang{126} on the right.
Here are two ways to say it.

> **Coach's translation: A good report.**
> 
> “The video shows your left knee bending to about \ang{118} and your right to
> about \ang{126}. From a phone video, each number could be off by a few
> degrees, so the 8-degree difference is probably real but not exact. Nothing
> here says why, and it is not a medical assessment; if the left knee hurts or
> feels stiff, ask your physical therapist. Let's film the same bends the same
> way, phone in the same spot, in two weeks, and see whether the gap closes.”

The poor version: “Your left knee is at 118.4 degrees, which is 6.3% worse
than your right. That indicates restricted mobility and an increased injury
risk. Do hip and ankle mobility work.” It gives a decimal place the video
cannot support, turns a measurement into a diagnosis and a prediction
(interpretation, the fourth level), and gives advice that does not follow from
the number. The good version states the number, its precision, what it does
not show, one action, and when to check again.

## Summary

- A video is a table of frames. One frame lasts $1/f$, which is the finest
timing the clip can give.

- The stored frame rate is the playback clock; the capture rate is the real
one. Multiply file time by $f_\text{stored}/f_\text{capture}$. All of the
book's example MP4s are stored at 30 fps, whatever they were filmed at.
The apps use the detected rate, fall back to 60 fps, and let you
override it.

- Film square to the movement, still, far back, in good light, with the whole
body in frame and a reference of known length in the plane of the movement.

- A pose model returns 17 keypoints and a confidence each. Confidence screens
out bad frames but does not prove a point is right.

- The apps default to MoveNet Thunder and offer YOLO26 pose (n to x, starting
at s) and BlazePose, all running on the device.

- Scale from a known object, the athlete's stature, or court and pool markings.
Each is true only in its own plane.

- Clean keypoints with a threshold, gap handling, swap correction and smoothing
set in seconds. Draw raw points; check filtered numbers against the picture.

- Four levels of error: landmark, projection, event, interpretation. Three
levels of trust: timing first, in-plane angles next, front-view tilts and
meters last.

| Quantity | Formula |
|---|---|
| Time of frame $k$ ; one frame | $t_k = k/f$ ; $\Delta t = 1/f$ |
| Real time from file time | $t_\text{real} = t_\text{file}\,f_\text{stored}/f_\text{capture}$ |
| Scale | $s = \text{pixels}/\text{meters}$ |
| Included angle at $b$ | $\theta = \arccos\dfrac{\mathbf{u}\cdot\mathbf{v}}{\|\mathbf{u}\|\|\mathbf{v}\|}$ |
| Flexion | $180^\circ - \theta$ |
| Direction error from a point error $e$ on a segment $L$ | $\arctan(e/L)$ |
| Tilt error of two points $w$ apart, each error $\sigma$ | $\sqrt2\,\sigma/w$ (radians) |
| Foreshortening | $L_\text{image} = L\cos\psi$ |

**New terms:** frame, pixel, frame rate, stored frame rate,
capture frame rate, shutter time, pose model, keypoint, confidence, occlusion,
top-down, bottom-up, single-stage, scale, stature, left–right swap, flexion.

**Going further:** https://apmonitor.com/dde/index.php/Main/VideoData reads video frames and turns
a runner's pose into a table; https://apmonitor.com/dde/index.php/Main/ObjectDetection runs YOLO detection on
images, video and a webcam; https://apmonitor.com/dde/index.php/Main/PoseEstimation compares four YOLO
generations on one clip; https://apmonitor.com/pds/index.php/Main/ComputerVisionIntro and
https://apmonitor.com/pds/index.php/Main/VisionDeepLearning cover images in OpenCV and the networks behind the
models. For a history of video motion analysis in sport,
see .

**Track it:** the share of confident pose frames in each `run-form` clip (Appendix J).

## Exercises

> **Course use: Week 8.**
> 
> **H16** (due Class 16, *Measure*): 8.1, 8.2, 8.5, 8.9, 8.18; about 65 minutes.
> 
> **H17** (due Class 17, *Model and tell*): 8.11, 8.20, 8.21, 8.22, 8.23; about 185 minutes. A case-file exercise may be done on your own data instead. The full map is in the Course Guide.

**Exercise 8.1** (Concept check · Foundation · 2 min · CORE)

A phone films a sprint start in slow motion at 240 fps and saves it as a
30 fps file. The file plays for 4.0 s. How long did the
filmed action take in real life?

(a) 32 s
(b) 4.0 s
(c) 0.50 s
(d) 1.0 s

**Exercise 8.2** (Concept check · Foundation · 2 min · CORE)

A pose model returns a confidence of 0.97 for a runner's right ankle. What
does that tell you?

(a) The model rates the point as clearly visible and well placed, but the point may still be on the wrong spot or the wrong leg.
(b) There is a 97% chance that the point is within one pixel of the ankle joint center.
(c) The ankle angle computed from this point is 97% accurate.
(d) The point is certainly on the right ankle, because confidence above 0.9 rules out a left–right swap.

**Exercise 8.3** (Concept check · Foundation · 2 min)

From one side-view phone video of a runner, filmed square at the correct
capture rate, which result belongs to the most trusted level?

(a) Stride length in meters, scaled from the runner's stature.
(b) Pelvic drop in degrees.
(c) Knee angle at foot strike with the camera \ang{30} off square.
(d) Cadence in steps per minute.

**Exercise 8.4** (Concept check · Core · 3 min)

A coach lays a meter stick on the ground to set the scale, but the stick lies
1 m nearer the camera than the athlete's running line. The camera
is 6 m from the running line. The app's stride lengths will be

(a) about 20% too long.
(b) about 17% too short.
(c) unaffected, because the stick is a meter long wherever it lies.
(d) about 17% too long.

**Exercise 8.5** (Hand calculation · Foundation · 8 min · CORE)

A runner's foot is on the ground for 7 frames of a clip filmed and stored at
60 fps.

- What is the contact time? *Checkpoint:* {0.117 s.}

- If each end of the contact can be one frame off, how large is a one-frame error in milliseconds and as a share of the contact time? *Checkpoint:* {16.7 ms, 14%.}

- How many frames would the same contact span at 240 fps, and what share is one frame then? *Checkpoint:* {28 frames; 4.17 ms, 3.6%.}

**Exercise 8.6** (Hand calculation · Core · 10 min)

A jump is filmed in slow motion at 240 fps and stored at
30 fps. The athlete is in the air for 132 frames.

- What flight time does a program that uses the header rate report? *Checkpoint:* {4.40 s.}

- What is the real flight time? *Checkpoint:* {0.550 s.}

- Compute the jump height $h = g t^2/8$ from each, with $g=\SI{9.81}{\metre\per\second\squared}$, and the ratio of the two heights. *Checkpoint:* {23.7 m and 0.371 m; 64.}

- Confirm part (b) in the Jump app by setting the frame rate on one of your own slow-motion clips; state what you changed.

**Exercise 8.7** (Hand calculation · Extension · 12 min)

A swimmer is filmed from a balcony above the pool, the camera looking
straight down at the water. Two neighboring lane lines on the bottom, whose
centers are 2.5 m apart, appear 180 px apart in the frame.

- What is the scale? *Checkpoint:* {72 px/m.}

- The swimmer's head moves 270 px along the lane in 2.0 s of real time. What is the speed? *Checkpoint:* {1.88 m/s.}

- If each lane line is placed 3 px off, in the worst direction, what is the scale error? *Checkpoint:* {3.3%.}

- Name one error source this hand calculation hides that a pool brings and a running track does not, and say which way it biases the speed.

**Exercise 8.8** (Hand calculation · Extension · 12 min)

Two rules set a scale from stature
(Section 8.6): the apps' rule, which takes the
nose-to-ankle span as 0.888 of stature, and the full-stature rule an earlier
version of the Running app used. A 1.70 m athlete's nose-to-ankle
span is 720 px.

- Compute the scale by the apps' rule (span divided by 0.888 of stature) and by the full-stature rule (span divided by stature). *Checkpoint:* {476.9 and 423.5 px/m.}

- A stride spans 600 px. What length does each rule give, and how far apart are they in percent? *Checkpoint:* {1.258 m and 1.417 m; 12.6%.}

- Measure a partner (with their written consent, Appendix E): stature, and the height of the nose and of the ankle bone above the floor. Compute their nose-to-ankle share of stature and the correction factor it implies. How far is it from 0.888, and how much would the apps' lengths be off for them?

**Exercise 8.9** (App lab · Core · 25 min · CORE)

*Your own range of motion.* Use the Range of motion app
(https://apopt.com/rom/), Basic mode, knee protocol, on yourself.

- Set the phone on a tripod at knee height, about 3 m away, square to your side, with your filmed leg nearest the camera. Record 3 slow bends and straightens, holding each end for about a second (about 15 to 20 seconds). Note the capture frame rate your phone used.

- Run the app in Basic mode. Check that the frame rate shown matches what you filmed at. Save the PDF and the text (Markdown) result.

- Pick one number: the largest flexion. Pause the video at that frame, take a screenshot, print it or open it in a drawing tool, and measure the included knee angle with a protractor from hip to knee to ankle. Flexion is 180 minus that angle.

- Switch to Advanced mode. Find one thing Basic left out (for example landmark coverage, the model used, or a compensation measure) and say whether it changes your reading.

- Write half a page: what you measured, what it shows, how sure you are (use the four levels of error), what you would change in the filming, and when you would film again.

**Exercise 8.10** (App lab · Extension · 30 min)

*Default model against YOLO.* Film yourself (side view, whole body, a few
squats or strides, 5 to 10 seconds, note the capture rate) and load the clip
into the canvas app (https://apopt.com/canvas/).

- Analyze with the default model (MoveNet Thunder). Export the CSV. Read `left_knee_angle` at five frames you choose, including the deepest bend.

- Analyze again with YOLO26s, keeping every other setting. Read the same five frames.

- For each frame give the difference. In the frame with the largest difference, look at both overlays: which skeleton sits on the leg?

- State, in two sentences, which model you would use for this movement and why, and what you would record so that a later session is comparable.

**Exercise 8.11** (Python analysis · Foundation · 20 min · CORE)

Run Listing 8.2 on `form3_30fps.mp4` with
`yolo26n-pose.pt`, then with `yolo26s-pose.pt`.

- How many frames have a person for each model? *Checkpoint:* {117 and 115.}

- Using your CSVs, compute the left knee's included angle in every frame for each model (ask your AI assistant for the code, then check one frame by hand against Example 8.5). What are the angles at frame 30? *Checkpoint:* {\ang{90.8} (n) and \ang{89.4} (s).}

- In how many of the frames both models found does the left-knee angle differ by more than \ang{10}? What explains most of them? *Checkpoint:* {65 of 115.}

**Exercise 8.12** (Python analysis · Core · 25 min)

Reproduce Figure 8.4 for `jump1_120fps.mp4`.

- For each of YOLO26n and YOLO26s, count the frames with no person and the frames where the left ankle's confidence is below 0.3. *Checkpoint:* {n: 54 and 1; s: 60 and 4.}

- Replot with the horizontal axis in real seconds, using the capture rate. What is the last tick value? *Checkpoint:* {About 1.23 s.}

- Look at the frames with no person. Describe in one sentence each why the model fails at the start and at the end of the clip.

**Exercise 8.13** (Python analysis · Extension · 40 min)

*Specify, generate, verify.* You will ask an AI assistant for a function
`real_duration(k1, k2, stored_fps, capture_fps)` that returns the real
time between frames `k1` and `k2`.

- Before asking, write the specification and three tests with answers you computed by hand, including the slow-motion case of the byhand box in Section 8.1. *Checkpoint:* {60 frames, stored 30, captured 120 gives 0.50 s.}

- Generate the function, run your tests, and fix it if they fail.

- Extend the comparison in code/compare_sizes.py with a “side-blind” distance, the smaller of the same-side and the opposite-side distance. Reproduce the left-ankle numbers for the sketched runner. *Checkpoint:* {82.3 px same side, 48.2 px side-blind, 30% of frames swapped.}

- Explain to a classmate why the side-blind distance is a better measure of placement error but a worse measure of whether a gait app will work.

**Exercise 8.14** (Body science · Foundation · 5 min)

The pose model's “knee” keypoint is not the knee's center of rotation. Give
two anatomical reasons, and say which kind of measure (an angle in the side
view, or a few-degree tilt in the front view) is hurt more by the difference.

**Exercise 8.15** (Body science · Core · 8 min)

Define the sagittal, frontal and transverse planes of the body in one sentence
each. For each, name one movement in your sport that happens mostly in that
plane, and say where you would put a single camera to film it.

**Exercise 8.16** (Science of the sport · Foundation · 5 min)

Choose a sport you know. Name two markings or objects on its field, court or
pool with a known size that you could use to set a scale, give their size with
a source, and say whether each lies in the plane of the movement you would
film.

**Exercise 8.17** (Science of the sport · Extension · 8 min)

A pitched ball leaves the hand at about 40 m/s. A runner's
step at 180 steps per minute lasts 0.333 s.

- How far does the ball travel between two frames at 30 fps and at 240 fps? *Checkpoint:* {1.33 m and 0.167 m.}

- How many frames does one running step span at 30 fps? *Checkpoint:* {10.}

- Use these to explain why the pitching apps recommend slow motion and the running app does not insist on it.

**Exercise 8.18** (Field collection · Foundation · 30 min · CORE)

*A known angle, square and off square.* Equipment: phone, tripod, printed
protractor (large, at least 15 cm), tape, a partner.

- Consent: your partner gives written consent to be filmed (Appendix E; under 18, a parent or guardian also signs and the partner gives their own assent), knows the clip is for class only, and can stop at any time. Film only the arm.

- Tape the protractor to a wall at elbow height. Your partner stands side-on with the elbow at its center and holds the forearm at \ang{90}, then \ang{120}, then \ang{150} of included angle, each for 3 seconds.

- Film from 2 m, camera square to the wall, at elbow height.

- Move the camera so it looks at the wall \ang{20} off square, at the same distance, and repeat.

- In the canvas app, read `left_elbow_angle` (or right) at each hold. Record the protractor angle, the app angle square, and the app angle \ang{20} off.

Safety: hold only comfortable positions; stop if anything hurts.

**Exercise 8.19** (Field collection · Core · 30 min)

*Scale with distance.* Equipment: phone, tripod, tape measure, a meter stick.

- Fix the phone on a tripod. Mark three distances from the lens along the floor: 2 m, 4 m, 6 m.

- Stand the stick upright, square to the camera, at each distance in turn and take one photo or a short clip.

- In the canvas app (or any image tool), measure the stick's length in pixels at each distance and compute the scale.

- Plot scale against $1/\text{distance}$.

Safety: keep the walkway clear of the tripod legs.

**Exercise 8.20** (Build · Core · 75 min · CORE)

*Build step B-8: play, step and overlay.* Add a page to your app that
loads a video and a keypoint CSV (the output of
Listing 8.2), steps through the video one frame at a time,
and draws the keypoints and skeleton over each frame.

- Put the pure functions in their own module: `frameAt(seconds, fps)`, which returns the frame number at a time; `parseKeypointCsv(text)`, which returns a map from frame number to 17 points and 17 confidences; and `drawPose(ctx, pose, minConf)`, which skips any bone with an end below `minConf`.

- To step, set `video.currentTime` to the *middle* of the next frame, $(k+0.5)/f$, and redraw on the video's `seeked` event. Draw on a canvas laid over the video, sized in video pixels.

- Pass these known-answer tests: frameAt(30.5/30, 30) is 30; `frameAt(1.0, 30)` is 30; the left knee (point 13) of frame 30 in `form3_30fps_yolo26s-pose.csv` rounds to $(294, 1025)$.

- Load the sketched-runner clip and both CSVs and step to frame 30. Take a screenshot of each.

**Exercise 8.21** (Communicate · Foundation · 20 min · CORE)

An athlete's parent, who has signed the consent form (Appendix E), will film a
14-year-old's jump at home and send it to you for the Jump app; the athlete has
given their own assent. Write the text message you would send with the filming
instructions: at most 80 words, no jargon, and including the one setting that
most often goes wrong.

**Exercise 8.22** (Check the AI · Core · 8 min)

An AI assistant was given an app's results file for a runner and wrote: “The
pose model reported a mean keypoint confidence of 0.98, so your stride length
of 1.62 m is accurate to about 2%, roughly 3 cm.” Find the
flaw and rewrite the sentence correctly.

**Exercise 8.23** (Python analysis · Core · 60 min)

Case file: take two running clips of the same athlete from the case files at
apopt.com/data/athletes, one filmed from the side and one from behind. Run
Listing 8.2 on both, then check the model against your
own eyes on five frames of each.

- The clock. Read each clip's stored rate (Listing 8.1)
and find its capture rate in the case-file notes. *Checkpoint:* {The number of
frames the listing reads equals the stored rate times the playback length,
within a frame. If the two rates differ, every time you report is multiplied
by stored over capture, Equation \eqref{ch08-pose:eq:slowmo}.}

- The person. For each clip, report the share of frames with a person and,
for the points you will use (side: hip, knee and ankle of the near leg; back:
both hips and both knees), the share of frames with confidence below 0.3.

- Five frames by hand. Choose five frames spread through each clip,
including at least two hard ones (foot contact, legs crossing). Open each
frame as an image and read the pixel position of the same points by eye. Read
one frame twice, at least an hour apart, to measure your own repeatability.
For each point, compute the distance between your point and the model's, in
pixels and as a share of the hip-to-ankle length in that frame.
*Checkpoint:* {Your two readings of the same frame agree within a few pixels. A
model point closer to yours than your own repeat gap agrees as well as you can
see; report the swaps (model's left on your right) separately from the gaps.}

- Angles. On the side clip, compute the knee's included angle by hand and
by model in the five frames. On the back clip, compute the tilt of the line
through the two hips. Write a function for the tilt error,
$\sqrt2\,\sigma/w$, and test it first. *Checkpoint:* {$\sigma = \SI{5}{\px}$ and
$w = \SI{100}{\px}$ give \ang{4.05}.} Then use your own $\sigma$ (from part
(c)) and the clip's hip width.

**Exercise 8.24** (Communicate · Core · 25 min)

Case file: using the two clips of the previous exercise, write a one-page
“Is this video good enough?” report for the athlete's coach. For each clip,
go through the five checks of Section 8.10; for each
of the four levels of error of Section 8.8, give one
piece of evidence from your analysis or one reason it does not apply; and for
each measure the coach wants (side: cadence and knee angle; back: hip drop),
give its level of trust from Table 8.6. End with three
sentences to the coach: the verdict, the one filming change that would help
most, and what the clips cannot tell them.
