目錄
注:原創不易,轉載請務必注明原作者和出處,感謝支持!
保存視頻中的幀
利用OpenCV提供的VideoCapture類可以輕松實現保存視頻中幀的功能。下面代碼可以將一個視頻文件中的所有幀抽取並保存成JPG圖像。
videoName
- 視頻文件名
imagePath
- 圖片保存的路徑
imagePrefix
- 圖片文件前綴字符串
圖片完整路徑:imagePath + "/" + imagePrefix + to_string(i) + ".jpg"
void ExtractFrames(const string &videoName, const string &imagePath, const string &imagePrefix)
{
VideoCapture cap;
Mat img;
// 打開視頻
cap.open(videoName);
if (!cap.isOpened())
{
cout << "Error : could not load video" << endl;
exit(-1);
}
// 取得視頻幀數
size_t count = (size_t)cap.get(CV_CAP_PROP_FRAME_COUNT);
for (size_t i = 0; i < count; ++i)
{
cap >> img;
string imgName = imagePath + "/" + imagePrefix + to_string(i) + ".jpg";
// 將當前幀保存
imwrite(imgName, img);
cout << "Frames " << i << " ... done" << endl;
}
}
ExtractFrames
調用實例:
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char *argv[])
{
ExtractFrames("E:/images/video/1.mp4", "E:/images/video", "red-forest");
return 0;
}
抽取出的圖片將被保存為:
red-forest0.jpg
red-forest1.jpg
red-forest2.jpg
...
red-forest45.jpg