Getting frames from .avi video using OpenCV

sue-ling picture sue-ling · Feb 12, 2012 · Viewed 25.3k times · Source
#include "cv.h"
#include "highgui.h"
int main(int argc, char** argv)
{
CvCapture* capture=0;
IplImage* frame=0;

capture = cvCaptureFromAVI("C:\\boy walking back.avi"); // read AVI video
if( !capture )
    throw "Error when reading steam_avi";

cvNamedWindow( "w", 1);

for( ; ; )
{
/*  int cvGrabFrame (CvCapture* capture);
    IplImage* cvRetrieveFrame (CvCapture* capture)*/
    frame = cvQueryFrame( capture );
if(!frame)
        break;
    cvShowImage("w", frame);

}
cvWaitKey(0); // key press to close window
cvDestroyWindow("w");
cvReleaseImage(&frame);
}

I am using openCV with VS2008. I have read in a video file and used CV_CAP_PROP_FRAME_COUNT to obtain the number of frames which was approximately 130 for a 4 second long video clip. I am doing a motion recognition of walking so I need to get every other 5 frames since between 5 frames, there is little change in the motion of the body. I have a program so far which allows me to obtain one frame of the video clip. However, I am unable to obtain different frames and also, I am not sure how to go about getting every other 5 frames. The above is the code used to get one frame of the video.

Answer

mevatron picture mevatron · Feb 12, 2012

You should be able to skip 4 frames, and then keep the 5th frame. Below is a small example I wrote to demonstrate this:

IplImage* skipNFrames(CvCapture* capture, int n)
{
    for(int i = 0; i < n; ++i)
    {
        if(cvQueryFrame(capture) == NULL)
        {
            return NULL;
        }
    }

    return cvQueryFrame(capture);
}


int main(int argc, char* argv[])
{
    CvCapture* capture = cvCaptureFromFile("../opencv-root/samples/c/tree.avi");

    IplImage* frame = NULL;
    do
    {
        frame = skipNFrames(capture, 4);
        cvNamedWindow("frame", CV_WINDOW_AUTOSIZE);
        cvShowImage("frame", frame);
        cvWaitKey(100);
    } while( frame != NULL );

    cvReleaseCapture(&capture);
    cvDestroyWindow("frame");
    cvReleaseImage(&frame);

    return 0;
}

Hope that helps :)