OpenCV中如何遍历特定路径下的文件
前言
在对图像文件进行处理时,常需要对特定文件夹下的文件进行处理,好在OpenCV中提供了自动查找的函数接口。本文将提供两种自动查找特定路径下文件的方法。
一、glob函数
OpenCV的glob函数可以用于搜索符合指定规则的文件路径列表。
glob函数的主要功能是将pattern路径下的所有文件名存进result中。其函数原型为:
void cv::glob(String pattern, std::vector< String > & result, bool recursive = false);
这里的pattern是你需要查找的文件路径,result是一个存储文件名的向量,recursive是一个可选参数,如果设置为true,glob函数会递归查找所有子目录。
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
std::vector<cv::String> filenames;
cv::String folder = "E:\\Images";
cv::glob(folder, filenames);
for (auto filename : filenames)
{
cout << filename << endl;
}
cout << endl;
cout << "***************************************************" << endl<<endl;
cv::glob(folder, filenames,true);
for (auto filename : filenames)
{
cout << filename << endl;
}
system("pause");
return 0;
}
测试结果:
二、自定义条件遍历函数
代码如下:
#include <iostream>
#include <string>
#include <io.h>
#include <vector>
using namespace std;
void get_need_file(string path, vector<string>& file, string ext)
{
intptr_t file_handle = 0;
struct _finddata_t file_info;
string temp;
if ((file_handle = _findfirst(temp.assign(path).append("/*" + ext).c_str(), &file_info)) != -1)
{
do
{
file.push_back(temp.assign(path).append("/").append(file_info.name));
} while (_findnext(file_handle, &file_info) == 0);
_findclose(file_handle);
}
}
int main()
{
string file_path1 = R"(E:/Images)";
string file_path2 = R"(E:/Images/10)";
vector<string> pngfiles{}, jpgfiles{};
string need_extension1 = ".png", need_extension2 = ".jpg";
get_need_file(file_path1,pngfiles, need_extension1);
get_need_file(file_path2, jpgfiles, need_extension2);
for (auto file : pngfiles)
{
cout<<file<< endl;
}
cout << "************************************" << endl;
for (auto file : jpgfiles)
{
cout << file << endl;
}
system("pause");
return 0;
}
测试结果