OpenCV create Mat from Array in heap

假装没事ソ 提交于 2021-02-07 10:51:46

问题


I have a problem when I try to initialize a Mat object using an array allocated on the heap.

This is my code:

void test(){

    int rows = 2;
    int cols = 3;

    float **P_array;
    P_array = new float*[rows];

    int i;
    for(i = 0; i < rows; i++)
            P_array[i] = new float[cols];


    P_array[0][0]=1.0; P_array[0][1]=2.0; P_array[0][2]=3.0;
    P_array[1][0]=4.0; P_array[1][1]=5.0; P_array[1][2]=6.0;

    float P_array2[2][3]={{1.0,2.0,3.0},{4.0,5.0,6.0}};

    Mat P_m = Mat(rows, cols, CV_32FC1, &P_array);
    Mat P_m2 = Mat(2,3, CV_32FC1, &P_array2);

    cout << "P_m: "  << P_m   << endl;
    cout << "P_m2: " << P_m2 << endl;

}

And those are the results:

P_m: [1.1737847e-33, 2.8025969e-45, 2.8025969e-45;
  4.2038954e-45, 1.1443695e-33, -2.2388967e-06]
P_m2: [1, 2, 3;
  4, 5, 6]

As you can see the dynamically allocated array is not copied successfully. However, it is critical for me to be able to initialize from a dynamically allocated array.

What should I do?

Thanks for your help.


回答1:


opencv Mat's want consecutive memory, the internal representation is just a single uchar * .

  • your P_array is an array of pointers - not consecutive
  • your P_array2 is consecutive (but static again..)

if you need to initialize it with dynamic memory, just use a single float pointer:

float *data = new float[ rows * cols ];
data[ y * cols + x ] = 17; // etc.

Mat m(rows, cols, CV_32F, data);

also, take care that your data pointer does not get deleted / goes out of scope before you're done with the Mat. in that case, you'll need to clone() it to achieve a deep copy:

Mat n = m.clone();
delete[] data; // safe now.


来源:https://stackoverflow.com/questions/25136781/opencv-create-mat-from-array-in-heap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!