#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
void readvideoandsaveimage(string video, string path)
{
VideoCapture capture(video);
long totalFrameNumber = capture.get(CV_CAP_PROP_FRAME_COUNT);
cout << "total frames is:" << totalFrameNumber << "." << endl;
//设置开始帧
long frameToStart = 1;
capture.set(CV_CAP_PROP_POS_FRAMES, frameToStart);
//设置结束帧
int frameToStop = 1000;
//获取帧率
double rate = capture.get(CV_CAP_PROP_FPS);
cout << "rate is:" << rate << endl;
double delay = 1000 / rate;
//定义一个用来控制读取视频循环结束的变量
bool stop = false;
long currentFrame = frameToStart;
if (!capture.isOpened())
{
cerr << "Failed to open a video" << endl;
return;
}
Mat frame;
int num = 1;
string filename;
char temp_file[15];
while (!stop)
{
capture >> frame;
if (frame.empty())
{
//break;
continue;
}
_itoa_s(num, temp_file, 4, 10); //4表示字符长度,10表示十进制,_itoa_s实现整型转字符串
filename = temp_file;
filename = path + filename + ".jpg";
imshow("Extractedframe", frame);
imwrite(filename, frame);
int c = waitKey(delay);
if ((char)c == 27 || currentFrame > frameToStop)
{
stop = true;
}
//按下按键后会停留在当前帧,等待下一次按键
if (c >= 0)
{
waitKey(0);
}
num++;
currentFrame++;
}
capture.release();
waitKey(0);
}
int main(int argc, char** argv)
{
string videoFromfile = "D:\images\1.mp4"; //读取视频
string Imagespath = "D:\images\2018-09-22\"; // 保存图片的文件夹路径一定要有,因为OpenCV不会自动创建文件夹
readvideoandsaveimage(videoFromfile, Imagespath);
return 0;
}
------------------------------------------------------------------运行效果: