Sub topic 1
Video Frames, Frame Rate and Codecs
Prerequisites
You should know basic Python, including loops and try/finally blocks. You should also be comfortable with NumPy array indexing and shapes. Install the package with pip install opencv-python.
What a video is
A video is a sequence of still images, called frames, shown one after another. The frame rate, measured in frames per second (fps), sets how many frames play each second. A 30 fps clip holds 30 frames for every second of playback.
A codec is the method used to compress frames so the file stays small. H.264 and MPEG-4 are common examples. The codec sits inside a container such as MP4 or AVI. OpenCV decodes the codec for you, so your code receives ready-to-use frames.
A frame is a NumPy array
Each frame is a NumPy array with shape (height, width, 3) and dtype uint8. OpenCV stores the three channels in Blue, Green, Red (BGR) order. Many other libraries use RGB, so check the order when you mix tools.
import numpy as np
frame = np.zeros((480, 640, 3), dtype=np.uint8) # black 640x480 frame
frame[:, :, 2] = 255 # index 2 is red in BGR
print(frame.shape) # (480, 640, 3)Opening a file or a camera
cv2.VideoCapture takes a file path or a camera index. Always call isOpened(), because a wrong path does not raise an error by itself.
import cv2
cap = cv2.VideoCapture("input.mp4") # or 0 for the first camera
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")The read loop
cap.read() returns two values: ok, a Boolean success flag, and frame, the image. Stop when ok is False. A file ends this way, and a camera read can fail this way too.
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
try:
while True:
ok, frame = cap.read()
if not ok:
break
print(frame.shape)
finally:
cap.release()Exercise
Why does the code check isOpened() before the loop starts?
Show answer
A wrong path or a missing camera makes read() return False immediately. The check raises a clear error instead of letting the program fail silently.