matlab 经常需要用c /c++ 编译的代码进行调用,而数据传输上面是个问题,下面我把我的转换方式给大家参考!!
这里是读取到matlab中的矩阵数据,这里认为是灰度图像。
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
int n = mxGetNumberOfDimensions(prhs[0]); //图像维数
int M = mxGetM(prhs[0]); //图像行数
int N = mxGetN(prhs[0]); //图像列数
uchar *imgData = NULL;
if( mxIsUint8(prhs[0]) && n == 2)
{
uchar* imgData = (uchar *)mxGetPr(prhs[0]);
cv::Mat src( M,N, CV_8UC1);
int subs[2]; // 三通道图像就需要 subs [3], 后续程序作相应修改
for (int i = 0; i < M; i++)
{
subs[0] = i;
for (int j = 0; j < N; j++)
{
subs[1] = j;
int index = mxCalcSingleSubscript(prhs[0], 2, subs);
src.row(i).col(j).data[0] = imgData[index];
}
}
}
}
C++版本:数据传入
double* in1 = (double *)mxGetPr(prhs[0]);
int NN = mxGetN(prhs[0]);
int MM = mxGetM(prhs[0]);
// double* in = new double[NN*MM];
image_double inn = new_image_double(NN,MM);
int subs[2]; // 三通道图像就需要 subs [3], 后续程序作相应修改
for (int i = 0; i < MM; i++)
{
subs[0] = i;
for (int j = 0; j < NN; j++)
{
subs[1] = j;
int index = mxCalcSingleSubscript(prhs[0], 2, subs);
// in[i*NN+j] = in1[index];
inn->data[i*NN+j] = in1[index];
}
}
上述对应的函数和结构体:
image_double new_image_double(unsigned int xsize, unsigned int ysize)
{
image_double image;
/* get memory */
image = (image_double) malloc( sizeof(struct image_double_s) );
if ( image == NULL ) error("not enough memory.");
image->data = (double *) calloc( (size_t) (xsize * ysize), sizeof(double) );
if ( image->data == NULL ) error("not enough memory.");
/* set image size */
image->xsize = xsize;
image->ysize = ysize;
return image;
}
typedef struct image_double_s
{
double *data;
unsigned int xsize, ysize;
} *image_double;
数据写给matlab
plhs[0] = mxCreateDoubleMatrix(1, pos.size(), mxREAL);
double *pos_mat = mxGetPr(plhs[0]);
for (int i = 0; i != pos.size(); ++i)
{
pos_mat[i] = double(pos[i]);
}
这里pos 为自己定义的内容,大家替换成自己相关的内容即可,我这里的pos为vector
再有就是注意,传入参数时M,N的顺序变换后,matlab 读取后的数据也会变换需要reshape后或者再加上专职才可以恢复!!!!