Let's Make Robots!

Taking Video From a Webcam in OpenCV

So I have been trying to get OpenCV to work. I displayed some pictures in windows and simple stuff like that. Then, following along in my book, I attempted to write a program which would take video from a webcam and place it in a video. Here is my code:

 

#include "stdafx.h"

#include "cv.h"

#include "highgui.h"

 

 

main( int argc, char** argv ){

cvNamedWindow( "Webcam", CV_WINDOW_AUTOSIZE );

 

CvCapture* capture;

if( argc==1 ){

capture = cvCreateCameraCapture(0);

}else{

capture = cvCreateFileCapture( -1 );(I believe that this -1 is the source of the problem. I am not sure why becuase it is simply supposed to choose a webcam but it is the only part of the code underlined in red)

}

assert( capture != NULL );

IplImage* frame;

while(1){

frame = cvQueryFrame( capture );

if( !frame ) break;

cvShowImage( "Webcam", frame );

char c = cvWaitKey(33);

if( c == 27 ) break;

}

cvReleaseCapture( &capture );

cvDestroyWindow( "Webcam" );

 

return 0;

}

By the way, I am working in C++. So when I build this it finds one error. I can not figure out what it is so I was wondering if I could have some assistance. Thanks-Magykguy

 

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
GroG's picture

cvCreateFileCapture expects a char* 

It wants a string, specifically it wants a path/filename of an video file such as : 

CvCapture* capture = cvCreateFileCapture( "movie.avi" );

 

magykguy721's picture

I'm trying to take video from a webcam. So how would I specify a path? Or would I have to use a different method?

GroG's picture

This method gets a capture of the first webcam

capture = cvCreateCameraCapture(0); 

The code you had looked like it could switch from webcam to file depending on what parameters where sent on startup - except for the -1 bug

magykguy721's picture

As I edited in the post above, I think the -1 is the problem. I tryed replacing your bit of code with mine and it still said it has 1 error when I built it. Like I said, I think this 1 error is the -1. 

birdmun's picture

If it is syntax, you should get a line number. Otherwise, you should still get a line number and some kind of cryptic error.

birdmun's picture

while(1) {
   frame = cvQueryFrame( capture );
   if( !frame ) break;
   cvShowImage( "Webcam", frame );
   char c = cvWaitKey(33);
   if( c == 27 ) break;
}

I would rather see if something like the following would work.
frame = cvQueryFrame( capture );
while ( frame || c != 27 ) {
   cvShowImage( "Webcam", frame );
   frame = cvQueryFrame( capture );
   char c = cvWaitKey(33);
}
I just don't like the way the previous code was written. I didn't see anything that popped out as a syntax error. Maybe you could post your error?