opencv中有一个工具类Directory:它可以遍历对应文件夹下的所有文件,帮助读取文件夹下的所有文件名;
【注意是opencv2.0版本才有这个函数,opencv3.0中没这个函数了。。。】
Directory工具类中包含三个函数接口,分别是:
static std::vector< std::string > GetListFiles (const std::string &path, const std::string &exten="*", bool addPath=true)
static std::vector< std::string > GetListFilesR (const std::string &path, const std::string &exten="*", bool addPath=true)
static std::vector< std::string > GetListFolders (const std::string &path, const std::string &exten="*", bool addPath=true)
这三个函数都是static,函数只获取指定目录下的文件, 不理会目录。
(1) GetListFiles:遍历指定文件夹下的所有文件,不包括指定文件夹内的文件夹;
(2) GetListFolders:遍历指定文件夹下的所有文件夹,不包括指定文件夹下的文件;
(3) GetListFilesR:遍历指定文件夹下的所有文件,包括指定文件夹内的文件;这个R代表的recursive的意思,就是碰到文件夹还是往里钻。
path:string, 用于指定根目录
exten: string,这个是个正则表达式,匹配的返回,否则不返回。
addPath: bool,如果为true,返回的文件名会带path,如果为false,返回的仅是文件名;
简单示例:【读取某文件夹下的所有文件夹名,遍历每个文件夹中的图像;保存在指定路径下,按照对应文件夹保存】
std::string savepath = "xxx/data/out/";
std::string path0 = "xxx/data/in/";//注意最后的反斜杠
std::string exten0 = "*";
bool addPath0 = false;
cv::Directory dir;
std::vector<cv::String> foldernames = dir.GetListFolders(path0, exten0, addPath0);
for (int fi = 0; fi < foldernames.size(); fi++)
{
std::string foldername = path0 + foldernames[fi] + "/image/";
std::cout<<"\n\nProcessing Folder : "<< foldernames[fi] <<std::endl;
std::string path1 = foldername;
std::string exten1 = "*.png";
bool addPath1 = false;
vector<string> filenames = dir.GetListFiles(path1, exten1, addPath1);
for (int i = 0; i < filenames.size(); i++)
{
cv::Mat test = imread(foldername + filenames[i], cv::IMREAD_GRAYSCALE);//以灰度图格式读入
//sprintf(path, "%s%s", foldername.c_str(),filenames[i].c_str());
//cv::Mat test = imread(path, cv::IMREAD_GRAYSCALE);
cv::imshow("test ", test );
cv::waitKey(1);
std::string savepathout = savepath + foldernames[fi];//保存
_mkdir(savepathout.c_str());
cv::imwrite(savepathout + "/" + filenames[i], test);
}
}