Displaying AVI Video using OpenCV

A short demonstration of how to use OpenCV to capture and display video frames from an avi file. The code demonstrates how to capture video from an example video (avi) file, get information in the form of frames per sec. and display the video.

1. Some pre-requisites

i. Make sure OpenCV has been successfully installed on your machine. Here’s how.

ii. Before attempting any of this you will probably need to download and compile ffmpeg, a command line tool used for converting multimedia files between formats, most notably libavcodec. Here’s how.

2. Implementation

All that is needed to initiate the video capture is the cvCaptureFromAVI:

CvCapture* capture = cvCaptureFromAVI("infile.avi");

And to grab individual frames we simply use cvQueryFrame:

IplImage* frame = cvQueryFrame( capture );

cvGetCaptureProperty is used to return the frames per second so that we may control the speed at which individual frames get displayed.

Sample video output:

3. Code Listing

Here is the code listing used to display the sample video file, “SAMPLE.AVI“:

#include <cv.h>  
#include <cxcore.h>    
#include <highgui.h>    

int main()
{	   
    int key = 0;
 
    // Initialize camera and OpenCV image
    //CvCapture* capture = cvCaptureFromCAM( 0 );
    CvCapture* capture = cvCaptureFromAVI( "sample.avi" );	
    IplImage* frame = cvQueryFrame( capture );

    // Check 
    if ( !capture ) 
	{
        fprintf( stderr, "Cannot open AVI!\n" );
        return 1;
    }

	// Get the fps, needed to set the delay
    int fps = ( int )cvGetCaptureProperty( capture, CV_CAP_PROP_FPS );
 
    // Create a window to display the video
    cvNamedWindow( "video", CV_WINDOW_AUTOSIZE );
 
    while( key != 'x' ) 
	{
        // get the image frame 
		frame = cvQueryFrame( capture );
 
        // exit if unsuccessful
        if( !frame ) break;
       
        // display current frame 
        cvShowImage( "video", frame );
 
        // exit if user presses 'x'        
		key = cvWaitKey( 1000 / fps );
    }
 
    // Tidy up
    cvDestroyWindow( "video" );
    cvReleaseCapture( &capture );

	return 0;
}

4. Some caveats

Just to re-iterate, you may need to ensure that ffmpeg has been successfully installed in order to allow video encoding and video decoding in different formats. Not having the ffmpeg functionality may cause problems when trying to run this simple example and produce a compilation error like this:

Compiler did not align stack variables. Libavcodec has been miscompiled and may be very slow or crash. This is not a bug in libavcodec, but in the compiler. You may try recompiling using gcc >= 4.2. Do not report crashes to FFmpeg developers.

Also, please be advised that it is not possible to compile the sourcecode from ffmpeg in visual studio 2010.

5. If you still get problems

Try the various Windows builds for FFMPEG over at this website. For example, for a 64-bit PC running Windows 7 you may wish to try these builds. Download and extract the file, and insert a copy of the ffmpeg.exe file contained in the /bin subfolder inside the C++ project folder you are working on. This worked for me when I encountered simuilar difficulties.

Sample avi is downloadable from here.


Other posts related to image detection

Tracking Coloured Objects in Video using OpenCV
Analyzing FlyCapture2 Images obtained from Flea2 Cameras
Integrating the FlyCapture SDK for use with OpenCV
OpenCV Detection of Dark Objects Against Light Backgrounds
Getting Started with OpenCV in Visual Studio
Object Detection Using the OpenCV / cvBlobsLib Libraries

17 Comments

  1. Hi!
    excellent article and very usefull. I am working on a project displaying also avi files with opencv and I have two problems : I have no sound in the videos I display, and I am doing a certain image processing for each frame of the video and the video is being displaying very slowly. Do you now how can I improve any of those questions?
    Sorry for my english :p

    • Hi your English is fine. Thanks for your feedback. Are you saying you have no sound in your videos when there should be? I have not tackled this kind of problem before, so I don’t really have anything more to contribute yet. Have you trawled Google? Usually you will always find others who have encountered similar problems. If you get a solution let me know how you get on?

  2. Hi, thank you for this useful articule. I am working on a project in which I need to read a video file, extract frames from this video file in order to apply a watermark. I am still in the very beginnig of my project. I followed every step you mentioned above and i think that i have installed ffmepg correctly ( i am using a 32-bit 3Go RAM PC running windows 7).
    When trying to compile the example you gave i just get this “The program ‘[3640] loadVideo.exe: Native’ has exited with code 0 (0×0).” (of course with the task number changing every time i try to run the program)
    could you please help me resolving this?
    thanks!

    • Hi
      Native’ has exited with code 0 (0×0) means that everything went well and the thread exited correctly. Zero typically means ‘success’, non-zero typically means some kind of error.

      It may be helpful if you run this as a Windows Console application project.
      Cheers
      Andy

  3. Hello! First at all thank you for your post, actually I am using opencv with Eclipse in Ubuntu, my first program to learn was open a image, then I tried open a new video, because my original project is work with a camera, then I was using different code but the video can not open. I use your code but I see the message “Cannot open AVI!”, I don’t know if is because is necessary some library more, or what. I hope you can guide me. Thanks!

    • Hi

      Are you getting the video from a file or a camera?
      If from a file are you setting the path from where it needs to find the video file correctly?
      Don’t forget Windows and Linux file paths need to be set differently ie
      Windows might look like
      cvCaptureFromAVI(“C:\\mystuff\\sample.avi”);
      while Ubuntu Linux might look like
      cvCaptureFromAVI(“/home/mystuff/sample.avi”);
      Andy

  4. Hello Andy.
    I want to convert my video from color to grayscale. in each frame, I use cvCvtColor(frame, gray, CV_BGR2GRAY); to convert and then, display it. But it went in wrong with this error:
    Unhandled exception at 0x7c812aeb in avi_open.exe: Microsoft C++ exception: cv::Exceptioni at memory loacation 0x0011e280.
    Can you help me to solve this error, thank u very much.

      • i only insert a new line of fucntion cvCvtcolor into the sample code:

        #include “highgui.h”
        #include
        int main()
        {
        cvNamedWindow( “Example2″, CV_WINDOW_AUTOSIZE );
        CvCapture* capture = cvCreateFileCapture(“test.avi”);
        IplImage* frame;
        while(1)
        {
        frame = cvQueryFrame( capture );
        if( !frame ) break;
        IplImage* gray = cvCreateImage(cvSize(frame->width, frame->height),IPL_DEPTH_8U, frame->nChannels );
        cvCvtColor(frame, gray, CV_BGR2GRAY);
        cvShowImage( “Example2″, gray );
        char c = cvWaitKey(33);
        if( c == 27 ) break;
        }
        cvReleaseCapture( &capture );
        cvDestroyWindow( “Example2″ );
        }

        • Hello Kerry

          If you change the line:

          IplImage* gray = cvCreateImage(cvSize(frame->width, frame->height),IPL_DEPTH_8U, frame->nChannels );

          into:

          IplImage* gray = cvCreateImage( cvGetSize( frame ), 8, 1 );

          You will find that it works and produces your grayscale image without crashing.
          Andy

  5. Hello,

    One question. I want to capture frames at a very low rate of 1fps. I am using capture.set(CV_CAP_PROP_FPS,1) without any success. The frame rate is still stubbornly at 25fps.

    Any suggestions?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>