# Q-23: Read a video frame by frame and save every tenth frame

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

Web page: https://apopt.com/course/tutorials/q23-video-frames/ · Data: https://apopt.com/data/tutorials/q23-video-frames/

## The decision

Before trusting any number from a clip, check that the clip is what you think it is: how many
frames, at what rate, and whether the camera stayed still. The frame loop answers all three.

## The raw data

- `runner.mp4`: a 22-frame running clip, 1920 × 1080 pixels at 30 frames per second From the Data-Driven Engineering course page [Video Data Analysis](https://apmonitor.com/dde/index.php/Main/VideoData); downloaded from there, not copied here. The saved frames stay in `local/`.

A video is a stack of pictures and a clock (Chapter 8, "A Video Is a Table"). Every analysis
of a clip, by an app or by you, is the same loop: read a frame, do something with it, write
one row, read the next. Here the "something" is small: save every tenth frame as a picture
and measure two numbers from each frame. The clip is the short running clip from the
Data-Driven Engineering course.

The first two cells need OpenCV (`cv2`), so they run in a notebook on your computer or in
Colab. The saved pictures show a person, so they go into `local/`, which stays on your
computer. Only the table is published.

*Predict first:* The clip lasts under a second at 30 frames per second. How many frames, and how many of them are "every tenth" (0, 10, 20, ...)?

```python
import cv2

cap = cv2.VideoCapture("runner.mp4")
fps = cap.get(cv2.CAP_PROP_FPS)
n = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
w, h = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print(f"{n} frames at {fps:.0f} fps = {n / fps:.2f} s, {w} x {h} pixels")
print(f"one frame lasts {1000 / fps:.1f} ms")
cap.release()
```

Output:

```
22 frames at 30 fps = 0.73 s, 1920 x 1080 pixels
one frame lasts 33.3 ms
```

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

os.makedirs("local/frames", exist_ok=True)
os.makedirs("clean", exist_ok=True)
cap = cv2.VideoCapture("runner.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)
    change = np.nan if prev is None else np.abs(gray - prev).mean()   # how much the picture moved
    saved = i % 10 == 0
    if saved:
        cv2.imwrite(f"local/frames/frame_{i:03d}.jpg", frame)
    rows.append([i, round(i / fps, 3), round(gray.mean(), 1), round(change, 2), saved])
    prev, i = gray, i + 1
cap.release()
table = pd.DataFrame(rows, columns=["frame", "t_s", "brightness", "change", "saved"])
table.to_csv("clean/frames.csv", index=False)
print(f"read {i} frames, saved {table['saved'].sum()} to local/frames/")
print(table.to_string(index=False))
```

Output:

```
read 22 frames, saved 3 to local/frames/
 frame   t_s  brightness  change  saved
     0 0.000       125.0     NaN   True
     1 0.033       126.3   34.62  False
     2 0.067       127.9   35.20  False
     3 0.100       129.6   34.68  False
     4 0.133       130.9   32.94  False
     5 0.167       132.4   32.44  False
     6 0.200       133.8   31.91  False
     7 0.233       134.8   30.96  False
     8 0.267       135.6   31.26  False
     9 0.300       136.7   30.61  False
    10 0.333       135.9   29.43   True
    11 0.367       137.0   28.38  False
    12 0.400       137.6   26.73  False
    13 0.433       138.2   26.18  False
    14 0.467       138.5   25.30  False
    15 0.500       139.4   24.71  False
    16 0.533       139.9   23.97  False
    17 0.567       139.8   23.50  False
    18 0.600       140.5   22.72  False
    19 0.633       139.9   22.19  False
    20 0.667       138.5   21.55   True
    21 0.700       139.2   20.37  False
```

Three columns came from the clock and the counter: `frame`, `t_s` (frame divided by the
frame rate) and `saved`. Two came from the pixels: `brightness`, the mean gray level from 0
(black) to 255 (white), and `change`, the mean difference in gray level from the frame
before. Open `local/frames/` on your computer to see the three saved pictures.

### Plot the table

From here on, everything runs in this page, from the published table.

```python
import pandas as pd
import matplotlib.pyplot as plt

t = pd.read_csv("clean/frames.csv")
print(f"{len(t)} rows; time step {t['t_s'].diff().median() * 1000:.1f} ms; saved frames: {t.loc[t['saved'], 'frame'].tolist()}")
print(f"change per frame: median {t['change'].median():.2f}, largest {t['change'].max():.2f} at frame {int(t.loc[t['change'].idxmax(), 'frame'])}")

fig, ax = plt.subplots(figsize=(6.4, 3.2))
ax.plot(t["t_s"], t["change"], "o-", ms=4, label="change from previous frame")
for k, ts in enumerate(t.loc[t["saved"], "t_s"]):
    ax.axvline(ts, color="black", ls="--", lw=1, label="saved frame" if k == 0 else None)
ax.set(xlim=(-0.03, 0.73), xlabel="time (s)", ylabel="mean change (gray levels)")
ax.legend()
plt.tight_layout()
```

Output:

```
22 rows; time step 33.0 ms; saved frames: [0, 10, 20]
change per frame: median 28.38, largest 35.20 at frame 2
```

![Mean change in gray level from the previous frame, plotted against time for the 22 frames, falling from about 35 to 20, with the times of the three saved frames (0, 10 and 20) marked by dashed vertical lines.](https://apopt.com/course/tutorials/q23-video-frames/c04-1.png)

The clock checks out: 22 rows, one every 33 ms, and frames 0, 10 and 20 saved, as you
predicted if you counted from zero. The pixels say something the header does not. The mean
change is about 28 gray levels **every frame** (median 28.38), and it falls slowly through
the clip while the brightness rises. A still camera filming one runner would change only
where the runner is, a small part of the picture. Here nearly every pixel changes, because
the camera turns to follow the runner as he runs away from it, and more sky and snow come
into view. Look at the three saved frames: the stands swing from behind the runner to the
right edge. A moving camera means no fixed scale and no fixed background, which is why
Chapter 8's filming advice starts with a still camera.

**For the athlete:** put the phone on something solid and let the runner cross the frame;
don't follow them with the camera.

## With your own data

Replace `runner.mp4` with your own clip and run the two local cells. Keep the saved frames in
`local/`; publish only `clean/frames.csv`.

## The same method in another field

The same loop reads any camera feed in a plant or lab: count frames, time-stamp them, store
one row per frame. The Data-Driven Engineering page on
[video data](https://apmonitor.com/dde/index.php/Main/VideoData) reads this clip the same way
before running a pose model on it.

## Acknowledgements

The running clip is from the Data-Driven Engineering course.

## Action card

- **Finding:** The clip is 22 frames (0.73 s) at 30 frames per second, filmed with a camera that turns to follow the runner.
- **Evidence:** The mean picture change is about 28 gray levels every frame, falling from 35 to 20 as the camera swings.
- **Sure:** High; the three saved frames show the background moving.
- **Action:** Film with the phone fixed, and let the runner cross the frame.
- **Retest:** Run the same loop on the next clip; a still camera gives a much smaller change per frame.

## References

- Data-Driven Engineering: [Video Data Analysis](https://apmonitor.com/dde/index.php/Main/VideoData).

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