Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ OpenCV 2.4.11: List all cameras

I want to list all connected webcams (USB-webcams and internal webcams), using C++, OpenCV 2.4.11, Windows 8.1 and Qt Creator 3.4.2. For me it is enough to get the number of accessible webcams in the following way:

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

Here is my code:

// 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++;
}

The code in the try-block works if I have activated my internal webcam. The call fails when I deactivate the internal camera in the hardware manager (and no other camera is attached to my laptop) with the following error message (debug mode):

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).

and the following 2 build problems:

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

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

How can I fetch the occuring error? As you see, try/catch does not work.

Or is there a method where I can access all available webcams in OpenCV without such a dirty loop?

like image 864
Loomis Avatar asked Dec 10 '15 09:12

Loomis


1 Answers

There is still no any functionality related to camera count in OpenCV at the current moment (3.0.0 version) - see corresponding ticket.

Proper camera handling seems like OpenCV internal problem (for example, described here or here). Usually it appears in capture code after physically disabling camera while it is still opened in OpenCV (when we try to read destroyed file descriptor).

Generally you can even implement your own handler for access violations (please look into this thread), but it's really dirty trick.

like image 64
avtomaton Avatar answered Oct 03 '22 10:10

avtomaton