2012-06-04 8 views
7

Sto inviando dati da matrici OpenCV a MATLAB utilizzando C++ e Matlab Engine. Ho provato a convertire dalla colonna principale alla riga principale, ma sono davvero confuso su come farlo. Non riesco a capire come gestire il puntatore Matlab mxArray e inserire i dati nel motore.Invio di dati da OpenCV matrix a Matlab Engine, C++

Qualcuno ha collaborato con OpenCV con MATLAB per inviare matrici? Non ho trovato molte informazioni e penso che sia uno strumento davvero interessante. Qualsiasi aiuto sarà gradito.

+0

vale la pena controllare [mexopencv] (https://github.com/kyamagu/mexopencv), un progetto che espone OpenCV in MATLAB come funzioni MEX – Amro

risposta

7

Ho una funzione che funziona se è stato creato il motore MATLAB. Quello che faccio è la creazione di un modello di Singletone per il motore di MATLAB:

Il mio colpo di testa si presenta così:

/** 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); 
    }; 

mio 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); 
} 

Quando si desidera inviare una matrice, ad esempio

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

è così semplice come questo:

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