# Weird bug with VideoCapture

Hello everybody,

I'm facing a very weird bug when using VideoCapture.

I have two webcams, and I want to switch between them.

When the program is started, it opens device 0. When the user presses 'd', he gets connected to 'current_device+1'. When he presses 'q', he gets connected to 'current_device-1'

I can switch between 0 and 1 very well, and multiple times without any problem, however, when I try to connect to device 2, it detects a problem (I only have 2 cams), and then connects back to 1. No problem until here, however, when I press 'q', it tries to connect to device 0, and here is the problem, it can connect, but the operator "<<" is very slow (1 second I think), and it always returns empty Mat....

Here is the code (very simple reproduction of the problem (most of the lines are just to print stuff on the console)):

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>

using namespace cv;
using namespace std;

int main( int argc, char** argv ) {
namedWindow("TestW");
VideoCapture vc(0);

int i = 0;
char key('0');
Mat frame;

while (key != 'a') {
key = waitKey(10);
vc >> frame;

if (frame.empty()) {
std::cerr << "WTF, frame is empty." << std::endl;
} else {
imshow("TestW", frame);
}

if (key == 'd') {
i++;
std::cerr << "Trying to open " << i << "...";
vc = VideoCapture(i);
if (vc.isOpened()) {
std::cerr << " done." << std::endl << std::endl;
} else {
i--;
std::cerr << "But is not working, trying to open " << i << "...";
vc = VideoCapture(i);
if (vc.isOpened()) {
std::cerr << "And is working" << std::endl << std::endl;
} else {
std::cerr << "Let's stop here." << std::endl;
exit(1);
}
}

} else if (key == 'q') {
i--;
std::cerr << "Trying to open " << i << "..." << std::endl;
vc = VideoCapture(i);
if (vc.isOpened()) {
std::cerr << "done" << std::endl << std::endl;
} else {
std::cerr << "Let's stop here." << std::endl;
exit(1);
}
}
}
}


And here is an output with this code:

At the beginning, I just switch between 0 and 1:

Trying to open 1... done.

Trying to open 0...

done

Trying to open 1... done.

Trying to open 0...

done

Trying to open 1... done.

I then press 'd' when I'm connected to device 1 (so it connects to device 2, and goes back to device 1):

Trying to open 2...But is not working, trying to open 1...And is working

And 'q' when I'm connected to device 1, the connection seems okay, but it's very slow and the frames are empty:

Trying to open 0... done WTF, frame is empty. WTF, frame is empty. WTF, frame is empty. WTF, frame is empty. WTF, frame is empty.

However I can still go back to device 1 without any problem! But device 0 seems to be broken after having connected to device 2....

Do you have any suggestion? I'm working on Windows 7 64 bits

edit retag close merge delete