Sub topic 3
Opening a File or a Camera with `VideoCapture`
This chapter assumes basic Python loops and try/finally, NumPy array shapes, and the idea that video is a sequence of images. It also assumes that opencv-python is installed:
python -m pip install opencv-pythonWhat `VideoCapture` does
OpenCV's VideoCapture class connects your program to a video source. A source can be:
- A file path such as
"input.mp4". - A camera device number such as
0. - A stream URL supported by the OpenCV backend installed on your system.
The object keeps track of the source and decodes frames when you call its read method. A successful read returns two values:
ok, a Boolean that says whether a frame was received.frame, a NumPy array containing the image.
A file has a natural end. A camera normally does not, but a camera read can still fail because the device was disconnected, is busy, or is not supported.
Open a file
Pass the path to cv2.VideoCapture. Check isOpened() immediately. This check catches common problems such as a misspelled path, a missing file, or an unavailable decoder.
The check does not prove that the file contains readable frames. The first call to read() provides that additional test.
import cv2
source = "input.mp4"
cap = cv2.VideoCapture(source)
if not cap.isOpened():
raise RuntimeError(f"Could not open video source: {source}")
try:
ok, frame = cap.read()
if not ok:
raise RuntimeError("The source opened, but no frame was readable")
height, width = frame.shape[:2]
print(f"Read a frame with size {width}x{height}")
finally:
cap.release()The frame is a NumPy array with shape (height, width, channels). OpenCV normally decodes color images in BGR order: blue, green, red. This differs from the RGB order used by many plotting and machine-learning libraries.
Open a camera
A camera is selected by a device index. On many systems, 0 means the first camera, 1 means the second, and so on. The available indexes depend on the operating system and connected devices.
The same opening and reading checks work for a camera:
import cv2
camera_index = 0
cap = cv2.VideoCapture(camera_index)
if not cap.isOpened():
raise RuntimeError(f"Could not open camera {camera_index}")
try:
ok, frame = cap.read()
if not ok:
raise RuntimeError("The camera opened, but the first read failed")
print("Camera frame shape:", frame.shape)
finally:
cap.release()release() disconnects the camera or closes the file. Always call it, including when processing raises an exception. A finally block is useful because it runs on normal completion and on errors.
Choose a source safely
A small helper can handle either a file or a camera. The source type matters: a string is interpreted as a path or URL, while an integer is interpreted as a camera index.
| Source value | Meaning |
|---|---|
| `"input.mp4"` | Open a video file |
| `0` | Open the first camera |
| `1` | Open another camera device |
Use a camera index only after confirming which device your system exposes. Use an explicit file path while testing file-based code so that path errors are easy to identify.
Exercise
Why should a program check both cap.isOpened() and the ok value returned by cap.read()?
Show answer
isOpened() checks whether OpenCV created the source connection, while ok checks whether a particular frame was actually received. The connection can succeed even when the source has no readable frames or a later camera read fails.