# Q-2: Step through a video one frame at a time

Data-Driven Athletics tutorial · Week 1 · Chapter 1 · about 15 min · workflow steps: Gather, Statistics, Visualize

Web page: https://apopt.com/course/tutorials/q02-frame-step/ · Data: https://apopt.com/data/tutorials/q02-frame-step/

## The decision

You are about to time a jump by counting frames. Before counting, decide which clock turns a
frame number into seconds, and whether every frame in the file is a distinct moment.

## The raw data

- `clean/frame_table.csv`: one row per frame of the course's example jump clip (190 rows) with the frame number, its time on the file's clock and on the 120 fps capture clock, mean brightness, and the difference from the previous frame; no pixels Written by the first two cells from `jump2_120fps.mp4`, the course's example jump (Chapter 1). The clip shows a person and is not published; run those cells on a clip of your own.

### A video is a stack of pictures and a clock

To time a jump from video you step through it one frame at a time and note the frame numbers
where something happens. The frame number becomes a time only when you divide it by a frame
rate, and a phone clip carries two of them: the rate the camera **recorded** at and the rate
the file **stores** (Section 1.3.2, and Chapter 8). The clip here is the course's example jump,
named `jump2_120fps.mp4` because it was filmed in slow motion at 120 frames per second.

The first two cells run on your own computer or in Colab (they need OpenCV), because they read
the video. They write a table with one row per frame and no pictures in it; from the third cell
on, everything runs in this page from that table.

*Predict first:* The file name says 120 frames per second. What rate will the file's header report?

```python
import cv2

cap = cv2.VideoCapture("local/jump2_120fps.mp4")
fps_file = 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, header says {fps_file:.2f} fps, {w} x {h} pixels")
print(f"playback length {n / fps_file:.2f} s; at the 120 fps capture rate {n / 120:.2f} s")
cap.release()
```

Output:

```
190 frames, header says 30.00 fps, 1080 x 1920 pixels
playback length 6.33 s; at the 120 fps capture rate 1.58 s
```

The header says 30, not 120. The phone stored four times fewer frames per second than it
recorded, so the clip plays four times slower than life. Played back it lasts 6.33 s; the real
jump took 1.58 s.

### Step through every frame and write a table

The loop reads one frame at a time. For each it writes the frame number, its time on both
clocks, its mean brightness, and how much it differs from the frame before (the mean absolute
difference of the gray values, 0 to 255). A difference near zero means the frame repeats the
one before it. The cell also saves frames 78 to 84 as pictures under `local/` so you can look at
them one by one on your computer; they are never published.

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

os.makedirs("clean", exist_ok=True)
os.makedirs("local/frames", exist_ok=True)
cap = cv2.VideoCapture("local/jump2_120fps.mp4")
rows, prev, i = [], None, 0
while True:
    ok, frame = cap.read()
    if not ok:
        break
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY).astype(float)
    diff = np.nan if prev is None else np.abs(gray - prev).mean()
    rows.append([i, i / fps_file, i / 120, gray.mean(), diff])
    if 78 <= i <= 84:
        cv2.imwrite(f"local/frames/frame_{i:03d}.jpg", frame)   # for your eyes only
    prev, i = gray, i + 1
cap.release()
table = pd.DataFrame(rows, columns=["frame", "t_file_s", "t_capture_s", "mean_gray", "diff_prev"])
table.round({"t_file_s": 6, "t_capture_s": 6, "mean_gray": 2, "diff_prev": 3}).to_csv("clean/frame_table.csv", index=False)
print(f"{len(table)} rows written to clean/frame_table.csv")
```

Output:

```
190 rows written to clean/frame_table.csv
```

### Step through the table

From here on the cells run in this page. Print the rows around frame 80, where the book's hand
count found the feet leaving the ground (Section 1.3, Example "A hand count on the course's
example clip").

*Predict first:* Two neighboring frames are how many milliseconds apart in real time?

```python
import pandas as pd

table = pd.read_csv("clean/frame_table.csv")
print(table[(table["frame"] >= 78) & (table["frame"] <= 84)].to_string(index=False))
step_ms = 1000 * (table["t_capture_s"].iloc[1] - table["t_capture_s"].iloc[0])
print(f"one frame = {step_ms:.1f} ms of real time; frames 80 to 124 = {(124 - 80) * step_ms / 1000:.3f} s")
```

Output:

```
 frame  t_file_s  t_capture_s  mean_gray  diff_prev
    78  2.600000     0.650000     107.19      4.092
    79  2.633333     0.658333     107.18      0.051
    80  2.666667     0.666667     106.79      4.034
    81  2.700000     0.675000     106.52      3.972
    82  2.733333     0.683333     106.18      3.796
    83  2.766667     0.691667     105.90      3.576
    84  2.800000     0.700000     105.58      3.317
one frame = 8.3 ms of real time; frames 80 to 124 = 0.367 s
```

One frame is 8.3 ms of real time, so the 44 frames from takeoff at frame 80 to landing at frame
124 are 0.367 s, the flight time the jump app also reports. Divided by the header's 30 the same
44 frames would be 1.467 s, four times too long.

Look at the `diff_prev` column: frame 79 differs from frame 78 by almost nothing. Plot the
difference for the whole clip to see whether that is chance.

*Predict first:* How many of the 190 frames do you expect to be exact repeats of the frame before?

```python
import matplotlib.pyplot as plt

repeat = table["diff_prev"] < 0.5
print(f"{int(repeat.sum())} repeated frames, at frames {table.loc[repeat, 'frame'].tolist()[:6]} ...")
print("gaps between repeats:", sorted(set(table.loc[repeat, "frame"].diff().dropna().astype(int))))
fig, ax = plt.subplots(figsize=(8, 3.4))
ax.plot(table["frame"], table["diff_prev"], "-", color="0.5", lw=1, label="every frame")
ax.plot(table.loc[repeat, "frame"], table.loc[repeat, "diff_prev"], "kx", ms=6, label="repeat (< 0.5)")
ax.set(xlabel="frame number", ylabel="difference from previous frame (gray levels)")
ax.legend()
plt.tight_layout()
```

Output:

```
32 repeated frames, at frames [1, 7, 13, 19, 25, 31] ...
gaps between repeats: [6]
```

![Mean gray-level difference from the previous frame against frame number, 0 to 189. The difference peaks near frame 76 (the drive up) and frame 134 (the landing) and sags between them; every sixth frame, marked with a cross, drops to near zero.](https://apopt.com/course/tutorials/q02-frame-step/c07-1.png)

Thirty-two frames, exactly every sixth one, repeat the frame before. The camera did not do
that by chance: the file was made from the recording in a way that duplicated frames. It
matters for timing. If the camera recorded 120 distinct frames a second, then six file frames
hold only five distinct moments, and counting file frames at 8.3 ms each can overstate a
duration by up to a fifth (Chapter 8 returns to this). The difference also traces the jump: it
peaks near frame 76, the drive up, and near frame 134, the landing, and sags in between, near
the top of the flight where the body moves slowest. The jump is visible in the table without
looking at a single picture.

**For the athlete:** "I timed your jump frame by frame from the slow-motion clip; for the next
test, film at a normal-speed setting of 60 frames per second or more so each frame is one
moment and the clock is the one the camera used."

## With your own data

Film one jump of yours with the phone's slow-motion setting and one at normal speed, run the two
local cells on each, and compare the header rate with the rate you chose on the phone. Keep the
clips and the saved frames in `local/`; share only the table.

## Action card

- **Finding:** The clip was recorded at 120 frames per second but stored at 30, and every sixth frame repeats the one before it.
- **Evidence:** The header reports 30.00; 32 of 190 frames differ from the previous one by under 0.5 gray levels, exactly six frames apart.
- **Sure:** High for both facts; how the repeats change the true flight time is not settled by this table.
- **Action:** Divide frame counts by the capture rate, and film test jumps at a normal-speed setting so frames are not duplicated.
- **Retest:** Check the header and the repeats on every new clip before counting.

## References

- *Data-Driven Athletics*, Chapter 1, A First Measurement (Section 1.3), and Chapter 8, A Video Is a Table (Section 8.1).

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