Sub topic 8
Working with Cameras: Indexes, Backends, and Requested Settings
Prerequisites and the camera model
This chapter assumes basic Python, NumPy array shapes, try/finally, and the OpenCV package. You should also know that a video stream is a sequence of images called frames.
OpenCV opens a camera through cv2.VideoCapture. A camera is usually identified by a device index. Index 0 commonly means the first camera, index 1 the second, and so on. These indexes are assigned by the operating system and may change when cameras are unplugged or reordered.
A camera does not have an end-of-file. The read loop should continue until the user quits or a read fails.
Camera indexes and backends
A backend is the OpenCV component that communicates with the operating system or camera driver. cv2.CAP_ANY lets OpenCV choose a suitable backend. Explicit backends can help when automatic selection has problems:
| Backend | Typical platform | Example constant |
|---|---|---|
| Video4Linux | Linux | `cv2.CAP_V4L2` |
| DirectShow | Windows | `cv2.CAP_DSHOW` |
| AVFoundation | macOS | `cv2.CAP_AVFOUNDATION` |
Backend availability depends on how OpenCV was built and on the installed drivers. An explicit backend that works on one computer may fail on another.
import cv2
camera_index = 0
backend = cv2.CAP_ANY
cap = cv2.VideoCapture(camera_index, backend)
if not cap.isOpened():
raise RuntimeError(
f"Could not open camera index {camera_index}"
)
# These are requests. The driver may choose other values.
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
cap.set(cv2.CAP_PROP_FPS, 30)
print("Backend:", cap.getBackendName())
print(
"Actual settings:",
int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
"x",
int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),
"at",
cap.get(cv2.CAP_PROP_FPS),
"FPS",
)
try:
while True:
ok, frame = cap.read()
if not ok:
print("Camera read failed")
break
cv2.imshow("camera", frame)
# waitKey is also needed for window events.
if cv2.waitKey(1) & 0xFF == ord("q"):
break
finally:
cap.release()
cv2.destroyAllWindows()Requested settings are not guaranteed
cap.set(property, value) sends a request to the driver. It does not guarantee that the camera accepted the value. Camera hardware usually supports only certain combinations. For example, a camera may provide 1280 × 720 at 30 FPS but support 1920 × 1080 only at 15 FPS.
Always read the properties back with cap.get. Treat the returned values as the operating configuration. Some drivers report 0 or an approximate value for FPS, so use measured timing when exact throughput matters.
Resolution also affects processing cost. A 1920 × 1080 frame contains four times as many pixels as a 960 × 540 frame. Higher resolution can improve detection detail, but it increases memory use and the time needed for every per-frame operation.
> callout tip > A successful set call means that the request was accepted by the OpenCV interface. It does not prove that the hardware uses that value. Verify the value after opening the camera.
Common failures and practical choices
- If index
0fails, try another index, but do not assume indexes identify a camera permanently. - If a camera opens but frames fail, check operating-system permissions and whether another program is using the device.
- If automatic backend selection is unreliable, test the backend documented for your operating system.
- If the requested FPS is unavailable, reduce the resolution or select a supported camera mode.
- Keep the
releaseanddestroyAllWindowscalls infinally, including when the loop exits because of an exception.
The frame returned by read is normally a NumPy array in OpenCV's BGR channel order. You can pass it to later processing such as grayscale conversion, blurring, or object detection.
Exercise
Why should a program read the camera properties after calling set?
Show answer
set sends a request, but the driver may choose a different supported resolution or frame rate. Reading the properties reveals the actual configuration.