opencv读取视频的特定帧或每秒截取指定数量的图片

假如视频的帧率是30,时长50秒,则直接每一帧都保存一共会保存1500张图,这显然太多了。因此考虑如何每秒只截取一帧并进行处理。

代码如下:

#include <iostream>
#include <opencv2\highgui.hpp>
#include <opencv2\core.hpp>
#include <fstream>
#define SAVEPATH "C:/Users/z/Desktop/img_files/"
using namespace std;
using namespace cv;
int main()
{
string file = "C:/Users/z/Desktop/IMG_4380.mp4";
VideoCapture cap(file);
if (!cap.isOpened())
{
cout << "open video file failed." << endl;
}
int frame_cnt = 0;
int num = 0;
Mat img;

while (true)
{
bool success = cap.read(img);
if (!success)
{
cout<< "Process " << num << " frames from" << file << endl;
break;
}
if (img.empty())
{
cout << "frame capture failed." << endl;
break;
}

if (frame_cnt % 30 == 0)
{
++num;
string name = SAVEPATH + to_string(num) + ".jpg";
imwrite(name, img);
cout << "processed " << num << " frames.\n" << endl;
}
++frame_cnt;
}

cout << cap.get(CV_CAP_PROP_FRAME_COUNT) << endl;
cout << cap.get(CV_CAP_PROP_FPS) << endl;
cap.release();
return 0;

}


精华就在if (frame_cnt % 30 == 0)这一句。

此外,在while循环中加入waitKey(1000)做延时并不会起作用,因为至少有一次用到imgshow函数时waitKey才会起作用。

猜你喜欢

转载自blog.csdn.net/qq_38469553/article/details/80804506