我的待分类的图片是按照时间来保存的,所以分开保存的时候我会用时间来创建新的文件夹,把属于同一秒的图片分到同一个文件夹
`void CFileSeparationDlg::OnBnClickedButton2()
{
CString text;
GetDlgItemText(IDC_EDIT1, text);
USES_CONVERSION;
char* fileName= T2A(text);//读取需要分离的图片的路径CString->char*
std::vector <CString> imgNames;//用来保存图片的名字
readImgNamefromFile(fileName, imgNames);//读入图片名字到数组
CString str;
//MessageBox(str);
int Length = imgNames.size();//获取图片名字数组长度
//MessageBox(Length);
CString csPath;//保存图片的路径
string picture;//图片名字数组CString->string
string sttSave;//保存时的图片路径
for (int i = 0; i < Length; i++)
{
picture = CT2A(imgNames[i].GetString());//图片名字数组CString->string
string text2= CT2A(text.GetString());//需要分离的图片的路径CString->string
//string srtr = fileName + "\\\\" + picture;
cv::Mat img = cv::imread(text2 +"\\"+picture);//从指定路径读取图片,不能用fileName + "\\\\" + picture;因为filename是char*
//cv::imshow("ImageShow", img);//opencv显示图片
/* if (!img.data)
return -1;*/
int j = imgNames[i].GetLength();//每一个图片名字的长度
str = imgNames[i].Mid(0, j - 9);//去掉图片名字后缀
//MessageBox(str);
//if(Second.)
int nRet = std::count(Second.begin(), Second.end(), str);//容器中是否有该名字,没有则创建以该名字命名的文件夹并保存图片,若有,则保存图片
if(nRet==0)
{
//MessageBox(_T("bu存在"));
Second.push_back(str);//去掉图片名字后缀后的字符串入栈
GetDlgItem(IDC_EDIT2)->GetWindowText(csPath);
//MessageBox(csPath);
//csPath.Replace(_T("\\"), _T("\\\\"));
//csPath.Replace()
//MessageBox(csPath);
csPath = csPath + "\\" + str;
//MessageBox(csPath);
//CString m_FilePath(L"C:\\File");
if (FALSE == CreateDirectory(csPath, NULL))//创建以该名字命名的文件夹
{
if (ERROR_ALREADY_EXISTS == GetLastError())
{
TRACE("\n this path is invalid");
}
else
{
TRACE("\n this path is exists");
}
}
sttSave = CT2A(csPath.GetString());//保存时的图片路径CString->string
//MessageBox(stt);
// string temp = std::to_string(i);
string addname = temp + ".jpg";
//sttSave.append(addname);
string stt2 = sttSave + "\\"+ picture ;//在相应文件夹下保存图片
cv::imwrite(stt2, img);//写入图片
cv::waitKey(0);
}
else {
//MessageBox(_T("存在"));
GetDlgItem(IDC_EDIT2)->GetWindowText(csPath);
csPath = csPath + "\\" + str;
sttSave = CT2A(csPath.GetString());//保存时的图片路径CString->string
string stt2 = sttSave + "\\" + picture;//在相应文件夹下保存图片
cv::imwrite(stt2, img);//写入图片
cv::waitKey(0);
}
}
MessageBox(_T("分离图片操作完成!!!!!"));
}
`
以下是readImgNamefromFile函数的代码
void readImgNamefromFile(char* fileName, vector <CString> &imgNames)
{
// vector清零 参数设置
imgNames.clear();
WIN32_FIND_DATA file;
int i = 0;
char tempFilePath[MAX_PATH + 1];
char tempFileName[50];
// 转换输入文件名
sprintf_s(tempFilePath, "%s/*", fileName);
// 多字节转换
WCHAR wstr[MAX_PATH] = { 0 };
MultiByteToWideChar(CP_ACP, 0, tempFilePath, -1, wstr, sizeof(wstr));
// 查找该文件待操作文件的相关属性读取到WIN32_FIND_DATA
HANDLE handle = FindFirstFile(wstr, &file);
if (handle != INVALID_HANDLE_VALUE)
{
FindNextFile(handle, &file);
FindNextFile(handle, &file);
// 循环遍历得到文件夹的所有文件名
do
{
sprintf_s(tempFileName, "%s", fileName);
imgNames.push_back((file.cFileName));
// imgNames[i].Insert(0, 1);
i++;
} while (FindNextFile(handle, &file));
}
FindClose(handle);
}