mat矩阵类型改变matlab,OpenCV中Mat与Matlab中mxArray类型的转换

在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];

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值