利用OpenCV从一段视频中提取图片

最近在做一个目标检测的小项目,需要自己做点数据集,手里适合做数据集的资源是mp4视频的格式,于是想用C++写个脚本从视频里提取图片保存,并且可以自定义抽取频率。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream> 
#include <stdio.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv/cv.h>

using namespace cv;
using namespace std;

int main(int argc, char **argv)
{
Mat srcImg;
//视频文件路径
string filename = "video_path/xxx.mp4";
VideoCapture cap0;
cap0.open(filename);
long totalFrameNumber = cap0.get(CV_CAP_PROP_FRAME_COUNT);
cout << "整个视频共" << totalFrameNumber << "帧" << endl;
int countNums = 0;
int nameNum = 0;
//保存图片的路径
char imagename[100];
while (cap0.isOpened())
{
cap0 >> srcImg;
if (srcImg.empty())
{
cout << "提取进度: 100%"<< endl;
break;
}
//可以修改保存频率
if (countNums % 10 == 0)
{
nameNum++;
sprintf(imagename, "save_img_path/%d.jpg", nameNum);
imwrite(imagename, srcImg);
// imshow("srcImg", srcImg);
// waitKey(1);
cout << "提取进度: " << (countNums * 100)/totalFrameNumber << "%" << endl;
}
countNums++;
}
return 0;
}

附:从rosbag录制的视频中提取图片

1
rosrun image_view extract_images _sec_per_frame:=0.2 image:="image_topic"

_sec_per_frame是提取间隔,单位为秒