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.
opencv Mat's want consecutive memory, the internal representation is just a single uchar * .
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.