我正在使用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(无效的设备号)不会抛出异常.它构造了一个< VideoCapture对象>包含无效设备 – 如果您使用它,您将获得例外.
测试构造的对象为None而不是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线
06002