将数据从OpenCV矩阵发送到Matlab Engine,C ++

时间:2012-06-04 15:34:40

标签: c++ matlab opencv matlab-engine

我使用C ++和Matlab Engine将数据从OpenCV矩阵发送到matlab。我试图从专业列转换为行专业但我真的很困惑如何做到这一点。我无法理解如何处理Matlab指针mxArray并将数据放入引擎。

有没有人与OpenCV一起使用matlab发送矩阵?我没有找到太多信息,我认为这是一个非常有趣的工具。欢迎任何帮助。

1 个答案:

答案 0 :(得分:7)

如果你已经创建了matlab引擎,我有一个有效的功能。我所做的是为matlab引擎创建一个SingleTone模板:

我的标题如下:

/** Singletone class definition
  * 
  */
class MatlabWrapper
    {
    private:
        static MatlabWrapper *_theInstance; ///< Private instance of the class
        MatlabWrapper(){}           ///< Private Constructor
        static Engine *eng; 

    public:
        static MatlabWrapper *getInstance() ///< Get Instance public method
        {
            if(!_theInstance) _theInstance = new MatlabWrapper(); ///< If instance=NULL, create it

    return _theInstance;            ///< If instance exists, return instance
        }
    public:
    static void openEngine();               ///< Starts matlab engine.
    static void cvLoadMatrixToMatlab(const Mat& m, string name);
    };

我的cpp:

#include <iostream>
using namespace std;

MatlabWrapper *MatlabWrapper::_theInstance = NULL;              ///< Initialize instance as NULL    
Engine *MatlabWrapper::eng=NULL;
void MatlabWrapper::openEngine()
{
        if (!(eng = engOpen(NULL))) 
        {
            cerr << "Can't start MATLAB engine" << endl;
            exit(-1);
        }       
}
void MatlabWrapper::cvLoadMatrixToMatlab(const Mat& m, const string name)
{
    int rows=m.rows;
    int cols=m.cols;    
    string text;
    mxArray *T=mxCreateDoubleMatrix(cols, rows, mxREAL);

    memcpy((char*)mxGetPr(T), (char*)m.data, rows*cols*sizeof(double));
    engPutVariable(eng, name.c_str(), T);
    text = name + "=" + name + "'";                    // Column major to row major
    engEvalString(eng, text.c_str());
    mxDestroyArray(T);
}

如果要发送矩阵,例如

Mat A = Mat::zeros(13, 1, CV_32FC1);

这很简单:

MatlabWrapper::getInstance()->cvLoadMatrixToMatlab(A,"A");