Sub topic 4
The read loop: `ok, frame = cap.read()`
A video source produces one image at a time. OpenCV returns that image through VideoCapture.read(). The call returns two values:
okis a Boolean success flag.frameis the current image as a NumPy array in BGR channel order.
This chapter assumes basic Python loops, try/finally, NumPy array shapes, and an installed opencv-python package.
The basic loop
Open a source, check it, and repeatedly call read():
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
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow("gray", gray)
# waitKey also lets OpenCV process window events.
if cv2.waitKey(1) & 0xFF == ord("q"):
break
finally:
cap.release()
cv2.destroyAllWindows()For a video file, ok usually becomes False when OpenCV reaches the end. The loop then stops before trying to process an invalid frame.
The frame value has a shape such as (720, 1280, 3). The first two values are height and width. The final value is the three-channel BGR color image. A grayscale conversion changes the shape to (720, 1280).
Why check `ok` first?
A failed read does not provide a usable frame. Depending on the backend and source, frame may be empty or contain invalid data. Always test ok before passing frame to processing functions.
The common failure cases are different for files and cameras:
| Source | Typical reason for `ok == False` | Usual response |
|---|---|---|
| Video file | End of file, damaged data, or a decoder error | Stop the loop and report the problem if needed |
| Camera | Disconnect, unavailable device, or temporary read failure | Stop, retry, or reconnect according to the application |
A camera has no natural end-of-file. You normally stop it with a key press, a time limit, or an external shutdown signal. A failed camera read may be temporary, but blindly continuing can create a tight loop that consumes CPU. Production code should count failures and retry with a short delay or reconnect after a limit.
Choosing where to stop
A file-processing loop normally stops when read() fails:
while True:
ok, frame = cap.read()
if not ok:
break
# Process frame hereA live preview usually needs both checks:
while True:
ok, frame = cap.read()
if not ok:
print("Camera read failed")
break
cv2.imshow("camera", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
breakThe argument to waitKey is a delay in milliseconds. A small positive value gives the window system time to handle keyboard and display events. Without waitKey, an OpenCV window may not refresh or respond correctly.
Keep cleanup outside the loop
Call release() when the source is no longer needed. For GUI programs, call destroyAllWindows() too. Put cleanup in a finally block so it runs when the loop ends normally or an exception occurs.
Do not open the same camera repeatedly without releasing it. Another process, or a later part of your program, may be unable to access a device that remains locked.
Exercise
Why should the program test ok before converting frame to grayscale, and why does a camera loop also need a key-press condition?
Show answer
A failed read may not produce a valid image, so processing frame first can raise an error. A camera does not reach an end-of-file, so a separate condition such as pressing q is needed to stop a successful read loop.