Sub topic 11
Jumping to a Frame in a File
This chapter assumes basic Python loops and try/finally, NumPy array shapes, and the OpenCV opencv-python package. It also assumes that a video is a sequence of numbered images. Frame numbers start at zero, so frame 0 is the first frame.
Why seek instead of reading every frame
A read loop normally decodes frames in order. That is efficient when you need the whole video, but wasteful when you need one frame or a small region. OpenCV lets you request a new position with VideoCapture.set.
The most useful property is CAP_PROP_POS_FRAMES. Set it to a frame number, then call read. The next successful read returns the frame at, or near, that position.
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
target_frame = 100
cap.set(cv2.CAP_PROP_POS_FRAMES, target_frame)
ok, frame = cap.read()
if not ok:
raise RuntimeError(f"Could not read frame {target_frame}")
cv2.imwrite("frame_100.png", frame)
cap.release()The saved image is a regular OpenCV frame: a NumPy array with shape (height, width, 3) and color channels in BGR order.
How random access works
Most compressed video does not store every frame as a complete image. It stores occasional keyframes and records changes for frames between them. When you seek to frame 100, the codec may jump to an earlier keyframe and decode forward until it reaches the requested frame.
This makes seeking different from indexing a Python list:
- It is usually slower than reading the next frame.
- Accuracy depends on the video codec and OpenCV backend.
- Repeated seeks can be expensive.
- Seeking near the end of a file can fail if the requested frame does not exist.
The following diagram shows the common process.
Check the actual position
Capture properties are estimates provided by the backend. After reading, query CAP_PROP_POS_FRAMES to inspect the position reported by OpenCV. Do not assume that every backend gives identical results.
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
target = 100
if target < 0 or target >= total:
raise ValueError(f"Frame must be between 0 and {total - 1}")
try:
cap.set(cv2.CAP_PROP_POS_FRAMES, target)
ok, frame = cap.read()
if not ok:
raise RuntimeError("The requested frame could not be decoded")
reported_position = cap.get(cv2.CAP_PROP_POS_FRAMES)
print(f"Requested frame: {target}")
print(f"Reported next position: {reported_position:.0f}")
if not cv2.imwrite("selected.png", frame):
raise RuntimeError("Could not save selected.png")
finally:
cap.release()After a successful read, the reported position often refers to the next frame that will be returned, so it may be one greater than the frame just read.
Seeking by time
You can also set CAP_PROP_POS_MSEC, which represents milliseconds from the beginning of the video. This is useful when a timestamp matters more than a frame number.
cap.set(cv2.CAP_PROP_POS_MSEC, 2500)
ok, frame = cap.read()Time-based seeking has the same codec and backend limitations. Variable-frame-rate video makes the relationship between time and frame number less predictable. For repeatable extraction, frame-number seeking on a constant-frame-rate file is usually easier to test.
Common errors
- Treating frame numbers as one-based. OpenCV uses zero-based positions.
- Ignoring the Boolean result from
read. - Requesting a frame beyond
CAP_PROP_FRAME_COUNT. - Expecting exact, fast random access from every codec.
- Forgetting to release the capture after a failed read.
- Assuming a time position maps perfectly to one frame.
Exercise
A video reports 240 frames, and you need frames 100 through 110. Should you call set with CAPPROPPOS_FRAMES before every read? Explain.
Show answer
No. Seek once to frame 100, then call read repeatedly for frames 100 through 110. Sequential decoding is usually faster and avoids repeated codec seeks.