Compile error in CV_MAT_ELEM

2019-03-04 12:56发布

问题:

As a result of a call to estimateRigidTransform() I get a cv::Mat object named "trans". To retrieve its contained matrix I try to access its elements this way:

for (i=0; i<2; i++) for (j=0; j<3; j++)
{
   mtx[j][i]=CV_MAT_ELEM(trans,double,i,j);
}

Unfortunately with VS2010 I get a compiler error

error C2228: left of '.ptr' must have class/struct/union

for the line with CV_MAT_ELEM. When I unwrap this macro I find something like

(mat).data.ptr + (size_t)(mat).step*(row) + (pix_size)*(col))

When I remove the ".ptr" behind (mat).data it compiles. But I can't imagine that's the solution (or can't imagine that's a bug and I'm the only one who noticed it). So what could be wrong here really?

Thanks!

回答1:

You don't access the mat elements like this. For a traversal see my other answer here with sample code: color matrix traversal

or see the opencv refman for grayscale Mat:

Mat M; // should be grayscale
int cols = M.cols, rows = M.rows;
for(int i = 0; i < rows; i++) 
{
  const double* Mi = M.ptr<double>(i); 
  for(int j = 0; j < cols; j++)
  {
    Mi[j]; // is the matrix element.
  }
}


回答2:

Just an addendum from my side: meanwhile I found CV_MAT_ELEM expects a structure CvMat (OpenCV-C-interface) but not cv::Mat (the C++-interface). That's why I get this funny error. Conversion from cv::Mat to CvMat can be done simply by casting to CvMat. Funny confusion with the C and C++ interfaces in OpenCV...