gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:47:37 26 4
gpt4 key购买 nike

我正在使用 OpenCV 打开并读取多个网络摄像头。一切正常,但我似乎无法找到一种方法来了解相机是否可用。

我试过这段代码(cam 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>包含无效设备 - 如果您使用它,您会得到异常。

测试 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

1 的输出:

Warning: unable to open video source:  1

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

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

关于python - 如何正确检查相机是否可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48049886/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com