Unable to read frames from VideoCapture from secondary webcam with OpenCV

After some time I’ve found out that it is always only the first call of read that fails and skipping the first frame started to work fine although the true reason of this behavior remained unknown.

Later James Barnett (see comments above) has pointed out that the reason might be that it takes a while till the camera gets ready for capturing and my current solution looks the following way (C++11’s sleep):

#include <chrono>
#include <thread>
...

VideoCapture cap(1);

// give camera some extra time to get ready:
std::this_thread::sleep_for(std::chrono::milliseconds(200));

if (!cap.isOpened()) {
     std::cout << "Unable to read stream from specified device." << std::endl;
     return;
}

while (true)
{
    // retrieve the frame:
    Mat frame;
    if (!cap.read(frame)) {
        std::cout << "Unable to retrieve frame from video stream." << std::endl;
        continue;
    }

    // display it:
    imshow("LiveStream", frame);

    // stop if Esc has been pressed:
    if (waitKey(1) == 27) {
        break;
    }
}

cap.release();

Hopefully some future visitors will find it helpful 🙂

Leave a Comment