我正在使用OpenCV打开并从几个网络摄像头读取.我一切都很好,但我似乎无法找到一种方法来了解相机是否可用.
我试过这个代码(凸轮2不存在):
import cv2
try:
c = cv2.VideoCapture(2)
except:
print "Cam 2 is invalid."
Run Code Online (Sandbox Code Playgroud)
但这只是打印了很多错误:
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>
Run Code Online (Sandbox Code Playgroud)
没有异常被抛出.在c.read()以后使用时,我确实得到了False,但我想在我的程序的初始化阶段这样做.
那么,我如何找出我有多少有效相机或检查某个数字是否"映射"到有效相机?
使用cv2.VideoCapture( invalid device number )不会抛出异常.它构造一个<VideoCapture object>包含无效设备 - 如果你使用它,你会得到例外.
测试构造的对象None以及not 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
Run Code Online (Sandbox Code Playgroud)
输出1:
Warning: unable to open video source: 1
Run Code Online (Sandbox Code Playgroud)
示例来自:https://github.com/opencv/opencv_contrib/blob/master/samples/python2/video.py lines 159ff
Run Code Online (Sandbox Code Playgroud)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
在 Linux 中可用的另一种解决方案是/dev/videoX在VideoCapture()呼叫中使用设备。插入摄像头时,设备就在那里。与 一起glob(),获取所有相机很简单:
import cv2, glob
for camera in glob.glob("/dev/video?"):
c = cv2.VideoCapture(camera)
Run Code Online (Sandbox Code Playgroud)
当然,c使用需要检查isOpened(),但您确定您只扫描可用的相机。
| 归档时间: |
|
| 查看次数: |
8160 次 |
| 最近记录: |