Level 3 In-Depth AI · Vision, Audio and Multimodal
Video Understanding
A video is a stack of images through time, and understanding it means understanding motion as well as appearance. This chapter covers frame sampling, two-stream networks, 3-D convolutions, video Transformers and the action-recognition task that drove them.
- Level
- ●●●●● Intermediate
- Reading
- 12 min
- To learn it well
- 1 hour to read, an hour to practise
- Builds on
- 33 concepts →
- Quiz
- 5 questions ↓
Read first
Vision TransformersThis leads to
—The full path from zero — 33 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Tensors and Shapes
- Supervised Learning
- Images as Data
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Convolutional Neural Networks
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- Image Classification
- LSTMs and GRUs
- Residual Connections
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- Vision Transformers
- Video Understanding
Read them roughly in this order. See it on the concept map →
Why it matters
Hundreds of hours of video are uploaded to YouTube every minute. Add security cameras, dashcams, body cameras, sports broadcasts, surgical recordings, video calls and factory monitoring, and video is probably the largest kind of data humans produce. Understanding it automatically powers content moderation and recommendation, sports analytics (tracking every player and the ball), driver assistance, robotics (learning from demonstrations), searching hours of footage for one event, and video question answering in multimodal assistants.
Video is also where the vision ideas from earlier chapters meet their hardest test. Some questions can be answered from a single frame ("is there a dog?"). Many cannot: "is the door opening or closing?", "did the player shoot or pass?", "is this person falling or sitting down?". The answer lies in how things change over time, and models need to capture that motion without drowning in the sheer quantity of pixels.
The intuition
A video is a flip-book: a sequence of still images (frames) shown quickly, usually 24 to 60 per second. Each frame is an image tensor (Images as Data). Stack them and a video becomes a 4-D tensor: time × channels × height × width.
Two kinds of information are mixed in it:
- Appearance: what things look like in each frame (a ball, grass, a person in a red shirt).
- Motion: how they move from frame to frame (the ball flying left, the arm swinging).
A single frame captures appearance. Motion only exists between frames. The history of video models is a series of answers to the question "how do we capture motion?": compare frames explicitly, give filters a time dimension, or let attention look across time.
Key idea Video = images + time. Appearance comes from single frames, and motion from comparing frames. Video models capture motion with optical flow (two-stream networks), with filters that span several frames (3-D CNNs), or with attention across time (video Transformers), while fighting the huge cost of processing so many pixels.
How it works
The size problem and frame sampling
Ten seconds of video at 30 frames per second (the frame rate), 224 × 224 pixels in colour, is million numbers, 300 times a single image. And neighbouring frames are nearly identical. Almost every video model therefore starts with frame sampling: pick a subset of frames.
- Dense clip sampling: take, say, 16 consecutive frames, or 16 frames taken every 2nd or 4th frame, as one short clip. This preserves fine motion.
- Sparse or segment sampling: split the whole video into equal segments and take one frame from each (Temporal Segment Networks, 2016). This covers long videos cheaply.
- At test time, average predictions over several clips spread across the video.
Decoding compressed video (H.264, H.265) is itself expensive. Data loading is often the bottleneck in video training.
Approach 1: frames through a 2-D CNN
The simplest approach runs an image classifier on each sampled frame and averages the predictions, or feeds per-frame features to an RNN or LSTM. A 2014 study by Karpathy and colleagues on a million sports videos found that single-frame models were surprisingly close to multi-frame ones. Many actions are recognisable from appearance alone: a swimming pool means swimming. This approach fails on actions defined by motion or direction, and the order of frames is lost the moment you average.
Approach 2: two-stream networks and optical flow
Optical flow is a per-pixel estimate of motion between two frames: for every pixel, a small arrow saying how far it moved horizontally and vertically. Simonyan and Zisserman's two-stream network (2014) used two CNNs: a spatial stream on single RGB frames (appearance) and a temporal stream on stacks of optical-flow fields (motion). The two streams' predictions are averaged. It worked well, but computing optical flow is slow and separate from training.
Approach 3: 3-D convolutions
A 2-D convolution slides a filter over height and width. A 3-D convolution adds time: a filter slides over time, height and width. A filter looks at a 3 × 3 pixel patch in three consecutive frames, so it can learn motion detectors directly from pixels, such as "edge moving right". The output at time , row , column is
with running over the filter's frames and , over its rows and columns (here are the filter weights and the lone after the sum is the bias). It is exactly the 2-D formula with one more index.
- C3D (2015) stacked convolutions, a VGG for video.
- I3D (2017) "inflated" a pretrained 2-D ImageNet network into 3-D by repeating each 2-D filter along time, so 3-D networks could start from image knowledge. It was trained on the new Kinetics dataset (400 human action classes, about 240,000 ten-second YouTube clips).
- SlowFast (2019) ran a slow pathway at a low frame rate with many channels (appearance) beside a fast pathway at a high frame rate with few channels (motion).
The cost is the catch. A filter has three times the weights and arithmetic of a one at every layer. Many designs factorise it into a spatial convolution followed by a temporal one ("(2+1)-D" convolution).
Approach 4: video Transformers
Vision Transformers extend naturally to video. Cut the clip into space-time patches called tubelets (for example 2 frames × 16 × 16 pixels), embed each one as a token, add position embeddings for space and time, and run a Transformer.
Worked example of cost. An 8-frame clip at 224 × 224 with 16 × 16 patches gives tokens. Full attention compares every token with every other: about million pairs per head per layer, 64 times more than for one frame's 196 tokens. Divided space-time attention (TimeSformer, 2021) splits each block into two steps. First each patch attends only to the same position in the other 7 frames (time), then only to the 196 patches of its own frame (space). That is about pairs, roughly 8 times fewer, and it worked better in their experiments too.
Video Transformers are data-hungry, like their image cousins. VideoMAE (2022) pretrains them without labels by hiding 90% or more of the tubelets and reconstructing them. Because neighbouring frames are so redundant, video needs an even higher masking ratio than images to make the task hard.
Tasks and datasets
- Action recognition: one label per clip ("playing guitar", "push-up"). Benchmarks include UCF101 (2012, 13,320 clips, 101 classes), Kinetics-400/600/700, and Something-Something v2, whose 174 classes ("pushing something from left to right", "pretending to put something on a surface") deliberately require temporal reasoning: a single frame is useless there.
- Temporal action localisation: find when each action starts and ends in a long, untrimmed video.
- Object tracking: follow objects across frames, by linking per-frame detections or with SAM 2's video memory (Image Segmentation).
- Video–text tasks: captioning, retrieval ("find the clip where the goal is scored") and question answering. Contrastive video–text models extend CLIP and Contrastive Learning. Multimodal LLMs sample frames, encode each as image tokens and reason over them. Google reported in 2024 that Gemini 1.5 could take in about an hour of video within its long context window.
In code
An experiment that shows why motion needs time-aware models. The synthetic clips show a bright square moving left (label 0) or right (label 1). A per-frame 2-D CNN that averages over frames cannot tell the direction. A tiny 3-D CNN can. It runs in about 15 seconds on a CPU.
import torch
import torch.nn as nn
import torch.nn.functional as F
def make_clips(n, T=8, S=16):
"""Clips of a bright square moving left (label 0) or right (label 1), plus noise."""
labels = torch.randint(0, 2, (n,))
video = 0.2 * torch.randn(n, 1, T, S, S) # (N, C, T, H, W)
for i in range(n):
y = torch.randint(2, S - 5, (1,)).item()
x0 = torch.randint(4, S - 7, (1,)).item()
step = 1 if labels[i] == 1 else -1
for t in range(T):
x = min(max(x0 + step * (t - T // 2) // 2, 0), S - 3)
video[i, 0, t, y:y + 3, x:x + 3] += 1.0
return video, labels
class FrameAverage(nn.Module): # 2-D CNN on each frame, then average over time
def __init__(self):
super().__init__()
self.conv = nn.Conv2d(1, 16, 3, padding=1)
self.fc = nn.Linear(16, 2)
def forward(self, v): # v: (N, 1, T, H, W)
N, C, T, H, W = v.shape
frames = v.transpose(1, 2).reshape(N * T, C, H, W)
f = F.relu(self.conv(frames)).mean(dim=(2, 3)) # (N*T, 16)
return self.fc(f.view(N, T, 16).mean(dim=1)) # order of frames is lost
class Conv3D(nn.Module): # 3-D convolution: filters span time as well as space
def __init__(self):
super().__init__()
self.conv = nn.Conv3d(1, 16, kernel_size=3, padding=1) # 3 frames x 3 x 3 pixels
self.fc = nn.Linear(16, 2)
def forward(self, v):
return self.fc(F.relu(self.conv(v)).mean(dim=(2, 3, 4)))
torch.manual_seed(0)
X_test, y_test = make_clips(500)
for Model in [FrameAverage, Conv3D]:
model = Model()
opt = torch.optim.Adam(model.parameters(), lr=1e-2)
for step in range(300):
X, y = make_clips(64)
loss = F.cross_entropy(model(X), y)
opt.zero_grad(); loss.backward(); opt.step()
with torch.no_grad():
acc = (model(X_test).argmax(1) == y_test).float().mean()
print(f"{Model.__name__:12s} test accuracy {acc:.3f}")
# FrameAverage test accuracy 0.524
# Conv3D test accuracy 1.000
The frame-averaging model is at chance (50%), because a set of frames without their order contains no information about direction. The 3-D convolution solves the task perfectly.
A pretrained video Transformer (VideoMAE fine-tuned on Kinetics-400) through Hugging Face. It needs a video-decoding package such as av, and clip.mp4 is any short video:
from transformers import pipeline
clf = pipeline("video-classification", model="MCG-NJU/videomae-base-finetuned-kinetics")
for pred in clf("clip.mp4")[:3]:
print(f"{pred['label']:30s} {pred['score']:.3f}")
Common pitfalls
- Static bias. Many benchmarks can be solved largely from scenery and objects (a pool means swimming), so a high score may not mean the model understands motion. Test on motion-centric data such as Something-Something, or shuffle the frames and see whether accuracy drops. If it doesn't, your model ignores time.
- Sampling that misses the action. A 2-second clip sampled from a 2-minute video may not contain the event at all. Use several clips, or segment sampling, at test time.
- Frame-rate mismatches. A model trained on clips sampled every 4th frame at 30 fps sees motion at a different speed if fed 60 fps video sampled the same way. Match the temporal stride to training.
- Data-loading bottlenecks. Decoding video on the fly can starve the GPU. Pre-extract frames at the needed rate and resolution, or use fast decoders and several loader workers.
- Leakage between splits. Clips cut from the same original video, or the same person in the same room, must stay on one side of the train/test split (Training, Validation and Test Sets).
- Memory. Activations scale with frames × pixels. Reduce clip length or resolution, use mixed precision (Mixed Precision Training) and gradient checkpointing.
Watch out Video of people raises serious privacy and surveillance concerns, and action- or emotion-recognition models carry the biases of their training data. Inferring intent, emotion or "suspicious behaviour" from video is far less reliable than marketing suggests. Treat such outputs as weak signals, and know the law where you deploy (see AI Regulation and Governance and Bias and Fairness).
Where it leads
- Multimodal LLMs increasingly take video directly, sampling frames into image tokens.
- SAM 2 tracks and segments objects through video with a memory of earlier frames.
- Video Generation runs the process in reverse, using diffusion Transformers over space-time patches.
- Self-Supervised Learning methods such as VideoMAE learn from unlabelled video, the most plentiful data there is.
- Audio is often the forgotten half of a video. Audio-visual models use both.
A bit of history
Early action recognition (2000s) used hand-designed space-time features: "space-time interest points" and dense trajectories, which tracked points through the video and described their motion. UCF101 (2012) and HMDB-51 (2011) were the benchmarks. Deep learning arrived with Karpathy and colleagues' Sports-1M study and Simonyan and Zisserman's two-stream network (both 2014), then C3D (2015). DeepMind's Kinetics dataset and I3D (2017) did for video roughly what ImageNet and AlexNet had done for images, making large-scale pretraining standard.
SlowFast (2019) refined 3-D CNNs. In 2021 TimeSformer, ViViT and similar models brought Transformers to video, and VideoMAE (2022) showed how to pretrain them without labels. Since 2023 the field has merged with language: contrastive video–text models, video question answering, and multimodal LLMs that reason over long videos, while diffusion models learned to generate video itself.
Try it
- Compute the number of attention pairs per head per layer for a 16-frame clip at 224 × 224 with 16 × 16 patches, with full and with divided space-time attention.
- In the code, shuffle the frames of each test clip (
X_test[:, :, torch.randperm(8)]) and re-evaluate the 3-D CNN. What happens, and why?- Harder: add a third class, a square that stays still, and retrain both models. Which classes can the frame-averaging model now tell apart?
Hint for 1: tokens. Full attention gives about 9.8 million pairs, and divided attention gives .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Two-Stream Convolutional Networks for Action Recognition in Videos
Recognises actions with two CNNs, one on still frames for appearance and one on optical flow for motion, then fuses their predictions.
Quo Vadis, Action Recognition? A New Model and the Kinetics Dataset
Introduces I3D, which "inflates" ImageNet-pretrained 2-D filters into 3-D ones, and shows the value of pretraining on the large Kinetics dataset.
Is Space-Time Attention All You Need for Video Understanding?
TimeSformer, a convolution-free video Transformer. Its "divided" attention, first across time and then across space, keeps the cost manageable.
ViViT: A Video Vision Transformer
Studies ways to apply vision Transformers to video, including tubelet embeddings and factorised space-time encoders.
VideoMAE: Masked Autoencoders are Data-Efficient Learners for Self-Supervised Video Pre-Training
Pretrains video Transformers by hiding 90% or more of the space-time patches and reconstructing them, which works well even on small video datasets.
Stanford CS231n: Deep Learning for Computer Vision
Famous course notes on neural nets, backprop, CNNs and training, written very clearly.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/vision/video-understanding.md