首先我的CSV文件是这样的:
//************************************
// Method: ReadCsv
// FullName: CFaceRecognition::ReadCsv
// Access: protected
// Returns: void
// Qualifier:
// Parameter: const string & filename 文件路径
// Parameter: cv::vector<Mat> & images 存放图片的vector
// Parameter: cv::vector<int> & labels 存放标签的vector
// Parameter: char separator 分隔符
//************************************
void CFaceRecognition::ReadCsv(const string& filename, cv::vector<Mat>& images, cv::vector<int>& labels, char separator)
{
std::ifstream file(filename.c_str(), ifstream::in);
if (!file)
{
string error_message = "No valid input file was given, please check the given filename.";
CV_Error(CV_StsBadArg, error_message);
}
string line, path, classlabel;
while (getline(file, line))
{
stringstream liness(line);
getline(liness, path, separator);
getline(liness, classlabel);
if (!path.empty() && !classlabel.empty()) {
Mat image = imread(path, CV_LOAD_IMAGE_GRAYSCALE);
images.push_back(image);
labels.push_back(atoi(classlabel.c_str()));
}
}
file.close();
}
下面是保存图片并且更新CSV文件,不需要保存图片,将相关代码去掉即可:
//************************************
// Method: SaveGrayMatAndUpdateCSV 保存图片并更新CSV文件
// FullName: CFaceRecognition::SaveGrayMatAndUpdateCSV
// Access: protected
// Returns: void
// Qualifier:
// Parameter: const vector<Mat> images
// Parameter: const vector<int> labels
//************************************
void CFaceRecognition::SaveGrayMatAndUpdateCSV(const vector<Mat> images, const vector<int> labels)
{
string strFaceLibrary = "E:/att_faces/";
string strFolderName = strFaceLibrary + m_strRegisterFace2Name;
// 为图片创建必要的目录
CFileEx::CreateFolderForFile(strFolderName.c_str());
// // 将图片路径更新到csv文件中
ofstream StreamToFile("face.csv", ofstream::app);
if (!StreamToFile)
{
string error_message = "No valid input file was given, please check the given filename.";
CV_Error(CV_StsBadArg, error_message);
}
for (int i =0;i<images.size();i++)
{
// CFileEx::Separator()为分隔符,对于windows返回'\\',linux返回'/'。
string strFaceImgPath = strFolderName + CFileEx::Separator() + std::to_string(i+1) + ".bmp";
// 保存图片
bool bFlag = imwrite(strFaceImgPath, images[i]);
// 更新CSV文件
string strCSVAppendCon = strFaceImgPath + ";";
strCSVAppendCon += std::to_string(labels[i]);
StreamToFile << strCSVAppendCon << endl;
}
StreamToFile.close();
}