读取一个文件夹下符合要求的图像可以使用opencv3.2中的函数glob,函数定义如下:
CV_EXPORTS void glob(String pattern, std::vector<String>& result, bool recursive = false);
第一个参数时文件所在的路径,第二个参数是存放文件路径的容器,第三个参数的作用是:当recursive为false时,只遍历指定文件夹内符合模式的文件,当recursive为true时,会同时遍历指定文件夹下的子文件夹。
例子如下,读取一个文件夹中的tif文件并显示
#include <iostream> #include <opencv2/opencv.hpp> using namespace cv; using namespace std; int main() { vector<String> files; //存放文件路径 vector<Mat> images; //存放文件数据 glob("E:/桌面/例子/*.TIF", files, true); //读取文件夹下所有符合要求的文件路径 size_t num = files.size(); //读取的符合条件的文件个数 cout << "读取了" << num << "个图像" << endl; for (int i = 0; i < num; i++) { cout << "第" << i + 1 << "个文件的路径是:" << files[i] << endl; } for (int i = 0; i < num; i++) { Mat img = imread(files[i], IMREAD_GRAYSCALE); //读取灰度图像 if (img.empty()) { cerr << files[i] << " can't be loaded!" << endl; continue; } images.push_back(img); //将图像数据存入images中 } for (int i = 0; i < num; i++) { string name = format("%d", 1 + i); //显示图像 imshow(name, images[i]); } waitKey(); return 0; }
结果如下: