C ++ OpenCV 2.4.11:列出所有摄像头

时间:2015-12-10 09:18:30

标签: c++ opencv webcam video-capture

我想列出所有连接的网络摄像头(USB网络摄像头和内部网络摄像头),使用C ++,OpenCV 2.4.11,Windows 8.1和Qt Creator 3.4.2。 对我来说,以下列方式获取可访问的网络摄像头的数量就足够了:

VideoCapture videoCapture(0); // Will access my internal laptop webcam.
VideoCapture videoCapture(1); // Will access the first connected usb webcam.

这是我的代码:

// Following procedure detects, how many webcams are accessible from 0 on upwards.
numberOfDevices = 0;
bool noError = true;

while (noError)
{
    try
    {
        // Check if camera is available.
        VideoCapture videoCapture(numberOfDevices); // Will crash if not available, hence try/catch.

        // ...
    }
    catch (...)
    {
        noError = false;
    }

    // If above call worked, we have found another camera.
    numberOfDevices++;
}

如果我已激活内部网络摄像头,则try-block中的代码可以正常工作。当我通过以下错误消息(调试模式)停用硬件管理器中的内部摄像头(并且没有其他摄像头连接到我的笔记本电脑)时,呼叫失败:

Exception Triggered
---------------------------
The inferior stopped because it triggered an exception.<p>Stopped in thread 0 by: 
Exception at 0x7ff8533d9090, code: 0xc0000005: read access violation at: 0x0, flags=0x0 (first chance).

以及以下2个构建问题:

Exception at 0x7ff871af8b9c, code: 0xa1a01db1: , flags=0x0 (first chance)

Exception at 0x7ff8533d9090, code: 0xc0000005: read access violation at: 0x0, flags=0x0 (first chance)

如何获取发生的错误?如您所见,try / catch不起作用。

或者有没有一种方法可以在没有这么脏的环路的情况下访问OpenCV中所有可用的网络摄像头?

3 个答案:

答案 0 :(得分:3)

目前 OpenCV 中仍然没有任何与相机计数相关的功能( 3.0.0 版本) - 请参阅corresponding ticket

正确的相机处理似乎是 OpenCV 内部问题(例如,描述为herehere)。通常它会在物理上禁用相机后出现在捕获代码中,而它仍然在 OpenCV 中打开(当我们尝试读取已销毁的文件描述符时)。

一般情况下,您甚至可以为违反访问权限实施自己的处理程序(请查看this thread),但这真的很脏。

答案 1 :(得分:1)

我创建了这个C ++类,允许枚举在OpenCV中使用的设备(包括ID)。它托管在GitHub上。

https://github.com/studiosi/OpenCVDeviceEnumerator

我们的想法是使用DirectShow获取具有GUID CLSID_VideoInputDeviceCategory类别的所有设备,然后通过枚举器获取它们在系统上出现的顺序,这是您在打开它们时需要的ID OpenCV创建一个VideoCapture对象(通过使用接收ID的构造函数,它将是枚举中设备的索引)。显然,这种方法仅适用于Windows。

答案 2 :(得分:0)

在 OpenCV >4 版本中,默认 API 是 MSMF。 这是它的一个变体:https://github.com/Aoderus/OpenCV_CameraList_MSMF