C++版本的Opencv与matlab矩阵数据通过txt文件传递

最近需要用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 double
int 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 cols
function[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 col
function 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));
    end
end
fclose(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 col
Mat 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));
}

猜你喜欢

转载自www.cnblogs.com/xilu/p/9102770.html