Matlab to OpenCV Mat

convert Matlab matrix to OpenCV Mat. Support CV_32FC3 only currently.


The Code

int matlab2opencv(cv::Mat &img, const mxArray *&mat){
  mwSize num_dims = mxGetNumberOfDimensions(mat);
  const mwSize *dims = mxGetDimensions(mat);

  //for (int i = 0; i < num_dims; i++){
  //  mexPrintf("%d-th:%d\n", i, dims[i]);
  //}

  if (num_dims != 3 || dims[2] != 3){
    mexPrintf("error image dimensions!\n");
    return EXIT_FAILURE;
  }

  if (!mxIsSingle(mat)){
    mexPrintf("the input matrix must be double with value in [0,1].");
    return EXIT_FAILURE;
  }

  int rows = dims[0];
  int cols = dims[1];
  int nchs = 3;

  img.create(rows, cols, CV_32FC3);

  float *mat_data = (float*)mxGetData(mat);
  float *mat_temp_ptr = NULL;

  int layer_size = rows*cols;

  for (int ch = 0; ch < nchs; ch++){
    mat_temp_ptr = mat_data + ch*layer_size;
    int rd = 2 - ch;
    for (int c = 0; c < cols; c++){
      for (int r = 0; r < rows; r++){
        img.at<cv::Vec3f>(r, c)[rd] = mat_temp_ptr[c*rows+r];
      }
    }
  }

  return EXIT_SUCCESS;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值