Saturday, December 27, 2014

Image processing Practicals - Part 3 (Capture a video from a file and analysing frames)

This post is about video processing basics using OpenCV. If you still haven't configured OpenCV in your computer, follow the first post of this post series.
Basically, a video is a series of images/frames. So most of the time, first we have to break the video in to series of frames in order to manipulate the video. We don't need to save all the frames in hard disk and take one by one. Instead of doing like that, OpenCV provides a way to capture the video frames real time. The following example is an example scenario.

Breaking a video into frames using OpenCV

This program is working as a simple video player.
There are two ways to capture the video in OpenCV. Capture from a file and capture from a camera. Following code captures a video from a file.
If you need to capture from a camera you need to change only the parameter given in line 7.
In this case line 7 will be changed to:

 VideoCapture capture(0);  

The parameter '0' indicates that we are using the default camera for capturing.

Run this code:

1:  #include <opencv2/core/core.hpp>  
2:  #include <opencv2/highgui/highgui.hpp>  
3:  #include <iostream>  
4:  using namespace std;  
5:  using namespace cv;  
6:  int main() {  
7:       VideoCapture capture("movie.mp4");  
8:       Mat frame;  
9:       if (!capture.isOpened())  
10:            throw "Error when reading file";  
11:       namedWindow("window", 1);  
12:       for (;;) {  
13:            capture >> frame;  
14:            if (frame.empty())  
15:                 break;  
16:            imshow("window", frame);  
17:            waitKey(20);  
18:       }  
19:       waitKey(0);  
20:  }  

Using a loop we can take frame by frame and display it in the window. So that makes a video player. By changing the parameter value for waitKey function (line 17),  we can change the speed of the video. So we can use that captured frame for image processing tasks.






0 comments:

Post a Comment