在Python中隐藏VideoCapture OpenCV错误消息

时间:2019-04-22 20:39:37

标签: python opencv error-handling

我有一个尝试打开多个摄像机的代码(摄像机的数量可能会或可能不会更改)。我通过遍历推定的n个摄像机(未显示循环)并将重要内容包装在try上来解决了这个问题。

我的目标是检测相机是否存在,如果没有,则什么也不做。

try:
    cv2.VideoCapture(10)
    # do things if camera exists
except:
    pass

这有效,但是我仍然在控制台上收到消息

VIDEOIO ERROR: V4L: can't open camera by index 10

如何避免/隐藏/隐藏此消息?

更新

建议这样做,它仍然会打印错误

# detect all connected webcams
valid_cams = []
errors_id = []

for i in range(10):
    try:
        cap = cv2.VideoCapture(i)
        if cap.isOpened():
            (test, frame) = cap.read()
            if test:
                valid_cams.append(i)
    except:
        pass

1 个答案:

答案 0 :(得分:0)

您可以使用警卫和isOpened()来确保OpenCV可以打开视频流,而不是隐藏消息。

# detect all connected webcams
valid_cams = []
errors_id = []

for i in range(10):
    try:
        cap = cv2.VideoCapture(i)
        if cap is None or not cap.isOpened():
            print('Error: Unable to open camera stream: {}'.format(i))
        else:
            (test, frame) = cap.read()
            if test:
                valid_cams.append(i)
    except:
        pass