如何正确检查相机是否可用?


问题内容

我正在使用OpenCV打开并从多个网络摄像头读取。一切正常,但是我似乎找不到找到相机可用的方法。

我尝试了以下代码(摄像头2不存在):

import cv2
try:
    c = cv2.VideoCapture(2)
except:
    print "Cam 2 is invalid."

但这只会打印出很多错误:

VIDEOIO ERROR: V4L: index 2 is not correct!
failed to open /usr/lib64/dri/hybrid_drv_video.so
Failed to wrapper hybrid_drv_video.so
failed to open /usr/lib64/dri/hybrid_drv_video.so
Failed to wrapper hybrid_drv_video.so
GStreamer Plugin: Embedded video playback halted; module v4l2src0 reported: Internal data stream error.
OpenCV Error: Unspecified error (GStreamer: unable to start pipeline
) in cvCaptureFromCAM_GStreamer, file /builddir/build/BUILD/opencv-3.2.0/modules/videoio/src/cap_gstreamer.cpp, line 832
VIDEOIO(cvCreateCapture_GStreamer(CV_CAP_GSTREAMER_V4L2, reinterpret_cast<char *>(index))): raised OpenCV exception:

/builddir/build/BUILD/opencv-3.2.0/modules/videoio/src/cap_gstreamer.cpp:832: error: (-2) GStreamer: unable to start pipeline
 in function cvCaptureFromCAM_GStreamer

OpenCV Error: Unspecified error (unicap: failed to get info for device
) in CvCapture_Unicap::initDevice, file /builddir/build/BUILD/opencv-3.2.0/modules/videoio/src/cap_unicap.cpp, line 139
VIDEOIO(cvCreateCameraCapture_Unicap(index)): raised OpenCV exception:

/builddir/build/BUILD/opencv-3.2.0/modules/videoio/src/cap_unicap.cpp:139: error: (-2) unicap: failed to get info for device
 in function CvCapture_Unicap::initDevice

CvCapture_OpenNI::CvCapture_OpenNI : Failed to enumerate production trees: Can't create any node of the requested type!
<VideoCapture 0x7fa5b5de0450>

没有异常被抛出。c.read()稍后使用时,我会得到False,但是我想在程序的初始化阶段执行此操作。

那么,如何确定我拥有多少个有效摄像机,或者如何确定某个数量“映射”到一个有效摄像机?


问题答案:

使用cv2.VideoCapture( invalid device number )不会引发异常。它构造了一个<VideoCapture object>包含无效设备的设备-如果 使用 它,则会得到异常。

测试所构造的对象Nonenot isOpened()淘汰无效的。


对我来说,这有效(1个便携式相机设备):

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

输出1:

Warning: unable to open video source:  1

来自以下示例的示例:https
:
//github.com/opencv/opencv_contrib/blob/master/samples/python2/video.py
第159ff行


cap = cv.VideoCapture(source)
    if 'size' in params:
        w, h = map(int, params['size'].split('x'))
        cap.set(cv.CAP_PROP_FRAME_WIDTH, w)
        cap.set(cv.CAP_PROP_FRAME_HEIGHT, h)
if cap is None or not cap.isOpened():
    print 'Warning: unable to open video source: ', source