I'm testing out some code I found to capture the web cam video stream, it's quite different from what I used to do for achieving the same but it's supposed to be the appropiate way for doing it.
This is the way I used to do:
CvCapture* capture;
IplImage* frame = 0;
while (true)
{
//Read the video stream
capture = cvCaptureFromCAM(1);
if (! capture) break;
frame = cvQueryFrame(capture);
//Create a window to display
cvNamedWindow("Te estas viendo", CV_WINDOW_NORMAL|CV_WINDOW_KEEPRATIO);
cvShowImage("Te estas viendo", frame);
int c = cvWaitKey(10);
if ( (char)c == 27 ) break;
}
//Clean and release resources
cvReleaseImage(&frame);
cvDestroyAllWindows();
This is the testing code:
VideoCapture camera;
camera.open(cameraNumber);
if (!camera.isOpened()) {
cerr << "ERROR: Could not access the camera or video!" <<endl;
exit(1);
}
while (true) {
// Grab the next camera frame.
cv::Mat cameraFrame;
camera >> cameraFrame;
if (cameraFrame.empty()) {
std::cerr << "ERROR: Couldn't grab a camera frame." <<
std::endl;
exit(1);
}
I'm not getting the first error line, so it's supposed to be opening the camera, but always failing at grabbing camera frames.
You could be missing the closing bracket in your while loop. Also make sure that you create namedWindow
outside the while
loop. Creating the window at every iteration is expensive. See below:
VideoCapture camera;
camera.open(cameraNumber);
namedWindow("output");
if (!camera.isOpened()) {
cerr << "ERROR: Could not access the camera or video!" <<endl;
return -1;
}
while (true) {
// Grab the next camera frame.
cv::Mat cameraFrame;
camera >> cameraFrame;
if (cameraFrame.empty()) {
std::cerr << "ERROR: Couldn't grab a camera frame." <<
std::endl;
return -1;
}
imshow("output", cameraFrame);
waitKey(10);
}