如果您创建了 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");