How do I interprete a greyscale matlab image passed to my c++ mexFunction
Here is my project, I have a GUI that loads images and I need to pass 开发者_如何学Cthis image and several information to my mexFunction coded in C++, like xSize, ySize, window size for processing. I am having trouble to interprete the information that matlabs gives me and I am not sure how to actually do it too.
Did you check the type of the data of your matrix?
I think that imread
returns a matrix of size m*n*3 of type uint8.
try taking the example above and change the definition of input
to:
unsigned char *input;
(since double
takes four times the memory is uint8
you get memory exceptions when you treat the pointer as pointer to double
).
When you pass any matrix to a MEX function, it is stored as a 1D array in a column-major order. Thus it is fastest to access it sequentially using linear indices.
In the case of an image, you can access it as a 2D matrix if you prefer, you just need to map row/column indices to linear indices with a simple calculation.
Consider this example:
matrixExample.c
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
mwSize r,c, i,j, n;
double *input;
/* get size of the matrix */
r = mxGetM(prhs[0]);
c = mxGetN(prhs[0]);
/* get pointer to data */
input = mxGetPr(prhs[0]);
/* access matrix using row/column indices */
for (i=0; i<r; i++) {
for (j=0; j<c; j++) {
mexPrintf("%lf ", input[j*r+i]);
}
mexPrintf("\n");
}
/* access matrix using linear indices (column-major) */
n = mxGetNumberOfElements(prhs[0]);
for (i=0; i<n; i++) {
mexPrintf("%lf\n", input[i]);
}
}
Compile this MEX function:
>> mex -largeArrayDims matrixExample.c
Then you can use it on sample matrix:
>> matrixExample( rand(2,3) )
0.646204 0.592287 0.464080
0.668417 0.740318 0.143579
0.646204
0.668417
0.592287
0.740318
0.464080
0.143579
Note that I skipped doing input checking just to keep the example simple..
Everything should be explained in the documentation, so start by reading the users guide, and refer to the API reference when needed.
The are also a number of examples included with MATLAB you can study:
>> winopen( fullfile(matlabroot,'extern','examples','mex') )
>> winopen( fullfile(matlabroot,'extern','examples','mx') )
Look at the the MATLAB help for imread. It's quite detailed.
精彩评论