Second Program—AVI Video

Playing a video with OpenCV is almost as easy as displaying a single picture. The only new issue we face is that we need some kind of loop to read each frame in sequence; we may also need some way to get out of that loop if the movie is too boring. See Example 2-2.

Example 2-2. A simple OpenCV program for playing a video file from disk

#include "highgui.h"

int main( int argc, char** argv ) {
    cvNamedWindow( "Example2", CV_WINDOW_AUTOSIZE );
    CvCapture* capture = cvCreateFileCapture( argv[1] );
    IplImage* frame;
    while(1) {
        frame = cvQueryFrame( capture );
        if( !frame ) break;
        cvShowImage( "Example2", frame );
        char c = cvWaitKey(33);
        if( c == 27 ) break;
    }
    cvReleaseCapture( &capture );
    cvDestroyWindow( "Example2" );
}

Here we begin the function main() with the usual creation of a named window, in this case "Example2". Things get a little more interesting after that.

CvCapture* capture = cvCreateFileCapture( argv[1] );

The function cvCreateFileCapture() takes as its argument the name of the AVI file to be loaded and then returns a pointer to a CvCapture structure. This structure contains all of the information about the AVI file being read, including state information. When created in this way, the CvCapture structure is initialized to the beginning of the AVI.

frame = cvQueryFrame( capture );

Once inside of the while(1) loop, we begin reading from the AVI file. cvQueryFrame() takes as its argument a pointer to a CvCapture structure. It then grabs the next video ...

Get Learning OpenCV now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.