今天又遇到了同样的问题,所以将代码贴出来,以后遇到同样问题省时省力
首先是读取一堆某种类型的图片文件:
<span style="font-size:18px;">#include<opencv2\opencv.hpp>
#include<iostream>
#include<vector>
#include<string>
#include"windows.h"
using namespace std;
/*****************用于批量处理的程序**************************/
/*************************************************************/
using namespace std;
typedef std::vector<std::string>file_lists;
static int str_compare(const void* arg1,const void* arg2)
{
return strcmp((*(std::string*)arg1).c_str(),(*(std::string*)arg2).c_str());//比较字符串arg1 and arg2
}
file_lists ScaneDirectory(const std::string &path,const std::string &extension)
{
WIN32_FIND_DATA wfd;//WIN32_FIND_DATA:Contains information about the file that is found by
//FindFirstFile,FindFirstFileEx,or FindNext function
HANDLE hHandle;
string searchPath,searchFile;
file_lists vFilenames;
int nbFiles=0;
//searchPath=path+"/*"+extension;
searchPath = path + "/*" + extension;
//hHandle=FindFirstFile(searchPath.c_str(),&wfd);
hHandle = FindFirstFile(searchPath.c_str(), &wfd);//Searches a directory for a file or subdirectory
if(INVALID_HANDLE_VALUE==hHandle)
{
//fprintf(stderr,"ERROR(%s,%d"):Cannot find(*.%s)files in directory %s/n",_FILE_,_LINE_,extension.c_str(),path.c_str());
fprintf(stderr, "ERROR(%s, %d): Cannot find (*.%s)files in directory %s/n",
__FILE__, __LINE__, extension.c_str(), path.c_str());
exit(0);
}
do
{
if(wfd.cFileName[0]=='.')
{
continue;
}
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
continue;
}
else//
{
//searchFile=path+"/"+ wfd.cFileName;
searchFile = path + "/" + wfd.cFileName;
vFilenames.push_back(searchFile);
nbFiles++;
}
}while (FindNextFile(hHandle,&wfd));
FindClose(hHandle);
qsort((void*)&(vFilenames[0]),(size_t)nbFiles,sizeof(string),str_compare);
return vFilenames;
}
int main(int argc,const char *argv[])
{
file_lists files=ScaneDirectory("E:/source_online/ck+label/7",".png");
if(files.empty())
{
cout<<"no image file find in current directory."<<endl;
//while (1);
system("pause");
exit(-1);
}
int size=files.size();
cout<<"there are"<<size<<"image files totally..."<<endl;
for(int i=0;i<size;i++)
{
cout<<files[i].c_str()<<endl;
//此处加载对图像的处理
Mat src=imread(files[i].c_str());
}
return 0;
}
</span>
在上面进行了“.png”图片的数量统计,同时可以通过Mat src=imread(file[i].c_str())读取每一个图片文件的存储路径。
接下来是怎样对一堆处理后的图片文件连续命名,并保存在同一个指定的文件路径下
其实很简单,就可以利用一下几句代码:
<span style="font-size:18px;">char fileName[100];//用于保存图片文件存储地址,可以根据需要随意设置
int image_number=0;//一个变化量,使得每张图片文件的名字不会重复
sprintf(fileName,"E:/graduate_work/za/flipTheImage/%d.jpg",image_number);//给处理的图片进行命名
imwrite(fileName,flip_image);//flip_image是需要保存的图片,fileName是存储所需的文件存储地址
image_number++;</span>
这样就可以安心使用了,不过唯一不确定的是这段代码的执行效率怎么样,但是效果还是能够达到,如果有什么问题可以留言给我,谢谢。