標籤:部分 import getline not while printf 通用 pre template
最近需要用matlab和C++協同工作,為了規避代碼從matlab轉化為C++,只能轉化資料。(我也轉化過代碼,發現matlab對於矩陣的計算還是更方便而且快捷)
Opencv 中對於資料的儲存好像只有xml、yml等特定格式的檔案,而matlab不太容易讀取此類檔案。於是,我參考了一些網上的方法,寫了一個通用版本。
包括兩個部分,opencv寫,matlab讀 與 matlab寫,opencv讀。此為小兒科,單純的記錄一下,以後直接拿來用即可。
註:為了方便,txt為一列,前兩行分別是行數和列數。
1.opencv寫,matlab讀
//@brief save Mat to txt files //the Mat type must be doubleint Mat2txt(Mat D, string txt_name){ D.convertTo(D, CV_64FC1); ofstream fout; fout.open("txt_name"); fout << D.rows << endl; fout << D.cols << endl; for (int i = 0; i < D.rows; i++) { for (int j = 0; j < D.cols; j++) { fout << D.ptr<double>(i)[j] << endl; } } fout << flush; fout.close(); return 0;}
%the txt must be one col%and the first and second num must be the rows and colsfunction[data]=txt2mat(txt_name)txt_data=importdata(txt_name);r=txt_data(1);c=txt_data(2);data=txt_data(3:end);data=reshape(data,[c,r])‘;end
2.matlab寫,opencv讀
%the txt must be one colfunction mat2txt(txt_name)fid=fopen(txt_name,‘wt‘);[r,c]=size(A);fprintf(fid,‘%f\n‘,r);fprintf(fid,‘%f\n‘,c);for i=1:1:r for j=1:1:c fprintf(fid,‘%f\n‘,A(i,j)); endendfclose(fid);end
//@brief string to num(int,double...)//#include <sstream> template <class Type>Type stringToNum(const string& str){ istringstream iss(str); Type num; iss >> num; return num;}//@brief get the txt file from matlab//the data saved in txt must be one colMat txt2Mat(string txt_name){ ifstream fin; fin.open(txt_name); if (!fin.is_open()) { cout << "the file can not be opened!" << endl; } string temp; Mat A; int line = 0; int r = 0; int c = 0; while (getline(fin, temp)) { line++; if (line == 1) { r = stringToNum<int>(temp); } else { if (line == 2) c = stringToNum<int>(temp); else { A.push_back(stringToNum<double>(temp)); } } } fin.close(); OPENCV_ASSERT(A.rows == r*c, "TestCvError", "the size doesnt match!"); return (A.reshape(0, r));}
C++版本的Opencv與matlab矩陣資料通過txt檔案傳遞