Title: C/C++ <-> Matlab types convertor
Brief: Bidirectional conversion between C/C++ types (native, STL, openCV...) and Matlab matrix (compile or run time).
Key words: C, C++, mxArray, OpenCV, IplImage, iterator, mex, engine
Description:
Consider below scenarios (especially when programming with signal/speech/image processing and scientific computation):
1 Dumping C/C++ data into Matlab workspace in run-time to visualize data and facilitate debugging. But calling engine APIs directly seems not to be that convenient.
2 Implementing underlying algorithm as mex file to accelarate m file. Each time you must convert mxArray to C/C++ types, do some job, and finally convert C/C++ types back to returned mxArray.
This project provides easy access to above tasks given appropriate iterators (refer to any C++ STL textbook if iterator seems nothing to you).
As to scenario 1 see below examples:
/**************************
* EXAMPLE A for scenario 1
**************************/
unsigned char rgb_img[3*256*126]; // 3D signal, i.e. color image
// initialize rgb_img and do something to it...
const char* command = "figure; imshow(I)";
// Dump it as 3D matrix named I. column(width):256?row(height):126 and page(channel):3,
// then view it using matlab function "imshow".
matlab << name ("I")
<< width (256) << height (126) << channel (3)
<< start (rgb_img)
<< cmd (command);
Dump 1D and 2D signal goes similarly. Currently maximum 3D is supported.
Also openCV is supported. For example:
/**************************
* EXAMPLE B for scenario 1
**************************/
IplImage* pimg; // openCV image types
// initialize p and do something to it...
// Dump pimg as matrix I. The size and types are made the same as pimg automatically.
// Then view it.
matlab << name("I") << var(pimg) << cmd("figure;imshow(I)");
As to scenario 2 see below example:
/**************************
* EXAMPLE A for scenario 2
**************************/
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
vector<double> vt;
double val;
int n = (int) mxGetNumberOfElements(prhs[0]);
vt.resize(n);
// 1. convert mxArray to C/C++ types
mat_to_values (prhs[0], vt.begin());
mat_to_scalar (prhs[1], &val);
// 2. do some job to vt and val
// 3. finally convert C/C++ types back to mxArray
plhs[0] = values_to_new_mat (vt.begin(),vt.end());
}
mat_to_values and values_to_new_mat take pointer/iterator as input arguments, with appropriate iterator in hand you can also convert C native array, std::list or any other user data types (e.g. OpenCV IplImage).
For details, see more examples and the document in the zip file.
Have fun:) |