先通过文件操作获取当前文件下的所有文件名并存储,为方便处理先对路径名做“\”、“/”的转换,再用opencv读取.mp4文件,获得每一帧图片。
#include <iostream>
#include <io.h>
#include <string>
#include <vector>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
vector<string> files;
void getFiles(string path, vector<string>& files, string format)
{
//文件句柄
intptr_t hFile = 0; //不要用 long
//文件信息
struct _finddata_t fileinfo;
string p;
if ((hFile = _findfirst(p.assign(path).append("\\*" + format).c_str(), &fileinfo)) != -1)
{
do
{
//如果是目录,迭代之
//如果不是,加入列表
if ((fileinfo.attrib & _A_SUBDIR))
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
getFiles(p.assign(path).append("\\").append(fileinfo.name), files, format);
}
else
{
files.push_back(p.assign(path).append("\\").append(fileinfo.name));
}
//cout << fileinfo.name << endl;
}while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}
/**
* 字符串替换 将str中所有的src替换为dst
*/
void string_replaceAll(std::string &str, const std::string &src, const std::string &dst)
{
std::string::size_type pos = 0;
std::string::size_type srclen = src.size();
std::string::size_type dstlen = dst.size();
while ((pos = str.find(src, pos)) != std::string::npos)
{
str.replace(pos, srclen, dst);
pos += dstlen;
}
}
/******************读取本地视频*******************/
void VideoRead(string video_path)
{
//读取视频
VideoCapture capture(video_path);
//循环显示每一帧
while (1)
{
//frame存储每一帧图像
Mat frame;
//读取当前帧
capture >> frame;
//播放完退出
if (frame.empty()) {
printf("Play finished.\n");
break;
}
//实时显示当前帧
imshow("Frame", frame);
//延时20ms
waitKey(20);
}
}
void user(void)
{
printf("user.cpp file. \n");
//vector<string> files;
string path = "E:\\video\\test";
string format = ".mp4";
getFiles(path, files, format);
cout << files.size() << endl;
for (int i = 0; i < files.size(); i++)
{
// 替换字符串
string_replaceAll(files[i], "\\", "/");
cout << files[i].c_str() << endl;
VideoRead(files[i].c_str());
}
}
读到每帧图片后就可以愉快地对它做算法操作了。