Sub topic 8
Working with cameras: indexes, backends and requested settings
A camera is opened with the same cv2.VideoCapture class as a file, but several things behave differently. You pick the device by number instead of by path, a platform-specific backend talks to the driver, and the settings you set are only requests. This chapter covers those differences and how to write code that copes with them.
It assumes you can already write the read loop from earlier chapters (ok, frame = cap.read()), use try/finally, and read capture properties with cap.get(). You need a webcam or another camera to run the examples.
Device indexes
A file is opened by path. A camera is opened by an integer device index:
cap = cv2.VideoCapture(0)Index 0 usually means the first camera the operating system lists, but nothing in OpenCV guarantees it. Several things change which index you get:
- A laptop with a built-in webcam and a USB webcam may list them in either order.
- Unplugging and re-plugging a USB camera can change its index.
- Virtual cameras, such as those from video-conferencing or streaming software, take up indexes too.
- Some cameras expose several devices, for example a color stream and an infrared stream, and each gets its own index.
OpenCV has no portable call that lists cameras and their names. The usual workaround is to probe indexes in a small range and keep the ones that deliver a frame.
import cv2
def probe_cameras(max_index=5, backend=cv2.CAP_ANY):
"""Return (index, width, height) for each index that delivers a frame."""
found = []
for index in range(max_index):
cap = cv2.VideoCapture(index, backend)
try:
if not cap.isOpened():
continue
ok, frame = cap.read()
if ok:
height, width = frame.shape[:2]
found.append((index, width, height))
finally:
cap.release()
return found
if __name__ == "__main__":
cameras = probe_cameras()
if not cameras:
print("No working camera found")
for index, width, height in cameras:
print(f"camera {index}: {width}x{height}")The code checks for a real frame because isOpened() alone can be misleading. On some systems a device opens successfully but never delivers data, for example when another program holds it or the OS has denied camera permission.
Probing can be slow, because a failed index may take a second or more to time out on some platforms. Run it once at startup, or let the user choose an index, instead of probing inside a loop.
Backends
A backend is the library OpenCV uses to talk to the device. The camera index is interpreted by the backend, and each backend has its own quirks, speed and set of supported properties. Common backends by platform:
| Backend constant | Platform | Notes |
|---|---|---|
| `cv2.CAP_V4L2` | Linux | Video4Linux2, the standard Linux camera API |
| `cv2.CAP_DSHOW` | Windows | DirectShow, older and widely compatible, often opens quickly |
| `cv2.CAP_MSMF` | Windows | Media Foundation, the newer API, sometimes slow to open |
| `cv2.CAP_AVFOUNDATION` | macOS | Apple's capture framework |
| `cv2.CAP_ANY` | All | Lets OpenCV choose; this is the default |
You pass the backend as the second argument, which is called the apiPreference:
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW) # Windows, DirectShow
cap = cv2.VideoCapture(0, cv2.CAP_V4L2) # Linux, Video4Linux2With CAP_ANY, OpenCV tries the backends compiled into your build and picks the first one that works. That is usually fine, but naming a backend is useful in three cases:
- Open time. On Windows,
CAP_MSMFcan take many seconds to open some cameras, whileCAP_DSHOWopens quickly. - Property support. A property that is ignored under one backend may work under another. Exposure and fourcc control are common examples.
- Reproducibility. Naming the backend removes one source of "works on my machine" differences.
Only backends compiled into your OpenCV build are available. The opencv-python wheels include the main camera backend for each platform. Asking for one that is not present fails to open, as shown here.
Requested settings are not guaranteed
With a file, properties such as width and height describe what is stored. With a camera, cap.set() sends a request to the driver. The driver can accept it, round it, pick a nearby mode, or ignore it. A camera that supports 640x480 and 1280x720 will not give you 1000x700. It will fall back to a mode it has, and which one depends on the driver.
cap.set() returns a boolean, but you should not rely on it alone. Some backends return True for a request they ignore. The reliable check is to read the value back with cap.get() and compare it with what you asked for.
import cv2
def open_camera(index=0, width=1280, height=720, fps=30, backend=cv2.CAP_ANY):
cap = cv2.VideoCapture(index, backend)
if not cap.isOpened():
raise RuntimeError(f"Could not open camera {index}")
# Requests only: the driver decides what it actually uses.
cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
cap.set(cv2.CAP_PROP_FPS, fps)
actual_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
actual_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
actual_fps = cap.get(cv2.CAP_PROP_FPS)
print(f"requested {width}x{height} @ {fps}, "
f"got {actual_w}x{actual_h} @ {actual_fps:.1f}")
return cap
cap = open_camera()
try:
ok, frame = cap.read()
if ok:
print("first frame shape:", frame.shape) # (height, width, 3)
finally:
cap.release()Two details matter here:
- Check the frame, not just the property.
cap.get(cv2.CAP_PROP_FRAME_WIDTH)reports what the backend believes. The shape of an actual frame is the final truth, and it is what you must use to size aVideoWriter. - Frame rate often reads 0. Many cameras report an FPS of
0, or a number that does not match the real delivery rate. Treat the reported FPS as a hint, and measure the real rate (see the timing chapter) before writing it into a file.
Size and rate are linked
Cameras usually offer a fixed list of modes, each pairing a resolution, a pixel format and a maximum frame rate. High resolutions often cap the frame rate. A camera might give 30 fps at 640x480 but only 5 fps for raw frames at 1920x1080 over USB 2. If you ask for a mode and then see a low frame rate, the cause may be the mode and not your processing code.
Pixel format and FourCC
Cameras deliver frames in a pixel format such as YUYV (uncompressed) or MJPG (each frame is a JPEG). Uncompressed formats use much more USB bandwidth, so high-resolution, high-rate modes are often only available as MJPG. You can request a format through the FOURCC property:
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*"MJPG"))Set the FOURCC before width, height and FPS. On many backends, changing the format afterwards resets the other settings. This is a request like any other, so read the value back. The FOURCC property comes back as a float encoding four characters, which you can decode like this:
code = int(cap.get(cv2.CAP_PROP_FOURCC))
fourcc = "".join(chr((code >> (8 * i)) & 0xFF) for i in range(4))
print("pixel format:", fourcc)Whatever the camera's format, OpenCV hands you a decoded BGR NumPy array from read(). The format only affects bandwidth, latency and speed.
Reading from a live source
A camera has no end of file. read() returns ok == False only when something goes wrong: the device was unplugged, another process took it, or the driver stopped. Camera reads also have two practical differences from file reads.
Warm-up. The first few frames after opening are often dark, off-color or repeated while auto-exposure and white balance settle. If the first frame matters, discard a handful of frames before using one.
Buffering and latency. The driver keeps a small queue of frames. If your processing is slower than the camera, the queue fills and the frames you read are older than what the camera sees now, so the picture lags behind real time. Some backends accept cap.set(cv2.CAP_PROP_BUFFERSIZE, 1) to shrink the queue, but many ignore it. The portable fix is to make each loop iteration faster than the frame interval, or to read frames in a separate thread and keep only the latest. Measuring per-frame time is covered in a later chapter.
A loop that tolerates brief read failures before giving up looks like this:
import cv2
WARMUP_FRAMES = 10
MAX_FAILURES = 5
cap = cv2.VideoCapture(0)
if not cap.isOpened():
raise RuntimeError("Could not open camera 0")
try:
for _ in range(WARMUP_FRAMES):
cap.read() # discard while exposure settles
failures = 0
while True:
ok, frame = cap.read()
if not ok:
failures += 1
if failures >= MAX_FAILURES:
print("Camera stopped delivering frames")
break
continue
failures = 0
cv2.imshow("camera", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
finally:
cap.release()
cv2.destroyAllWindows()For a file, the first False means the video is over. For a camera it may be a one-off glitch, so a short run of consecutive failures is a better signal. A long-running program may go further and release the capture, wait, and reopen it.
Common errors
isOpened()isFalse. The index is wrong, another program holds the camera, permission is denied, or the chosen backend is not available. Try other indexes and other backends, and close apps such as video-call software.- Opens but
read()always fails. Often a permissions problem, or a virtual camera with no active source. - Window is black or very dark at first. Warm-up frames. Discard the first few.
- Wrong resolution. The driver rejected your request. Read the value back and use the real frame shape.
- Video lags behind reality. Processing is slower than the camera frame interval, so buffered frames pile up. Speed up the loop or keep only the latest frame.
- Index changes between runs. Do not hard-code it. Make it a command-line option or a config value.
- Camera stays "in use" after a crash.
release()was never called. Usetry/finallyas in the examples.
Exercise
You run cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920) and cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080) on a USB webcam, and both calls return True. Later your VideoWriter output is corrupt. What is the most likely cause, and how do you avoid it?
Show answer
A return value of True does not prove the driver applied the request. The camera probably stayed in a smaller mode, such as 1280x720 or 640x480, so the frames did not match the size passed to VideoWriter, which can produce an unplayable or empty file. Avoid it by reading the properties back with cap.get(), and by taking the size from frame.shape[:2] of a real frame (height, width) before creating the writer.
Exercise
Why does a camera read loop usually tolerate a few failed reads, while a file read loop stops at the first one?
Show answer
A file ends cleanly, so the first ok == False means the end of the video. A camera never reaches an end, so a False result means a fault, which can be a brief glitch such as a dropped frame or a temporary driver stall. Counting consecutive failures and stopping only after a short run avoids quitting on a harmless hiccup, while still ending when the camera is really gone.