OpenCV批量读取文件夹下的文件
批量处理图片时,可以使用OpenCV遍历文件夹下的文件来实现,OpenCV在2.X和3.X版本有较大的改动,所以有些功能并不通用。以下是在OpenCV2.X和3.X中较为简单的遍历方法。
在OpenCV 2.X的版本中包含了contrib模块,里面封装了一个Directory类,用该类就可以实现对于目录的遍历操作,在该内部包含了三个成员函数:
1)GetListFiles:遍历指定文件夹下的所有文件,不包括指定文件夹内的文件夹;
2)GetListFolders:遍历指定文件夹下的所有文件夹,不包括指定文件夹下的文件;
3)GetListFilesR:遍历指定文件夹下的所有文件,包括指定文件夹内的文件夹。
使用该方法遍历文件夹下的文件时比较简单:
#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:\\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;
.
在版本转换到OpenCV3.X的时候,其内部已经不再默认包含contrib模块了,需要自己编译进去,所以这里使用的函数是自带的glob函数:
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace cv;
using namespace std;
int main()
{
string pattern_tif = "D:\\Photo\\*.tif";//要遍历文件的路径及文件类型
vector<cv::String> image_files;
glob(pattern_tif, image_files,false);//三个参数分别为要遍历的文件夹地址;结果的存储引用;是否递归查找,默认为false
if (image_files.size() == 0)
{
cout << "No image files[jpg]" << endl;
return 0;
}
else
{
for (int i = 0; i< image_files.size(); i++)//image_file.size()代表文件中总共的图片个数
{
Mat image = imread(image_files.at(i));
imshow("1", image);
waitKey(60);
}
}
}
在使用时需要注意所使用的的OpenCV是哪个版本的,2.X和3.X的区别还是比较大的。以上是两种比较简单批量处理文件夹下问价的方法。