1 #include <opencv2/core/core.hpp> 2 #include <opencv2/highgui/highgui.hpp> 3 #include <opencv2/imgproc/imgproc.hpp> 4 #include <iostream> 5 6 using namespace std; 7 using namespace cv; 8 9 int main() 10 { 11 //打开视频文件:其实就是建立一个VideoCapture结构 12 VideoCapture capture("D:/videos/PetsD2TeC2.avi"); 13 //检测是否正常打开:成功打开时,isOpened返回ture 14 if(!capture.isOpened()) 15 cout<<"fail to open!"<<endl; 16 //获取整个帧数 17 long totalFrameNumber = capture.get(CV_CAP_PROP_FRAME_COUNT); 18 cout<<"整个视频共"<<totalFrameNumber<<"帧"<<endl; 19 20 21 //设置开始帧() 22 long frameToStart = 300; 23 capture.set( CV_CAP_PROP_POS_FRAMES,frameToStart); 24 cout<<"从第"<<frameToStart<<"帧开始读"<<endl; 25 26 27 //设置结束帧 28 int frameToStop = 400; 29 30 if(frameToStop < frameToStart) 31 { 32 cout<<"结束帧小于开始帧,程序错误,即将退出!"<<endl; 33 return -1; 34 } 35 else 36 { 37 cout<<"结束帧为:第"<<frameToStop<<"帧"<<endl; 38 } 39 40 41 //获取帧率 42 double rate = capture.get(CV_CAP_PROP_FPS); 43 cout<<"帧率为:"<<rate<<endl; 44 45 46 47 //定义一个用来控制读取视频循环结束的变量 48 bool stop = false; 49 //承载每一帧的图像 50 Mat frame; 51 //显示每一帧的窗口 52 namedWindow("Extracted frame"); 53 //两帧间的间隔时间: 54 //int delay = 1000/rate; 55 int delay = 1000/rate; 56 57 58 //利用while循环读取帧 59 //currentFrame是在循环体中控制读取到指定的帧后循环结束的变量 60 long currentFrame = frameToStart; 61 62 63 //滤波器的核 64 int kernel_size = 3; 65 Mat kernel = Mat::ones(kernel_size,kernel_size,CV_32F)/(float)(kernel_size*kernel_size); 66 67 while(!stop) 68 { 69 //读取下一帧 70 if(!capture.read(frame)) 71 { 72 cout<<"读取视频失败"<<endl; 73 return -1; 74 } 75 76 //这里加滤波程序 77 imshow("Extracted frame",frame); 78 filter2D(frame,frame,-1,kernel); 79 80 imshow("after filter",frame); 81 cout<<"正在读取第"<<currentFrame<<"帧"<<endl; 82 //waitKey(int delay=0)当delay ≤ 0时会永远等待;当delay>0时会等待delay毫秒 83 //当时间结束前没有按键按下时,返回值为-1;否则返回按键 84 85 86 int c = waitKey(delay); 87 //按下ESC或者到达指定的结束帧后退出读取视频 88 if((char) c == 27 || currentFrame > frameToStop) 89 { 90 stop = true; 91 } 92 //按下按键后会停留在当前帧,等待下一次按键 93 if( c >= 0) 94 { 95 waitKey(0); 96 } 97 currentFrame++; 98 99 } 100 //关闭视频文件 101 capture.release(); 102 waitKey(0); 103 return 0; 104 }