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;
}
上一篇:总结jQuery选择器


下一篇:漫谈PHP组件、框架、Composer那些事