void glob(String pattern, std::vector<String>& result, bool recursive = false);
当recursive为false时,仅仅遍历指定文件夹内符合模式的文件,当recursive为true时,会同时遍历指定文件夹的子文件夹。
由于glob遍历图像名称不是按顺序进行遍历的;在读取图像序列的时候经常要按顺序读取,如在多目标跟踪中;这时可以sort进行排序;
#include<iostream> #include<vector> #include<opencv2/opencv.hpp> #include<string> using namespace std; using namespace cv; //自定义排序函数 bool sortFun(const cv::Point2d &p1, const cv::Point2d &p2) { return p1.x < p2.x;//升序排列 } void main() { vector<String> imgFiles; vector<string> imgNames_; string imgsDir = "C:\\Users\\23913\\Desktop\\bottle_test_data\\JPEGImages"; string pattern = imgsDir + "/" + string("*.jpg"); glob(imgsDir, imgFiles, false); size_t count = imgFiles.size(); if (count == 0) { cout << "this dir has no jpg!" << endl; return; } cout << "the num of jpgs:" << count << endl; for (int i = 0; i < count; i++) { //获取不带路径的文件名字 size_t pos = imgFiles[i].find_last_of("/") + 1; string imgName = imgFiles[i].substr(pos, imgFiles[i].length() - pos); cout << imgName << endl; //获取不带后缀名的文件名 string imgName_ = imgName.substr(0, imgName.rfind(".")); imgNames_.emplace_back(imgName_); } sort(imgNames_.begin(), imgNames_.end(), [](string a, string b) {return stoi(a) < stoi(b); }); for (int i = 0; i < imgNames_.size(); i++) { cout << imgNames_[i] << endl; } getchar(); }