如何在OpenCV 2.3中计算摄像头数量?

23

我想获取可用相机的数量。

我尝试像这样计算相机的数量:

for(int device = 0; device<10; device++) 
{
    VideoCapture cap(device);
    if (!cap.isOpened())
        return device;          
}
如果我连接相机,它从未打开失败。所以我尝试预览不同的设备,但我总是得到我的相机图像。
如果我连接第二个相机,设备0是相机1,设备1-10是相机2。
我认为DirectShow设备存在问题。
如何解决这个问题?或者是否有类似于OpenCV1中的cvcamGetCamerasCount()函数?
我正在使用Windows 7和USB相机。
6个回答

11

10
即使这是一个旧帖子,这里有一个适用于OpenCV 2/C++的解决方案。
/**
 * Get the number of camera available
 */
int countCameras()
{
   cv::VideoCapture temp_camera;
   int maxTested = 10;
   for (int i = 0; i < maxTested; i++){
     cv::VideoCapture temp_camera(i);
     bool res = (!temp_camera.isOpened());
     temp_camera.release();
     if (res)
     {
       return i;
     }
   }
   return maxTested;
}

在 Windows 7 x64 环境下测试了以下内容:

  • OpenCV 3 [自定义版本]
  • OpenCV 2.4.9
  • OpenCV 2.4.8

使用 0 至 3 个 USB 摄像头。


你的代码在Git上吗?我也有Windows 8.1,想检查一下是Windows平台的问题还是OpenCV的bug。 - BlouBlou
@jgd:你能告诉我你使用的是哪个版本,有多少个摄像头,在哪个系统上,以便我能够再次检查我的代码(一年前完成)吗? - BlouBlou
@BlouBlou 在平板电脑上使用两个摄像头,安装 Windows 操作系统和 OpenCV 2.4.2。在笔记本电脑上进行另一个测试,使用相同版本的 OpenCV,但只有一个摄像头。 - Juan Garcia
可能取决于安装的设备驱动程序等... 现在,大约一年后,同样的代码对我来说崩溃了。几个月前我安装了一个GigE相机(在测试时未连接)。 - Micka
尝试访问一个超出可用数量的相机是未定义行为。因此,在某些系统上它会崩溃,而在其他系统上则不会。 - Jonathan.
显示剩余2条评论

9

这是一篇很旧的文章,但我发现在Ubuntu 14.04和OpenCv 3上使用Python 2.7时,这里的解决方案都不适用于我。相反,我用Python想出了以下解决方法:

import cv2

def clearCapture(capture):
    capture.release()
    cv2.destroyAllWindows()

def countCameras():
    n = 0
    for i in range(10):
        try:
            cap = cv2.VideoCapture(i)
            ret, frame = cap.read()
            cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            clearCapture(cap)
            n += 1
        except:
            clearCapture(cap)
            break
    return n

print countCameras()

也许有人会发现这很有用。

5
我用Python实现了这个功能:
def count_cameras():
    for i in range(10):
        temp_camera = cv.CreateCameraCapture(i-1)
        temp_frame = cv.QueryFrame(temp_camera)
        del(temp_camera)
        if temp_frame==None:
            del(temp_frame)
            return i-1 #MacbookPro counts embedded webcam twice

遗憾的是,即使没有任何内容,Opencv仍会打开摄像头对象,但如果尝试提取其内容,则无法归因于任何内容。您可以使用它来检查相机数量。在我测试过的每个平台上都有效。

返回i-1的原因是MacBookPro将自己的嵌入式相机计算两次。


2

Python 3.6:

import cv2

# Get the number of cameras available
def count_cameras():
    max_tested = 100
    for i in range(max_tested):
        temp_camera = cv2.VideoCapture(i)
        if temp_camera.isOpened():
            temp_camera.release()
            continue
        return i

print(count_cameras())

1

我也遇到了类似的问题。我使用videoInput.h库代替Opencv来枚举相机并将索引传递给Videocapture对象来解决了这个问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接