本文通过opencv的VideoCapture来实现打开一个视频文件。
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main(int argc, char **argv)
{
/*open a video file*/
<strong>VideoCapture cap</strong>("/home/user/opencv-3.1.0/test/project1/build/video.mp4");
if(!<strong>cap.isOpened</strong>())
cout<<"fail to open!"<<endl;
/*get the total number of frame*/
int totalframe = <strong>cap.get</strong>(<strong>CV_CAP_PROP_FRAME_COUNT</strong>);
cout<<"the total number of frame is "<<totalframe<<endl;
/*specify the first frame to be captured*/
int firstframe = 0;
<strong>cap.set</strong>(<strong>CV_CAP_PROP_POS_FRAMES</strong>,firstframe);
cout<<"the first frame is "<<firstframe<<endl;
/*specify the last frame*/
int lastframe = totalframe - 1;
if(lastframe < firstframe)
{
cout<<"program bad"<<endl;
return false;
}
else
{
cout<<"the last frame is "<<lastframe<<endl;
}
/*get the rate of frame*/
double rate = <strong>cap.get</strong>(<strong>CV_CAP_PROP_FPS</strong>);
cout<<"the frame rate is "<<rate<<endl;
bool over = false;
/*used to store every frame*/
Mat frame;
/*specify a window name used to display every frame*/
<strong>namedWindow</strong>("frame window");
/*specify interval between two frames*/
int interval = 1000/rate;
int currentFrame = firstframe;
/*set the kernel of filter*/
int kernel_size = 3;
Mat kernel = <strong>Mat::ones</strong>(kernel_size,kernel_size,CV_32F)/(float)(kernel_size*kernel_size);
while(!over)
{
/*read next frame*/
if(!<strong>cap.read</strong>(frame))
{
cout<<"cap.read failed"<<endl;
return false;
}
/*filter*/
<strong>filter2D</strong>(frame,frame,-1,kernel);
/*show frame*/
<strong>imshow</strong>("frame window",frame);
cout<<"current frame is "<<currentFrame<<endl;
int c = <strong>waitKey</strong>(interval);
if((char) c == 27 || currentFrame >= lastframe)
{
over = true;
}
currentFrame++;
}
/*close capturing action*/
<strong>cap.release</strong>();
<strong>waitKey</strong>(0);
return 0;
}