由于人脸测试需要,我计划通过csv文件来保存人脸的特征向量
每一个人脸的特征向量有128维,测试存放5000个,所以csv是5000*128的浮点数
先随机生成数据,每一维都落在(-1.0,1.0)之间
#include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> #include <random> using namespace std; int main(){ std::random_device rd; //obtain a seed std::mt19937 gen(rd()); //mersenne_twister_engine std::uniform_real_distribution<> dist(-1.0, 1.0); ofstream outFile; outFile.open("test5000.csv", ios::out); // 5000*128 for(int i=1;i<=5000;i++){ for(int j=1;j<=127;j++){ outFile << dist(gen) << ','; } outFile <<dist(gen) <<endl; } outFile.close(); }
读取数据到二维向量a:
#include <iostream> #include <fstream> #include <string> #include <vector> #include<algorithm> using namespace std; vector<vector<float> >a; //二维数组存储读入变量 vector<float>b; inline void file_to_string(vector<string> &record, const string& line, char delimiter); inline float string_to_float(string str); void read() { vector<string> row; string line; string filename; ifstream in("test5000.csv"); if (in.fail()) { cout << "File not found" <<endl; return ; } while(getline(in, line) && in.good() ) { file_to_string(row, line, ','); //把line里的单元格数字字符提取出来,“,”为单元格分隔符 for(int i=0, leng=row.size(); i<leng; i++){ b.push_back(string_to_float(row[i])); } a.push_back(b); b.clear(); } in.close(); return ; } inline void file_to_string(vector<string> &record, const string& line, char delimiter) { int linepos=0; char c; int linemax=line.length(); string curstring; record.clear(); while(linepos<linemax) { c = line[linepos]; if(isdigit(c)||c=='.'){ curstring+=c; } else if(c==delimiter&&curstring.size()){ record.push_back(curstring); curstring=""; } ++linepos; } if(curstring.size()) record.push_back(curstring); return; } inline float string_to_float(string str){ int i=0,len=str.length(); float sum=0; while(i<len){ if(str[i]=='.') break; sum=sum*10+str[i]-'0'; ++i; } ++i; float t=1,d=1; while(i<len){ d*=0.1; t=str[i]-'0'; sum+=t*d; ++i; } return sum; } int main(){ read(); printf("total numbers of people: %d ",a.size()); cout<<"top 5dims of person 1:"<<endl; for(int i=0;i<=4;i++) cout<<a[0][i]<<" "; return 0; }