在C++中多维矩阵是按行存放,而Matlab中是按列存放,故在opencv中从图像到Matlab中的mxArray需要进行转置。
以下讨论的OpenCV中的Mat类图像与mxArray的数据转换:
1、Mat类转为mxArray:
Mat imgSrc;
h = imgSrc.rows;
w = imgSrc.cols;
c = imgSrc.channels();
mxArray *pMat = NULL;
UINT8 *input = NULL;
if (c == 1) // gray image
{
mwSize dims[2] = {h, w};
pMat = mxCreateNumericArray(2, dims, mxUINT8_CLASS, mxREAL);
input = (UINT8 *)mxGetData(pMat);
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
{
input[j*h + i] = (* imgSrc.row(i).col(j).data);
}
}
}
else if (c == 3) // 3-channel image
{
mwSize dims[3] = {h, w, c};
pMat = mxCreateNumericArray(c, dims, mxUINT8_CLASS, mxREAL);
input = (UINT8 *)mxGetData(pMat);
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
{
for (int ch = 0; ch < c; ch++)
{
input[j*h + i + ch*h*w] = (UINT8)imgSrc.row(i).col(j).data[c - 1- ch];
}
}
}
}
2、mxArray转换为Mat类:
int n = mxGetNumberOfDimensions(data);
int M = mxGetM(data);
int N = mxGetN(data);
uchar *imgData = NULL;
if (mxIsUint8(data) && n == 2)
{
imgData = (uchar *)mxGetPr(data);
h = M;
w = N;
cv::Mat image(h, w, CV_8UC1);
size_t subs[2]; // 三通道图像就需要 subs [3], 后续程序作相应修改
for (int i = 0; i < h; i++)
{
subs[0] = i;
for (int j = 0; j < w; j++)
{
subs[1] = j;
int index = mxCalcSingleSubscript(data, 2, subs);
image.row(i).col(j).data[0] = imgData[index];
}
}
}