Sub topic 11
Jumping to a frame in a file
This chapter covers random access: moving the read position of a VideoCapture to a chosen frame so you can read it without decoding everything before it. It assumes you can already open a file, write the ok, frame = cap.read() loop, and read capture properties such as CAP_PROP_FRAME_COUNT. It also assumes you know that a frame is a NumPy array.
Why seeking exists
A read loop moves forward one frame at a time. That is the right tool for processing a whole file. Sometimes you need only part of it:
- Save a thumbnail from the middle of a video.
- Inspect the frame where an event was logged at a known time.
- Build a preview strip of evenly spaced frames.
- Resume processing after a crash instead of starting over.
Seeking lets you do these without reading all the preceding frames in your own code. Seeking is not free, and it is not always exact. The details below explain why.
The three position properties
You seek by setting a property with cap.set(property, value). You find the current position by reading the same property with cap.get(property).
| Property | Unit | Meaning |
|---|---|---|
| `cv2.CAP_PROP_POS_FRAMES` | frame index, 0-based | Index of the frame that the next `read()` will return |
| `cv2.CAP_PROP_POS_MSEC` | milliseconds | Timestamp of the current position |
| `cv2.CAP_PROP_POS_AVI_RATIO` | 0.0 to 1.0 | Relative position in the file, 0 at the start and 1 at the end |
CAP_PROP_POS_FRAMES is the one you will use most. The index is 0-based, so setting it to 0 returns the first frame. Setting it to 100 makes the next read() return the 101st frame, which is index 100.
After a read(), CAP_PROP_POS_FRAMES has advanced by one, because it describes the next frame, not the one you just received.
The basic seek
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
cap.set(cv2.CAP_PROP_POS_FRAMES, 100) # next read returns frame 100 (0-based)
ok, frame = cap.read()
if ok:
cv2.imwrite("frame_100.png", frame)
else:
print("Could not read frame 100")
cap.release()The sequence is: open, check, set the position, read once, check the flag. Check ok after the seek. A seek past the end of the file, or into a damaged region, usually shows up as a failed read, not as an exception.
What happens inside a seek
Most video files use inter-frame compression. Only some frames, called keyframes (or I-frames), are stored as complete images. The frames between two keyframes are stored as differences from earlier frames. A decoder cannot start at an arbitrary frame, because that frame may depend on frames before it.
When you ask for frame 100, the backend (usually FFmpeg) typically does this:
- Jump to the nearest keyframe at or before frame 100.
- Decode forward from that keyframe, discarding the output.
- Return frame 100.
This explains two behaviors:
- Cost depends on distance to the keyframe. If keyframes occur every 250 frames, a seek may decode up to 249 frames before returning one. Seeking to a keyframe is fast. Seeking just before the next keyframe is slow.
- Accuracy depends on the backend and file. A well-behaved backend decodes forward to the exact frame. Some backends or container formats land on the keyframe, or on a frame near the target. The result can be off by a few frames or more.
Verifying a seek
You cannot trust a seek without checking it at least once on your own files. The most direct test compares the seeked frame with the same frame reached by plain sequential reading. This script does that with two separate captures:
import cv2
import numpy as np
def frame_by_reading(path, index):
"""Reach a frame by decoding from the start. Slow but exact."""
cap = cv2.VideoCapture(path)
if not cap.isOpened():
raise RuntimeError(f"Could not open {path}")
try:
for _ in range(index):
if not cap.grab():
return None
ok, frame = cap.read()
return frame if ok else None
finally:
cap.release()
def frame_by_seeking(path, index):
"""Reach a frame with a seek. Fast but backend-dependent."""
cap = cv2.VideoCapture(path)
if not cap.isOpened():
raise RuntimeError(f"Could not open {path}")
try:
cap.set(cv2.CAP_PROP_POS_FRAMES, index)
ok, frame = cap.read()
return frame if ok else None
finally:
cap.release()
path = "input.mp4"
for index in (0, 50, 100, 250):
expected = frame_by_reading(path, index)
actual = frame_by_seeking(path, index)
if expected is None or actual is None:
print(f"frame {index}: could not read")
continue
differing = np.count_nonzero(cv2.absdiff(expected, actual))
print(f"frame {index}: {differing} differing values")A count of 0 means the two frames are identical. A small nonzero count can come from decoder differences. A large count means the seek landed on a different frame. Run this on a few representative files before building anything that relies on exact positions.
Guarding a seek in a helper function
A small helper keeps the checks in one place. It validates the index against the reported frame count, checks the return value of set, and checks the read:
import cv2
def read_frame_at(cap, index):
"""Return the frame at a 0-based index, or None on failure."""
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if index < 0 or (total > 0 and index >= total):
return None
if not cap.set(cv2.CAP_PROP_POS_FRAMES, index):
return None # the backend refused the seek
ok, frame = cap.read()
return frame if ok else None
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
try:
frame = read_frame_at(cap, 100)
print("got frame" if frame is not None else "seek failed")
finally:
cap.release()Two points about this helper:
cap.setreturns a boolean, butTruemeans only that the property was accepted. It does not prove the position is exact.CAP_PROP_FRAME_COUNTis often an estimate computed from the duration and the frame rate. It can be 0 or negative for some sources, which is why the check treatstotal > 0as optional.
Seeking by time or by ratio
When you know a time, not a frame number, set CAP_PROP_POS_MSEC:
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
cap.set(cv2.CAP_PROP_POS_MSEC, 5000) # 5 seconds
ok, frame = cap.read()
if ok:
print("Position after read (ms):", cap.get(cv2.CAP_PROP_POS_MSEC))
print("Next frame index:", int(cap.get(cv2.CAP_PROP_POS_FRAMES)))
cap.release()Time-based seeking has the same keyframe behavior. The conversion between time and frame index uses the reported FPS, so a variable-frame-rate file can map a time to a different frame than you expect.
CAP_PROP_POS_AVI_RATIO is useful for "jump to the middle" operations (0.5). Support varies by backend, so read the property back after setting it, or prefer frame indexes and compute the ratio yourself.
Taking evenly spaced frames
A preview strip is a common use of seeking. Compute the indexes first, then seek to each one:
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
try:
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if total <= 0:
raise RuntimeError("Frame count unknown; cannot space frames")
count = 5
for i in range(count):
index = i * total // count
cap.set(cv2.CAP_PROP_POS_FRAMES, index)
ok, frame = cap.read()
if not ok:
print(f"Skipped index {index}: read failed")
continue
cv2.imwrite(f"preview_{i}.png", frame)
print(f"Saved preview_{i}.png from frame {index}")
finally:
cap.release()Using i * total // count spreads the indexes across the file and never reaches total, so the last index stays in range even when the count is an estimate that is slightly too high.
Seek or skip?
Seeking is not always faster than reading forward. If you want every 5th frame, a seek per frame can cost more than skipping, because each seek restarts decoding from a keyframe. For short gaps, step forward with grab():
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
step = 5
index = 0
try:
while True:
if not cap.grab(): # advance one frame
break
if index % step == 0:
ok, frame = cap.retrieve() # decode into an array only when needed
if ok:
print("kept frame", index, frame.shape)
index += 1
finally:
cap.release()grab() advances to the next frame. retrieve() converts the grabbed frame into an array. read() is the two combined. For compressed video, grab() still decodes the frame internally, but it skips the conversion and copy into a NumPy array, so it is cheaper than read().
A rough decision rule:
- Few frames, far apart: seek.
- Many frames, close together:
grab()forward andretrieve()the ones you keep. - Exact positions required: read sequentially, or verify the seek as above.
Common errors
- Off-by-one confusion. Index 100 is the 101st frame. After one
read(),POS_FRAMESreports the next index, not the one you just read. - Not checking
okafter a seek. A bad seek often producesok == Falseandframe == None. PassingNoneto a later OpenCV call raises a confusing error. - Trusting
FRAME_COUNTas exact. Treat it as an estimate unless you have counted the frames yourself. - Seeking on a camera or stream. Live sources have no random access. The call may return
Falseor silently do nothing. Seeking is a file feature. - Seeking in a loop for sequential work. Setting
POS_FRAMESbefore every read of consecutive frames adds decoding cost and risks inconsistent results. Seek once, then read forward.
Exercise
A file reports 3000 frames and 30 FPS. You call cap.set(cv2.CAP_PROP_POS_FRAMES, 600) and then cap.read() once. (a) Which frame index does the read return, and about what time in seconds is that? (b) What does cap.get(cv2.CAP_PROP_POS_FRAMES) return afterward? (c) You need 10 frames spaced evenly across the file. Which indexes do you seek to, using the formula from this chapter?
Show answer
(a) The read returns the frame at index 600, the 601st frame, at about 600 / 30 = 20 seconds. (b) It returns 601, because the property reports the index of the next frame to be read. (c) With index = i * total // count and total = 3000, count = 10, the indexes are 0, 300, 600, 900, 1200, 1500, 1800, 2100, 2400 and 2700. Check ok after each read, because a seek may fail or land on a nearby frame.
Exercise
Why can seeking to frame 249 take much longer than seeking to frame 250 in a file whose keyframes are 250 frames apart (at indexes 0, 250, 500, and so on)? What simple check lets you detect an inexact seek on your own files?
Show answer
Frame 250 is a keyframe, so the decoder can start there and return it at once. Frame 249 depends on earlier frames, so the decoder jumps to the keyframe at index 0 and decodes 249 frames forward before it can return the target. To detect an inexact seek, read the same index two ways, by decoding sequentially with grab() and by cap.set(CAP_PROP_POS_FRAMES, ...), then compare the arrays with cv2.absdiff and np.count_nonzero. A count of 0 means the seek was exact for that frame.