1. 前言
之前用_finddata_t结构体做的C++文件夹遍历程序在Win10 VS2015环境下不能使用了,找了半天没找到原因,突然在网上看到使用Opencv也可以实现文件夹遍历的功能,这里对其进行了总结,主要分为3.0之前的版本和之后的版本。
2. Opencv 2X实现
在Opencv 2X的版本中包含了contrib模块,其里面封装了一个Directory类,用该类就可以实现对于目录的遍历操作,在该内部包含了三个成员函数:
1)GetListFiles:遍历指定文件夹下的所有文件,不包括指定文件夹内的文件夹;
2)GetListFolders:遍历指定文件夹下的所有文件夹,不包括指定文件夹下的文件;
3)GetListFilesR:遍历指定文件夹下的所有文件,包括指定文件夹内的文件夹。
class CV_EXPORTS Directory
{
public:
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);
};
使用示例:
#include <contrib.hpp>
cv::Directory dir;
//case1:
std::string path1 = "E:\\src_imgs\\";
std::string exten1 = "*.jpg";
bool addPath1 = false;//true;
std::vector<std::string> filenames = dir.GetListFiles(path1, exten1, addPath1);
std::cout<< "file names: "<< std::endl;
for (auto file : filenames)
std::cout<< file << std::endl;
//case2:
std::string path2 = "E:\\src_imgs\\";
std::string exten2 = "*";
bool addPath2 = true;//false
std::vector<std::string> foldernames = dir.GetListFolders(path2, exten2, addPath2);
std::cout << "folder names: "<< std::endl;
for (auto folder : foldernames)
std::cout << folder << std::endl;
//case3
std::string path3 = "E:\\src_imgs\\";
std::string exten3 = "*";
bool addPath3 = true;//false
std::vector<std::string> allfilenames = dir.GetListFilesR(path3, exten3, addPath3);
std::cout <<"all file names: "<< std::endl;
for (auto file: allfilenames)
std::cout<< file << endl;
3. Opencv 3X实现
在版本转换到3X的时候,其内部已经不再默认包含contrib模块了,需要自己编译进去,所以这里使用的函数是glob函数,其函数原型为:
CV_EXPORTS void glob(String pattern, std::vector<String>& result, bool recursive = false);
参数解释:
String pattern :需要遍历的路径的地址,其中包含搜索的类型通配符;
std::vector& result :结果的存储引用
bool recursive = false:是否递归查找
使用示例:
#include <opencv2/opencv.hpp>
#include <vector>
#include <string>
int main()
{
std::string src_path = "E:\\ src_imgs\\";
std::vector<cv::String> file_vec;
cv::glob(src_path+"*.jpg", file_vec, false);
for (std::string file_name : file_vec)
{
std::cout << file_name << std::endl;
}
return 0;
}
469




被折叠的 条评论
为什么被折叠?



