CvCreateMat和直接访问

时间:2011-06-29 09:18:33

标签: c opencv matrix memory-management

我尝试过这段代码并且没有正确访问该元素,有人可以解释一下原因吗?

int size[] = { 5, 5, 5 };
CvMatND* matA = cvCreateMatND(3, size, CV_32F);
cvSetZero(matA);


    printf("test: %d \n",cvGetReal3D(matA, 1, 1, 1));
    cvSetReal3D(matA, 1, 1, 1, (cvGetReal3D(matA, 1, 1, 1)+1));
    int test = cvGetReal3D(matA, 1, 1, 1);
    printf("test: %d \n",test);


    char cont = 1;
       for (int dim_index = 0; dim_index < matA->dims; dim_index++) 
         {   
    printf("There are %d elements on dim %d\n", matA->dim[dim_index].size, dim_index);

    for (int elem = 0; elem < matA->dim[dim_index].size; elem++)
    {   
        printf("On element [%d] of dim %d, wrote: %d\n", elem, dim_index, matA->data.ptr[matA->dim[dim_index].size * dim_index + elem]);
    }   
} 

输出:

test: 0
test: 1
There are 5 elements on dim 0
On element [0] of dim 0, wrote: 0
On element [1] of dim 0, wrote: 0
On element [2] of dim 0, wrote: 0
On element [3] of dim 0, wrote: 0
On element [4] of dim 0, wrote: 0
There are 5 elements on dim 1
On element [0] of dim 1, wrote: 0
On element [1] of dim 1, wrote: 0
On element [2] of dim 1, wrote: 0
On element [3] of dim 1, wrote: 0
On element [4] of dim 1, wrote: 0
There are 5 elements on dim 2
On element [0] of dim 2, wrote: 0
On element [1] of dim 2, wrote: 0
On element [2] of dim 2, wrote: 0
On element [3] of dim 2, wrote: 0
On element [4] of dim 2, wrote: 0

谢谢!

1 个答案:

答案 0 :(得分:0)

我为我的其他答案道歉,因为它不正确。您可以在那里添加评论,说明没有按预期工作。从那以后我有fixed it,正确的做法是:

int size[] = { 5, 5, 5 };
CvMatND* matA = cvCreateMatND(3, size, CV_32F);
cvSetZero(matA);

printf("Before writting at 1x1x1 %f \n", cvGetReal3D(matA, 1, 1, 1));
cvSetReal3D(matA, 1, 1, 1, (cvGetReal3D(matA, 1, 1, 1)+1));

int test = cvGetReal3D(matA, 1, 1, 1);
printf("After: %d\n", test);

printf("Before writting at 3x2x1 %f \n", cvGetReal3D(matA, 3, 2, 1));
cvSetReal3D(matA, 3, 2, 1, (cvGetReal3D(matA, 3, 2, 1)+1));

test = cvGetReal3D(matA, 3, 2, 1);
printf("After: %d\n", test);

for (int x = 0; x < matA->dim[0].size; x++) // dim 0
{
    for (int y = 0; y < matA->dim[1].size; y++) // dim 1
    {
        for (int z = 0; z < matA->dim[2].size; z++) // dim 2
        {
            unsigned char* ptr = matA->data.ptr + ((size_t)x * matA->dim[0].step) + ((size_t)y * matA->dim[1].step) + ((size_t)z * matA->dim[2].step);
            float value = *(float*)ptr;
            printf("x:%d y:%d z:%d --> %f\n", x, y, z, value);
        }
    }
}

我改进了你的测试,上面的代码将1写入位置(1,1,1)和(3,2,1)。

输出(简化):

x:1 y:1 z:0 --> 0.000000
x:1 y:1 z:1 --> 1.000000
x:1 y:1 z:2 --> 0.000000
...
x:3 y:2 z:1 --> 1.000000
...