Open In App

OpenCV | Loading Video

This article aims to learn how to display a video in OpenCV. To do so is a simple task just like displayed as a single image. But here, this display of frames have to be read in a loop as a part of the sequence.

Lets’s understand the complete process line by line in detail.



Code :




CvCapture* capture = cvCreateFileCapture("...input\\video_file.avi");

cvCreateFileCapture() function takes name/path of the AVI file of the video (to be loaded as a parameter). Then a pointer to a CvCapture structure is returned. All the information about the video file is contained in this structure. The CvCapture structure gets initialised to the beginning of the video when created in this way.

Code :




frame = cvQueryFrame(capture);

The reading from video file begins once it is inside the while(1) loop. A pointer to a CvCapture structure is taken as an argument by the cvQueryFrame(). Then the next video frame is taken into the memory which is actually a part of CvCapture structure. And that particular frame requires the pointer. cvQueryFrame uses the already allocated memory present in the CvCapture structure, unlike the cvLoadImage that allocates actual memory for the image. Thus, calling a cvReleaseImage() is not necessary for this “frame” pointer. When the CvCapture structure is released, the frame image memory will be freed.



Code :




c = cvWaitKey(10);
  
if (c == 27)
    break;

Waiting for 10ms after the frame is displayed. c will be set to the ASCII value of the pressed key if a user hits that particular key. Otherwise, it is set to ‘-1’. If ESC key (having an ASCII value of 27) is pressed by the user, then the code will exit the read loop. Otherwise, after 10ms are passed, the loop is executed again.

Code : Display video using OpenCV.




// Using OpenCV to display video
  
#include <highlevelmonitorconfigurationapi.h>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\opencv.hpp>
  
using namespace cv;
using namespace std;
  
iint main(int argc, char** argv)
{
    // creating window
    cvNamedWindow("Display_video", CV_WINDOW_AUTOSIZE);
  
    // loading video
    CvCapture* capture = cvCreateFileCapture("..input\\tree.avi");
    IplImage* frame;
  
    while (1) {
        frame = cvQueryFrame(capture);
  
        if (!frame)
            break;
  
        cvShowImage("Display_video", frame);
  
        char c = cvWaitKey(0);
  
        if (c == 27)
            break;
    }
    cvReleaseCapture(&capture);
  
    // destroying window
    cvDestroyWindow("Display_video");
}

Output :

VIDEO OUTPUT IN THE DISPLAY WINDOW

In the code above we are actually controlling the speed of the video in a very intelligent manner, we are just relying on the timer in cvWaitKey() for controlling the pace of frames to load.


Article Tags :