如何访问cvMat中的数据

时间:2014-10-17 12:27:32

标签: c element opencv-mat

我试图访问cvMat中的数据。

这是我的代码:

// Declare
int rank = 3;
CvMat* warp_matrix = cvCreateMat(rank,rank,CV_32FC1);

// Using
cvGetPerspectiveTransform(imgSrc,imgDst,warp_matrix);

for(int i=0; i<rank; i++)
{
    for(int j=0; j<rank; j++)
    {
        std::cout << warp_matrix->data[i][j] << std::endl;
    }
}

但是我发现了一个错误:

error: no match for 'operator[]' (operand types are 'CvMat::<anonymous union>' and 'int')

而且我不知道如何修复它 - 我尝试CV_MAT_ELEM()这样:

std::cout << CV_MAT_ELEM(warp_matrix,double,i,j) << std::endl;

它仍然无法正常工作(发现此错误):

error: request for member 'cols' in 'warp_matrix', which is of pointer type 'CvMat*' (maybe you meant to use '->' ?)

我现在不知道该怎么做。你能救我吗?

1 个答案:

答案 0 :(得分:0)

使用宏CV_MAT_ELEM。它需要一个cvMat而不是一个指向cvMat的指针。如果需要指针:

mx->data;

是一个未命名的指针联合(每种类型):

mx->data.ptr; // uchar
mx->data.i; // int
mx->data.s; // short
mx->data.db; // double
mx->data.fl; // float

请注意,这些是一维的,因此mx [row] [col]样式访问不起作用。考虑一下例子:

CvMat * mx = cvCreateMat( 3, 4, CV_32FC1 );
LOG->PrintLn( "%u x %u", mx->cols, mx->rows );
for( uint rdx = 0; rdx < mx->rows; ++rdx )
{
    for( uint cdx = 0; cdx < mx->cols; ++cdx )
    {
        CV_MAT_ELEM( * mx, float, rdx, cdx ) = ( 1 + rdx ) * 10 + cdx;
        LOG->Print( "\t%.1f", mx->data.fl[ mx->cols * rdx + cdx ] );
    }
    LOG->PrintLn();
}

(Matrices imgSrc和imgDst未在您的示例中声明,因此我无法生成转换。)