使用Dlib进行人脸标注时需要遍历所有的png格式的文件,可使用以下代码获取:
int getAllFiles(string path, vector<string>& files)
{
intptr_t hFile = 0;
struct _finddata_t fileinfo;
string p;
if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
{
do
{
if ((fileinfo.attrib & _A_SUBDIR))
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
{
if (CheckPostFix(fileinfo.name) == true)
{
files.push_back(p.assign(path).append("\\").append(fileinfo.name));
}
getAllFiles(p.assign(path).append("\\").append(fileinfo.name), files);
}
}
else
{
if (CheckPostFix(fileinfo.name) == true)
{
files.push_back(p.assign(path).append("\\").append(fileinfo.name));
}
}
} while (_findnext(hFile, &fileinfo) == 0);
}
_findclose(hFile);
return 0;
}
bool CheckPostFix(char* pFileName)
{
if (pFileName == nullptr)
{
return false;
}
std::string strFileName = pFileName;
int nStartPos = strFileName.rfind(".");
if (nStartPos == -1)
{
return false;
}
std::string strPostFix = strFileName.substr(strFileName.rfind("."));
if (strPostFix.find(".png") == std::string::npos)
{
return false;
}
return true;
}
包含的头文件:
#include <iostream>
#include<vector>
#include <io.h>
调用方法:
std::vector<std::string> filePaths;
getAllFiles(ImgDir, filePaths);
这样所有的png文件的路径都保存在filePaths里,通过遍历这个vector即可对每一个图片进行处理。
另外通过修改CheckPostFix函数里的后缀格式即可搜索不同格式的文件。
最近在Ubuntu上有测试了一下,会有找不到io.h的问题,即使包含了<sys/io.h>编译也会有问题,因此可以通过以下方式来获取文件名:
#include <sys/types.h>
#include <dirent.h>
#include <vector>
#include <string.h>
void getAllFiles(std::string path, std::vector<std::string>& filenames)
{
DIR *pDir;
struct dirent* ptr;
if(!(pDir = opendir(path.c_str())))
return;
while((ptr = readdir(pDir))!=0)
{
if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0)
{
if (CheckPostFix(ptr->d_name) == true)
{
filenames.push_back(path + "/" + ptr->d_name);
}
}
}
closedir(pDir);
}