opencv中图像与Matlab中mxArray的转化

在C++中多维矩阵是按行存放,而Matlab中是按列存放,故在opencv中从图像到Matlab中的mxArray需要进行转置。以下仅讨论IplImage*到mxArray的转化。

(1)单通道图像

单通道图像为二维矩阵,仅需实现转置:

mxArray* pMat = mxCreateDoubleMatrix(pImage->height,pImage->width,mxREAL);

UINT8 *pMatPr = (UINT8*)mxGetData(pMat);

for(int j = 0; j < pImage->height; j++)for(int i = 0; i < pImage->width; i++)

{

pMatPr[i * pImage->height + j] = CV_IMAGE_ELEM(pImage,uchar,j,i);

}

(2)多通道图像

3通道彩色图像为三维矩阵,转换方式如下:

const mwSize dims[3] = {pImage->height,pImage->width,3};

mxArray* pMat = mxCreateNumericArray(3,dims,mxUINT8_CLASS,mxREAL);

UINT8 *pMatPr = (UINT8*)mxGetData(pMat);

for(int k = 0; k < 3; k++)for(int j = 0; j < pImage->height; j++)for(int i = 0; i < pImage->width; i++)

{

pMatPr[i * pImage->height + j + k * pImage->height * pImage->width] = CV_IMAGE_ELEM(pImage,uchar,j,i * 3 + 2 - k);

}

结束时调用mxDestroyArray(pMat)释放Array所占有内存。

从mxArray到IplImage*的转化相同。