C++版本的Opencv與matlab矩陣資料通過txt檔案傳遞

來源:互聯網
上載者:User

標籤:部分   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檔案傳遞

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.