方法一:readdir(), 无需opencv
Linux可以直接readdir,然后用d_type来筛选合法文件。但在windows下没有d_type,windows可以用d_name的长度限制来排除非法文件。
下面代码在Linux和Windows平台均可使用,最终的图片名保存在vector数组中,若需要完整路径,使用字符串拼接即可。
/* Work for both Linux & Win */
#include <iostream>
#include <fstream>
#include <vector>
#include <dirent.h>
#include "sys/types.h"
using namespace std;
int main(){
const img_dir = "D:/XX/XXX";
vector<string> img_paths = get_img_files_dir(img_dir);
cout << "Successfully load " << img_paths.size() << " images." << endl;
/* 若要完整路径,每次取出图片名,进行字符串拼接即可 */
// 例如: const combined_dir = img_dir + "/" + img_paths[0];
return 0;
}
vector<string> get_img_files_dir(const string& directory)
{
vector<string> file_paths;
DIR* dir;
struct dirent* img_entry;
dir = opendir(directory.c_str());
if (dir == nullptr) {
cout << "Please check your Image File Path" << endl;
}
else {
while ((img_entry = readdir(dir)) != nullptr) {
/* WORK FOR LINUX */
#ifdef linux
if (file_name->d_type == DT_REG) {
file_paths.push_back(file_name->d_name);
}
#endif
/* WORK FOR WINDOWS */
#ifdef _WIN32//__WINDOWS_
string img_name = img_entry->d_name;
if (img_name.size() > 4) { //这部分长度限制可以自行调整
file_paths.push_back(img_entry->d_name);
}
#endif
}
closedir(dir);
}
return file_paths;
}
方法一参考:(143条消息) C/C++的readdir和readdir_r函数(遍历目录)_墨痕诉清风的博客-CSDN博客
方法二:opencv
下面代码需要先实现opencv的安装与配置,最终保存在vector数组中的是完整路径名,例如:"D:/XX/XXX/X.jpg"
#include <iostream>
#include <fstream>
#include <vector>
#include <opencv2/opencv.hpp>
using namespace std;
int main()
{
const string img_dir = "D:/XX/XXX";
vector<string> img_paths = get_img_files_dir(img_dir);
cout << "Successfully load " << img_paths.size() << " images for Inference." << endl;
cout << img_paths[0] << endl; //直接是完整路径:"D:/XX/XXX/X.jpg"
}
vector<string> get_img_files_dir(const string& directory)
{
string pattern = directory + "/*.*";
vector<string> file_paths;
cv::glob(pattern, file_paths, false);
return file_paths;
}
方法二参考:
(143条消息) C++把图片的文件名保存到数组里,opencv库glob()函数_opencv中glob函数_易小侠的博客-CSDN博客
vs+opencv配置教程:(推荐配在debug下,便于调试。如果出错,可尝试在链接器的附加依赖项中,只加opencv_worldxxxd.lib, 不加opencv_worldxxx.lib。带d的表示debug,不带d的表示release)