TExcelTAD

Preparing Video Data

A video is a stack of images in time: an array of shape (frames, height, width, channels) plus a frame rate. One minute at 30 frames per second and 1080p is 1,800 images and about 11 GB as raw uint8 pixels, so nobody trains on every frame. Preparing video means decoding frames the same way every time, choosing which frames to keep, resizing them, keeping each frame's timestamp and the identity of the video it came from, converting annotations from seconds to frames, and, above all, splitting by whole videos, because neighbouring frames are near-duplicates. The image steps (channels, resizing, normalisation) are the same as in Preparing Image Data; this lesson adds the time dimension.

frame sampling: keep 1 frame in 6 (30 fps to 5 fps) 0.0 s0.2 s0.4 s0.6 s video Akept: green split by whole video train: all frames of videos A, B, C test: all frames of D never: frames 1, 3, 5 of A in train and frames 2, 4, 6 of A in test

Decode, sample, resize, and keep the bookkeeping

Decoding must give the same frames every time: use one decoder library and version for training and inference, read the true frame rate from the container (it is not always 30, and variable frame rates exist), and convert colour once (OpenCV again gives BGR). Then pick frames. Two common schemes:

Scheme How Good for
fixed rate keep every k-th frame (30 fps to 5 fps: k = 6) detection and tracking, long videos, timestamps stay regular
fixed count N frames evenly spread over the clip (e.g. 8 or 16) action recognition models with a fixed input of N frames

Each kept frame carries its video id, its frame index and its timestamp = index / fps. Annotations given in seconds (an action from 1.2 s to 2.0 s) are converted to frame indices with the same rule. In the example, a synthetic 4-second clip at 30 fps stands in for a decoded video (codecs are not available in the browser, and decoding a file gives exactly this kind of array):

python · try it yourself
import numpy as np
import cv2

fps, seconds, H, W = 30, 4, 120, 160
n = fps * seconds
video = np.full((n, H, W, 3), 40, dtype=np.uint8)
for i in range(n):                                    # a square moving right
    x = 10 + i
    video[i, 50:70, x:x + 20] = (0, 200, 255)
print("decoded video:", video.shape, "=", round(video.nbytes / 1e6, 1), "MB as uint8")

k = 6                                                 # 30 fps -> 5 fps
idx_rate = np.arange(0, n, k)
idx_count = np.linspace(0, n - 1, 8).round().astype(int)
print("fixed rate:", len(idx_rate), "frames, first indices", idx_rate[:5].tolist())
print("fixed count:", idx_count.tolist())

frames = np.stack([cv2.resize(video[i], (80, 60), interpolation=cv2.INTER_AREA) for i in idx_rate])
meta = [{"video": "clip_007", "frame": int(i), "t": round(int(i) / fps, 3)} for i in idx_rate[:3]]
print("kept:", frames.shape, "| metadata:", meta)

action = (1.2, 2.0)                                   # "square crosses the centre", in seconds
first, last = int(np.ceil(action[0] * fps)), int(np.floor(action[1] * fps))
kept_in_action = idx_rate[(idx_rate >= first) & (idx_rate <= last)]
print("action frames", first, "-", last, "| kept frames inside:", kept_in_action.tolist())

diff = np.abs(np.diff(video.astype(int), axis=0)).mean(axis=(1, 2, 3))
print("mean pixel change between consecutive frames:", round(float(diff.mean()), 3), "of 255")
decoded video: (120, 120, 160, 3) = 6.9 MB as uint8
fixed rate: 20 frames, first indices [0, 6, 12, 18, 24]
fixed count: [0, 17, 34, 51, 68, 85, 102, 119]
kept: (20, 60, 80, 3) | metadata: [{'video': 'clip_007', 'frame': 0, 't': 0.0}, {'video': 'clip_007', 'frame': 6, 't': 0.2}, {'video': 'clip_007', 'frame': 12, 't': 0.4}]
action frames 36 - 60 | kept frames inside: [36, 42, 48, 54, 60]
mean pixel change between consecutive frames: 0.288 of 255

The 4-second clip is already 6.9 MB at a small 160 x 120 resolution. Keeping every 6th frame leaves 20 frames (indices 0, 6, 12, …); a fixed count of 8 spreads them from frame 0 to frame 119. After resizing to 80 x 60, each kept frame has its video id, index and timestamp (frame 6 is at 0.2 s). The action from 1.2 s to 2.0 s covers frames 36 to 60, and five kept frames fall inside it. The last line explains why sampling loses little: on average a pixel changes by only 0.288 of 255 from one frame to the next.

Annotations over time

Video labels come in three shapes: one label per video (a clip shows "cooking"), labelled segments (start and end time of each action) and per-frame boxes or masks with a track id that links the same object across frames. Store them in seconds or with the frame rate next to them, never as bare frame numbers without the fps: if the video is later re-encoded at another rate, frame 300 is no longer at 10 s. Annotating every frame is expensive, so teams annotate keyframes and interpolate the boxes in between, then review. Formats and tools are covered in Ground Truth, Annotations, Classes and Metadata.

Split by video, not by frame

Two frames 33 ms apart are almost the same image. Put one in training and the other in test, and a model can score well by recognising the scene instead of learning the task. The example below is designed to expose that: 20 videos, each filmed in its own scene (a random background), with a label that is random per video, so there is nothing real to learn.

python · try it yourself
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import KFold, GroupKFold, cross_val_score

rng = np.random.default_rng(0)
n_videos, frames_per_video = 20, 15
X, y, groups = [], [], []
for v in range(n_videos):
    scene = rng.integers(0, 256, (12, 16)).astype(float)      # this video's background
    label = int(rng.integers(0, 2))                            # random per video
    for f in range(frames_per_video):
        frame = scene + rng.normal(0, 8, scene.shape)          # camera noise
        frame[4:8, f:f + 3] = 255                              # an object moving across
        X.append(frame.ravel()); y.append(label); groups.append(v)
X, y, groups = np.array(X), np.array(y), np.array(groups)

knn = KNeighborsClassifier(n_neighbors=1)
by_frame = cross_val_score(knn, X, y, cv=KFold(5, shuffle=True, random_state=0)).mean()
by_video = cross_val_score(knn, X, y, cv=GroupKFold(5), groups=groups).mean()
print(f"frames: {len(X)} from {n_videos} videos")
print(f"random split of frames: {by_frame:.3f}")
print(f"split by whole video:   {by_video:.3f}")
frames: 300 from 20 videos
random split of frames: 1.000
split by whole video:   0.380

Splitting frames at random gives a perfect 1.000 with a 1-nearest-neighbour classifier, on labels that are random. Every test frame has a near-twin from the same video in the training folds, and the twin carries the video's label. Split by video, the score falls to 0.380, around chance (the exact value moves with so few videos), which is the truth: nothing about the label can be learned here.

The same applies one level up: clips cut from one long recording, videos from one recording session, one camera, one place or one person belong to one group. Choose the group by what the deployed model will meet that is new: new cameras means grouping by camera (Split Strategies, The Leakage Rules).

Pitfalls

  • Assuming 30 fps: read the frame rate from each file; mixed rates distort time-based features and labels.
  • Annotations as bare frame numbers: keep seconds or the fps with them.
  • Random frame-level splits: split by video, session, camera or person.
  • Decoding differences between training and serving: a different decoder can give slightly different frames and colours; use the same one.
  • Keeping every frame: costs storage and adds almost no new information; sample.

Practice

  1. A 2-minute video at 25 fps is sampled at 2 frames per second. Which frame step do you use, and how many frames do you keep? At which timestamp is the 10th kept frame?
Answer

Step 25 / 2 = 12.5 frames, which is not a whole number: either sample by time (frame index = round(t * 25) for t = 0, 0.5, 1.0, …) or accept a step of 12 or 13. Sampling by time gives 2 * 120 = 240 frames; the 10th kept frame (counting from the first at 0 s) is at 4.5 s, frame index round(4.5 * 25) = 112 (Python rounds 112.5 to the even 112).

  1. A dataset has 300 videos from 12 traffic cameras. The model will be installed at new intersections. How do you split?
Answer

By camera, not just by video: GroupKFold with groups=camera_id, so each test fold contains only cameras the model has never seen, which matches new intersections.

Test yourself

Why must frames of one video stay on one side of the split?

  1. Videos are too large
  2. Neighbouring frames are near-duplicates, so the model can recognise the scene instead of learning the task
  3. Frames have different sizes
  4. GroupKFold is faster

A video runs at 30 fps. Which frame index is the moment 2.5 s?

  1. 25
  2. 30
  3. 75
  4. 250

An action-recognition model takes exactly 16 frames per clip. Which sampling scheme fits?

  1. Keep every frame
  2. A fixed count: 16 frames spread evenly over the clip
  3. Keep only the first 16 frames
  4. Random frames from other videos