需要用到结构体_finddata_t,定义在“io.h”.函数_findfirst、_findnext和_fineclose
具体可见:http://qiaoxinwang.blog.163.com/blog/static/86096452010612139172
下面是一个读取文件的demo,功能是将test_rs中读取所有图片,存入test_rsk:
#include <fstream>
#include <string>
#include <iostream>
#include <stdio.h>
#include <opencv2/opencv.hpp>
#include <io.h>
using namespace std;
using namespace cv;
void getFiles(string path, vector<string>& files)
{
//文件句柄
long 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)
getFiles(p.assign(path).append("\\").append(fileinfo.name), files);
}
else
{
files.push_back(p.assign(path).append("\\").append(fileinfo.name));
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}
int main() {
char * filePath = "H:\\VOC2007\\ganhuo\\test_rs";
vector<string> files;
getFiles(filePath, files);
int size = files.size();
cout << size << endl;
size_t pos = files[1].find(string("test_rs"));
cout << files[1] << endl;
if (pos != string::npos) {
cout << pos << endl;
}
char buffer[100];
char buffer1[100];
for (int i = 0; i<size; i++)
{
//将数字字母拼接在一起得到读取文件的路径
//sprintf(buffer, "H:\\VOC2007\\ganhuo\\train1_rs\\%s", files[i]);
//从指定路径buffer中读取图片
Mat img = imread(files[i]);
//cout << img.channels() << endl;
//置换路径
files[i].replace(files[i].find("test_rs"), 7, "test_rsk");
//保存灰度图像到指定路径
imwrite(files[i], img);
}
//while (1);
return 0;
}