pythonopencverror-handlingvideo-capture

How do I get VideoCapture to return errors instead of warnings?


When trying to implement a basic try/except statement to get frames from a camera on Linux I noticed that OpenCV does not raise an error when the camera is missing or the device index is wrong; instead it prints a warning. How could I catch this?

Example:

import cv2

def foo(camera_index):
    try:
        cap = cv2.VideoCapture(camera_index)
    except Exception:
        print("Couldn't open camera at {}".format(camera_index))

Running foo(1) with a working camera at /dev/video/0 will print:

WARN:0] global /tmp/pip-req-build-kne9u3r2/opencv/modules/videoio/src/cap_v4l.cpp (893) open VIDEOIO(V4L2:/dev/video1): can't open camera by index

My except is then useless because cv2 will never raise a proper exception (yet the message text sounds like an error).


Solution

  • You can't catch those warnings, but you can check whether the VideoCapture object has been successfully created using isOpened() method.

    As an example:

    cap = cv2.VideoCapture(camera_index)
    if not cap.isOpened():
      raise Exception("Couldn't open camera {}".format(camera_index))
    

    Performing this check after creating a VideoCapture object is a common pattern; please see here for another example.