#include <opencv2/opencv.hpp>
#include <windows.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include <ctime>
#include <windows.h>
#include <istream>
#include <fstream>
using namespace std;
using namespace cv;
#define USE_DEFINE_FUNCTION
static void updateImgProc();
static void readImgNamefromFile(char* fileName, vector <string> &imgNames);
static string renameImg(string oldName);
int main()
{
//重命名函数
updateImgProc();
system("pause");
return 0;
}
//更新图片名字
static string renameImg(string oldName)
{
char tmpChar1[300]={"0",};
char forwardPart[300]={"0",};
char backPart[100]={"0",};
char newNameChar[400]={"0",};
string newName;
strcpy(tmpChar1, oldName.c_str());
newName.resize(200);
int nameLen=strlen(tmpChar1);
int pos1=nameLen;
int pos2=nameLen;
while(pos1>0){
pos1--;
if(tmpChar1[pos1]=='.'){
break;
}
}
while(pos2>0){
pos2--;
if(tmpChar1[pos2]=='_'){
pos2++;
break;
}
}
if(pos1-pos2 == 3){
memcpy(forwardPart, oldName.data(), pos2);
memcpy(backPart, oldName.data()+pos2, 8);
sprintf(newNameChar, "%s0%s", forwardPart, backPart);
newName=newNameChar;
}else{
newName.assign(oldName);
}
return newName;
}
//循环处理多个文件夹
void updateImgProc()
{
const char* videoListFileName = "..\\files.txt";
ifstream videoListFile(videoListFileName);
string videoFileName;
int videoTotalCnt = 0;
if (videoListFileName)
{
while(getline(videoListFile, videoFileName))
{
if (videoFileName.empty()) {
continue;
}
videoTotalCnt++; //统计files.txt行数
}
cout<<"txtLines = "<<videoTotalCnt<<endl;
}
videoListFile.clear();
ifstream videoFile(videoListFileName);
//循环处理多个文件夹
for(int videoCnt = 0; videoCnt < videoTotalCnt; videoCnt++)
{
string videoFileName;
videoFile>>videoFileName;
//读原图片文件夹
vector<string> srcImgNames;
string newName;
char* srcFileName = (char *)videoFileName.c_str();
readImgNamefromFile(srcFileName, srcImgNames);
int needRenamedImgNum=0;
for (int i=0; i<srcImgNames.size(); i++)
{
newName = renameImg(srcImgNames[i]);
#ifdef USE_DEFINE_FUNCTION
//使用自己写的重命名函数,即使只是简单打开再重写,也会存在失真问题
if (strlen(srcImgNames[i].c_str()) != strlen(newName.c_str()))
{
cout<<srcImgNames[i]<<endl;
cout<<newName<<endl<<endl;
Mat srcImg = imread(srcImgNames[i].c_str());
if (srcImg.empty()) {
cout<<"read frame failed!";
}
imwrite(newName.c_str(), srcImg);
DeleteFile(srcImgNames[i].c_str()); //删除原mat
needRenamedImgNum++;
}
#else
//使用opencv自带的rename函数,不用打开再保存图片,避免图像失真
rename(srcImgNames[i].c_str(),newName.c_str());
#endif
}
cout<<needRenamedImgNum<<endl;
}
}
//读取文件夹中所有图片
void readImgNamefromFile(char* fileName, vector <string> &imgNames)
{
imgNames.clear();
WIN32_FIND_DATA file;
int i = 0;
char tempFilePath[MAX_PATH+1];
char tempFileName[500];
sprintf (tempFilePath, "%s/*.jpg", fileName);
HANDLE handle = FindFirstFile(tempFilePath , &file);
if(handle != INVALID_HANDLE_VALUE)
{
do
{
sprintf(tempFileName, "%s", fileName);
imgNames.push_back(file.cFileName);
imgNames[i].insert(0, tempFileName);
i++;
} while(FindNextFile(handle, &file));
}
FindClose(handle);
}