apopt.comCBE 493R Data-Driven Athletics

Course / Tutorials / Week 8 / Q-23

Quick tutorial Q-23 · Week 8 · about 15 min · Foundation

Read a video frame by frame and save every tenth frame

Read a running clip's header, loop over its frames, save every tenth picture on your own computer, and publish a table with one row per frame.

  1. 1Gather (used)
  2. 2Statistics (used)
  3. 3Visualize (used)
  4. 4Cleanse
  5. 5Features
  6. 6Balance
  7. 7Scale
  8. 8Split
  9. 9Deploy
  1. Ask
  2. Collect (this week)
  3. Check (this week)
  4. Interpret
  5. Coach
  6. Reassess

1 of 3 cells run in this page. The rest need a model that does not run in the browser: run them in the notebook on your computer or in Colab (File → Upload notebook); their output from the course build is shown, and the files they write are published so the later cells still run here. Helpful first: Q-22 Detect a person in one image.

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

Try it

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.

Read the clip's header

Runs in the notebook (needs a model that does not run in the browser). Output from the course build:

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()
22 frames at 30 fps = 0.73 s, 1920 x 1080 pixels
one frame lasts 33.3 ms

The frame loop: save every tenth, measure every one

Runs in the notebook (needs a model that does not run in the browser). Output from the course build:

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

PythonWhat changed from frame to frame

Show the expected result without running
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.

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.

Action card

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.
How sure
High; the three saved frames show the background moving.
Action
Film with the phone fixed, and let the runner cross the frame.
Test again
Run the same loop on the next clip; a still camera gives a much smaller change per frame.

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.

Check yourself

  1. A clip has 22 frames, numbered from 0. Which frames does i % 10 == 0 save?

  2. How long is one frame at 30 frames per second?

    ms

0 of 2 answered · 0 right the first time

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 reads this clip the same way before running a pose model on it.

Acknowledgements

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

References

Built 2026-11-30 with Python packages numpy 2.5.5, pandas 3.1.1, matplotlib 3.11.2, cv2 5.1.0. In the browser the same code runs on Pyodide, so the last digit can differ.