Sub topic 1
What a video is: frames, frame rate and codecs
A video file looks like a single object, but your code never works with it that way. OpenCV decodes the file and hands you one still image at a time. This chapter builds the model behind that: what is stored in the file, what the decoder produces, and which numbers describe the result. The later chapters on reading, processing and writing depend on this model.
Prerequisites
This chapter assumes you have:
- Basic Python: functions, loops, f-strings, and the idea of
try/finally. - Basic NumPy: array shapes,
dtype, and indexing. - The
opencv-pythonpackage installed (pip install opencv-python). - A short video file named
input.mp4in your working directory, for the one script that opens a file.
You do not need to know how compression works. The chapter covers what you need.
A video is an ordered list of images
A video is a sequence of still images called frames, shown one after another quickly enough that the eye sees motion. Each frame has the same width and height. The frame rate is the number of frames shown per second, measured in frames per second (fps).
Common frame rates:
| Frame rate | Typical use |
|---|---|
| 24 fps | Film |
| 25 fps | PAL television |
| 30000/1001 fps (about 29.97) | NTSC television and many phone and web videos |
| 30 or 60 fps | Screen recordings, webcams, games |
| 120 fps and above | Slow motion, high-speed cameras |
Two consequences matter for code:
- The time between frames is
1 / fps. At 30 fps that is about 33.3 ms. This is your per-frame time budget if you want to process a live stream without falling behind. - A frame has an index (0, 1, 2, ...) and a timestamp (
index / fpsfor constant-rate video). OpenCV can report both, and they are not always interchangeable.
What is actually stored: raw versus compressed
Consider the storage cost if a file held every pixel of every frame. A 1920x1080 frame with three 8-bit channels takes 1920 x 1080 x 3 = 6,220,800 bytes, about 5.9 MiB. At 30 fps that is about 187 MB every second, or about 670 GB per hour. Real files are hundreds of times smaller, so they must be compressed.
width, height, channels, fps = 1920, 1080, 3, 30
bytes_per_frame = width * height * channels
bytes_per_second = bytes_per_frame * fps
bytes_per_hour = bytes_per_second * 3600
print(f"one frame: {bytes_per_frame:,} bytes ({bytes_per_frame / 2**20:.1f} MiB)")
print(f"one second: {bytes_per_second / 1e6:.0f} MB")
print(f"one hour: {bytes_per_hour / 1e9:.0f} GB")The script prints about 6.2 million bytes per frame (5.9 MiB), 187 MB per second, and 672 GB per hour. A typical H.264 file of the same footage runs at roughly 5 to 10 Mbit/s, which is about 2 to 4 GB per hour.
Codecs: how the compression works
A codec (coder-decoder) is the algorithm that compresses frames when a file is written and decompresses them when it is read. Common video codecs include H.264 (AVC), H.265 (HEVC), VP9, AV1 and MPEG-4 Part 2 (the codec behind the mp4v code you will use later). Motion JPEG (MJPG) is simpler: it compresses each frame independently as a JPEG.
Most codecs get their savings from two ideas:
- Spatial compression shrinks each frame by removing detail the eye barely notices, as JPEG does for photos.
- Temporal compression exploits the fact that consecutive frames are usually almost identical. Instead of storing each frame fully, the codec stores a few complete frames and describes the others as changes from their neighbors.
This produces three kinds of frames inside a compressed stream:
| Type | Name | What it stores |
|---|---|---|
| I-frame | Intra-coded, or keyframe | A complete image that needs no other frame to decode |
| P-frame | Predicted | Differences from earlier frames |
| B-frame | Bidirectional | Differences from both earlier and later frames |
A run of frames that starts with a keyframe is called a group of pictures (GOP). Keyframes may appear every second or two, or much less often.
This structure explains behavior you will meet later:
- To show frame 100, the decoder may first need to decode the nearest earlier keyframe and every dependent frame in between. This is why seeking in a file can be slow or slightly inaccurate.
- B-frames mean frames are stored in a different order from the order they are shown. The decoder reorders them, so the frames OpenCV returns are always in display order.
- Intra-only formats such as MJPG are larger on disk but are easy to seek in and fast to decode.
Containers: the file around the streams
A container (or wrapper format) is the file format that packages the compressed video stream with audio, subtitles, timestamps and metadata. The file extension usually names the container, not the codec.
| Container | Extension | Commonly holds |
|---|---|---|
| MP4 | `.mp4` | H.264, H.265, AV1, MPEG-4 Part 2, with AAC audio |
| Matroska | `.mkv` | Almost anything |
| AVI | `.avi` | MJPG, MPEG-4 Part 2, older codecs |
| WebM | `.webm` | VP8, VP9, AV1 with Opus or Vorbis audio |
Two files that are both named .mp4 can contain different codecs, and your system may decode one but not the other. When a file refuses to open, ask two questions: which container is it, and which codec is inside it?
From file to array
When you call cv2.VideoCapture("input.mp4"), OpenCV uses a backend (a library such as FFmpeg or GStreamer) to do the work. On each read, the backend:
- Reads packets of compressed data from the container (demuxing).
- Decodes the packets into raw pixels using the codec.
- Converts the pixels into a NumPy array that OpenCV returns to you.
Everything up to step 3 is outside your control once the file exists. What you receive is always decompressed: a uint8 array with shape (height, width, 3) and channels in blue, green, red (BGR) order. Chapter 2 covers the array in detail. The key point here is that the codec's cleverness is hidden from you. Compression artifacts such as blockiness, however, are baked into the pixels you get. Any analysis you do runs on the decoded, slightly degraded image.
Inspecting a video
You can ask the capture object about the file before processing anything. The script below opens a file, reads its properties, and decodes the FourCC (four-character code) that identifies the codec. Properties are covered fully in a later chapter. Here they serve to make the concepts visible.
import cv2
def fourcc_to_text(value: float) -> str:
code = int(value)
return "".join(chr((code >> (8 * i)) & 0xFF) for i in range(4))
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
try:
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)
count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
codec = fourcc_to_text(cap.get(cv2.CAP_PROP_FOURCC))
print(f"size: {width}x{height}")
print(f"fps: {fps:.3f}")
print(f"frames: {count} (as reported)")
print(f"codec: {codec!r}")
if fps > 0:
print(f"length: about {count / fps:.1f} s")
ok, frame = cap.read()
if ok:
print(f"first frame: shape={frame.shape}, dtype={frame.dtype}")
finally:
cap.release()Typical output for an H.264 file looks like this:
size: 1920x1080
fps: 29.970
frames: 900 (as reported)
codec: 'avc1'
length: about 30.0 s
first frame: shape=(1080, 1920, 3), dtype=uint8Note the shape. It is (height, width, 3), which is the reverse order of the width x height you read from the properties. This mismatch causes many bugs when writing video later.
Edge cases and gotchas
Reported values are hints, not guarantees. CAP_PROP_FRAME_COUNT is usually read from container metadata. For some formats, streams, or damaged files it is an estimate, zero, or negative. Never rely on it as the exact number of frames you will receive. Rely on cap.read() returning False to detect the end.
FPS can be zero or wrong. Cameras and network streams often report 0 or a default value such as 30. The value is what the driver or container claims, not a measurement. You can measure the true rate by counting frames over elapsed time, which a later chapter does.
Variable frame rate (VFR). Some files, especially phone recordings and screen captures, store frames at irregular intervals. A single fps number is then only an average. Computing time as index / fps drifts from the true time. If timing matters, read the per-frame timestamp (CAP_PROP_POS_MSEC) instead.
Frame rate is not playback speed in OpenCV. cap.read() decodes as fast as it can. A 30 fps file may process in 3 seconds or 3 minutes, depending on your hardware and code. Nothing in VideoCapture slows you to real time. Real-time pacing comes only from a live camera, or from code you write.
Codec support depends on your build. The opencv-python wheels bundle FFmpeg, which handles most common formats. HEVC and AV1 support varies by version and platform. A file that plays in a media player may still fail to open in OpenCV. Re-encoding it with a tool such as ffmpeg is the usual fix.
Rotation and aspect metadata. Phone videos are often stored in landscape with a rotation flag. Depending on the OpenCV version and backend, frames may arrive rotated, or already corrected. Check one frame's shape against what you expect.
Interlaced and non-square-pixel sources. Older broadcast footage may be interlaced (each frame is two interleaved fields) or use non-square pixels. OpenCV delivers the stored pixel grid as is. Deinterlacing and aspect correction are your job.
Audio is ignored. VideoCapture returns only video frames. Audio and subtitles in the container are skipped, and a video you write with VideoWriter will have no audio.
Summary of the model
- A video is an ordered sequence of equally sized frames at a frame rate.
- A codec compresses and decompresses those frames. A container packages the compressed streams with other data.
- Compressed streams mix keyframes with frames that depend on others, which makes decoding sequential and seeking approximate.
- OpenCV returns decoded frames as
uint8NumPy arrays of shape(height, width, 3)in BGR order. - Metadata such as fps and frame count describes what the file claims. Treat it as a hint, and check the results of reads.
Exercise
A 1280x720 video has 3 channels of 8 bits per pixel and runs at 25 fps. (a) How many megabytes per second would the raw, uncompressed frames need (1 MB = 1,000,000 bytes)? (b) cap.get(cv2.CAP_PROP_FRAME_COUNT) returns 750 and cap.get(cv2.CAP_PROP_FPS) returns 25.0, but your read loop ends after 748 frames. What should you conclude, and what should your loop use to decide when to stop?
Show answer
(a) One frame is 1280 x 720 x 3 = 2,764,800 bytes. At 25 fps that is 69,120,000 bytes per second, about 69 MB/s. (b) The frame count is metadata and can be slightly off, so the file simply yielded 748 decodable frames. The loop should stop when ok, frame = cap.read() returns ok == False, not when a counter reaches the reported count.
Exercise
A colleague says "my file is H.264 because it ends in .mp4". Why is that reasoning unreliable, and how could you check the codec from Python with OpenCV?
Show answer
The extension names the container, and an MP4 container can hold several codecs (H.264, H.265, AV1, MPEG-4 Part 2 and others). To check, open the file with cv2.VideoCapture, read cap.get(cv2.CAP_PROP_FOURCC), convert the integer to four characters (for example with "".join(chr((code >> (8 * i)) & 0xFF) for i in range(4))), and compare the result, such as avc1 for H.264. The value comes from the backend and may not be available for every source.