cv2 不会在 Python 中给出错误,所以不能将它与 except 块一起使用

cv2 doesn't give an error in Python, so can't use it with except block

我正在使用 cv2 在 Python 中启动相机。我希望它具有灵活性,因此无论用户使用的是内置摄像头还是 USB 摄像头,它都可以工作。如果无法识别凸轮,它也会显示错误。

这是我写的。

try:    
    camera = cv2.VideoCapture(0)
            
except:
    try:
        camera = cv2.VideoCapture(1)
                
    except:
        print("")
        print("There was a problem accessing your camera, please try again")
        print("Exiting now...")
        time.sleep(10)
        exit()

事实是,如果 cv2 未检测到凸轮,它不会给出 Python 错误。它只是给出以下警告:

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

所以,第二个 except 块没有执行,这可能会让我的用户对警告感到困惑。我如何才能执行 except 块?

谢谢!

使用cv2.VideoCapture(无效设备号)不会抛出异常。它构造一个包含无效设备的 - 如果你使用它,你会得到异常。

测试 None 而不是 isOpened() 的构造对象以清除无效对象。

import cv2 as cv 

def testDevice(source):
   cap = cv.VideoCapture(source) 
   if cap is None or not cap.isOpened():
       print('Warning: unable to open video source: ', source)

testDevice(0) # no printout
testDevice(1) # prints message

我已经从 - .

中获取了答案

Note: I initially checked the VideoCapture object using the help method provided i.e help(camera). help method in python helps to provide all the methods and attributes that are available for the object. It helps in debugging libraries and looking into methods and documentation quickly from console itself.

您可以尝试从捕获设备读取一次以获得一帧。如您所知,尝试读取帧时会给出另一个值,该值告诉我们读取是否成功:

camera = cv2.VideoCapture(0)
success, frame = camera.read()
if not success:
    camera = cv2.VideoCapture(1)
    success, frame = camera.read()
    if not success:
        print("")
        print("There was a problem accessing your camera, please try again")
        print("Exiting now...")
        time.sleep(10)
        exit()