Sub topic 4
The read loop: ok, frame = cap.read()
This chapter covers the loop that every OpenCV video program is built on. It assumes you know basic Python, including try/finally, and basic NumPy shapes. It also assumes opencv-python is installed and that you have already opened a source with cv2.VideoCapture. Here you will learn what cap.read() returns, when and why it fails, and how to end the loop correctly for both files and cameras.
What cap.read() returns
cap.read() grabs the next frame from the source, decodes it, and returns a tuple of two values:
ok: a Pythonbool. It isTrueif a frame was delivered andFalseif not.frame: a NumPy array of shape(height, width, 3)and dtypeuint8in BGR order, orNoneif the read failed.
The two values always go together. You must check ok before you touch frame. If you skip the check, a failed read gives you frame = None, and the next call, such as cv2.cvtColor(frame, ...), raises an error from OpenCV about an empty source image. The traceback points at cvtColor, but the real cause is the read one line earlier.
Internally, read() is a convenience that combines two steps, grab() and retrieve(). grab() advances to the next frame and retrieve() decodes it into an array. Later chapters and multi-camera setups sometimes call them separately. For a single source, read() is the right call.
The standard loop
This is the basic read-process-display loop. It reads a file, converts each frame to grayscale, and shows it until the file ends or you press q.
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 # end of file or a failed read
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow("gray", gray)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
finally:
cap.release()
cv2.destroyAllWindows()Three parts of this loop matter for this chapter:
while Trueruns until abreak. The number of frames is not known in advance, and for a camera it has no end, so aforloop over a frame count is the wrong tool.if not ok: breakis the end-of-stream check. It is the only thing that stops the loop when a file runs out of frames.- The
finallyblock runs on every exit path, including exceptions raised inside the loop. Resource cleanup gets its own chapter, but you should already write it this way.
One flag, several meanings
The ok flag is False for more than one reason, and the loop treats them all the same way. That is a strength for short scripts and a weakness when you need to debug.
| Situation | Source | What happens |
|---|---|---|
| The last frame has already been read | File | `ok` is `False`. This is normal end of file. |
| The file is corrupt or truncated | File | `ok` becomes `False` earlier than expected. |
| The camera was unplugged | Camera | `ok` is `False`. |
| The device is busy or a driver timeout occurs | Camera | `ok` may be `False` on some reads. |
| `release()` was already called | Both | `ok` is `False`, with no exception raised. |
| The source never opened | Both | `ok` is `False` on every call. |
For a file, a False read normally means the end. For a camera, it almost always means something went wrong, because a camera has no end of file. This is why the camera example in the topic prints a message before it breaks. Use this pattern when you want to tell the cases apart:
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))
count = 0
try:
while True:
ok, frame = cap.read()
if not ok:
break
count += 1
finally:
cap.release()
print(f"Read {count} frames; container reported about {total}")
if total > 0 and count < total * 0.99:
print("Warning: the file ended much earlier than expected")CAP_PROP_FRAME_COUNT is an estimate taken from container metadata. Some files report a count that differs from the number of frames you can actually decode by a few frames, and some streams report 0 or a negative number. This is why the check above allows a 1% margin and only runs when total is positive. Do not use the reported count as the loop condition.
Why not loop on isOpened()?
A common alternative you will see in tutorials is while cap.isOpened():. It works for simple files, but it has a trap. isOpened() reports whether the capture was initialised successfully. It does not become False when a file runs out of frames. If you forget the if not ok: break check inside such a loop, the program keeps calling read() forever, getting (False, None) each time, and then crashes on frame being None or spins without stopping.
The while True form with an explicit check makes the exit condition visible in one place. It also separates two different questions: "did the source open?" (asked once, before the loop) and "did this read work?" (asked on every iteration).
Frames are reused or replaced, not shared
Each call to read() returns a new array. You can safely keep a reference to a frame after the next read. The frame will not be overwritten. This matters when you want to compare two frames, as in frame differencing. The following loop keeps the previous frame while reading the next one:
import cv2
cap = cv2.VideoCapture("input.mp4")
if not cap.isOpened():
raise RuntimeError("Could not open input.mp4")
ok, prev = cap.read()
if not ok:
raise RuntimeError("No frames in input.mp4")
try:
while True:
ok, frame = cap.read()
if not ok:
break
# prev and frame are two different arrays here
print("mean change:", cv2.absdiff(prev, frame).mean())
prev = frame
finally:
cap.release()Note the structure. The first frame is read before the loop, so the loop always has a prev to compare against. The assignment prev = frame only rebinds a name. It does not copy pixels, and it does not need to, because the next read() creates a fresh array.
The array that read() returns is yours to modify. Drawing on it with cv2.putText or cv2.rectangle changes the array in place, which is fine as long as you do not need the original pixels afterwards. If you do, take a copy with frame.copy() before drawing.
Reading a camera
A camera loop looks the same, but the failure handling differs. There is no end of file, so a failed read is an error. The loop in the topic prints a message and stops:
import cv2
cap = cv2.VideoCapture(0) # first camera; the index depends on the system
if not cap.isOpened():
raise RuntimeError("Could not open camera 0")
try:
while True:
ok, frame = cap.read()
if not ok:
print("Camera read failed")
break
cv2.imshow("camera", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
finally:
cap.release()
cv2.destroyAllWindows()Stopping at the first failure is the simplest policy. A long-running program may prefer to tolerate a few failures and only give up after several in a row, because some USB cameras drop an occasional frame:
import cv2
MAX_FAILURES = 10
cap = cv2.VideoCapture(0)
if not cap.isOpened():
raise RuntimeError("Could not open camera 0")
failures = 0
try:
while True:
ok, frame = cap.read()
if not ok:
failures += 1
if failures >= MAX_FAILURES:
print(f"Giving up after {failures} failed reads")
break
continue
failures = 0 # a good read resets the counter
cv2.imshow("camera", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
finally:
cap.release()
cv2.destroyAllWindows()Do not use this retry policy for files. A failed read on a file is permanent, so retrying only wastes time before the loop ends anyway.
Blocking behavior
cap.read() blocks. The call does not return until a frame is ready. For a file, that is as fast as the decoder can work, so a file loop runs as quickly as your processing allows and not at the video's frame rate. For a camera, read() waits for the next frame to arrive, so the loop is paced by the camera, for example about 30 times per second. If your processing for each frame takes longer than the interval between frames, the loop falls behind. A later chapter measures this.
Because a blocking read can hang when a device stalls, programs that must stay responsive often move reading to a separate thread. That is outside this chapter, but it explains why you may see such designs.
Common errors
- Using
framewithout checkingok. The symptom is an OpenCVerrormentioning!_src.empty()in a later function, or anAttributeErrorsuch as'NoneType' object has no attribute 'shape'. Checkokimmediately after each read. - Forgetting
waitKey.imshowonly draws whenwaitKeyruns. Without it the window stays blank or frozen. The call also lets you detect key presses. - Reading after
release(). The call returns(False, None)quietly. If your loop ends immediately and you see no frames, check that no earlier code released the capture. - Relying on
isOpened()to end the loop. As described above, it does not turnFalseat the end of a file. - Wrong path. A misspelled file name does not raise an exception from
VideoCapture. It produces a capture whoseisOpened()isFalse, which is why that check comes first. - Expecting real-time playback from a file. A file loop plays as fast as it can decode. With
waitKey(1)it usually runs faster than the original frame rate, and for small videos it can look like fast-forward.
Exercise
A script uses while cap.isOpened(): and calls cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) right after ok, frame = cap.read(), with no check on ok. The input file has 200 frames. What happens after frame 200, and what is the fix?
Show answer
After frame 200, read() returns (False, None). isOpened() still returns True, so the loop runs again, and cvtColor receives None and raises an OpenCV error about an empty source image. The fix is to add if not ok: break immediately after the read, and preferably use while True: so the exit condition is explicit.
Exercise
You are reading from camera index 0. A read fails once every few minutes and then recovers. How would you change the loop so that it survives these single failures but still stops if the camera is truly gone?
Show answer
Count consecutive failed reads. On ok == False, increment a counter and continue to the next iteration. On ok == True, reset the counter to 0. Break out of the loop when the counter reaches a limit such as 10. Resetting on every good read means only an unbroken run of failures ends the program.