2
votes

I'm currently using OpenCV 2.3.1 with Visual Studio 2008. I'm trying to read the frames from a Hauppauge Usb Live-2 using VideoCapture, but I'm ran into a strange issue. Below is the relevant part of my code:

VideoCapture vc(0);

if (!vc.isOpened()) return -1;

Mat frame;
namedWindow("Camera");

bool success;

while (true)
{
    success = vc.read(frame);

    if (!success) continue;

    imshow("Camera", frame);

    if (waitkey(30) == 27) break;
}

Initially, when running my code in debug mode, the window displaying the captured frames shows only a solid gray image. Attempting to debug my program, I placed breakpoint a breakpoint at the start of my code and stepped through each line. At imshow, however, the window started displaying the grabbed frames properly, showing what was captured by my camera. Subsequently, I realized that so long as I enter a breakpoint between opening my device and displaying it on the window, the frames will start showing up properly.

Does anyone have any idea how entering a breakpoint may affect the execution of a program in debug mode (in this case allowing the VideoCapture object to start reading the frames properly)?

Note: Running the executable gave no problems either, so I'm posting this question out of curiosity.

2

2 Answers

2
votes

I believe your code is trying to display the image (which is empty) before your camera gets ready. Try to slow down for one or two seconds, by first include files like:

#include <chrono>
#include <thread>

Then before your while statement, add this line:

std::this_thread::sleep_for(std::chrono::milliseconds(2000));

If you are using C++ with lower version than 11, then the sleep_for method might be different. Take a reference here.

0
votes

The camera has an initialisation period so you need to check for empty frames.

Now there are two options, you could do what @Derman has said and put in a wait but how do you know how long you need to wait for?

Or you can check for empty frames and only show the window if they are not empty

VideoCapture vc(0);

if ( !vc.isOpened() )  // if not success, exit program
    {
        cout << "Cannot open the video file" << endl;
        return -1;
    }

Mat frame;
namedWindow("Camera");

bool success;
while (true)
{
    vc.read(frame);

    if(frame.empty()){
            std::cerr<<"frame is empty"<<std::endl;
            break;
        }

    imshow("Camera", frame);

    if (waitkey(30) == 27) break;
}

I don't see any reason why this code shouldn't start showing the frames once they are avaliable from the camera