C++ OpenCV 2.4.11:列出所有相机

C++ OpenCV 2.4.11: List all cameras

我想列出所有连接的网络摄像头(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 中所有可用的网络摄像头?

目前 OpenCV3.0.0 版本)中仍然没有任何与相机数量相关的功能 - 请参阅corresponding ticket.

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

通常您甚至可以实现自己的访问冲突处理程序(请查看 this thread),但这确实是个肮脏的把戏。

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

https://github.com/studiosi/OpenCVDeviceEnumerator

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

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