OpenCV从堆中的数组创建Mat [英] OpenCV create Mat from Array in heap
问题描述
当我尝试使用在堆上分配的数组初始化 Mat 对象时遇到问题.
I have a problem when I try to initialize a Mat object using an array allocated on the heap.
这是我的代码:
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;
}
这些就是结果:
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.
我该怎么办?
感谢您的帮助.
推荐答案
opencv Mat 想要连续 内存,内部表示只是一个 uchar * .
opencv Mat's want consecutive memory, the internal representation is just a single uchar * .
- 你的 P_array 是一个 指针数组 - 不是连续的
- 你的 P_array2 是连续的(但又是静态的..)
- 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);
此外,请注意在完成 Mat 之前,您的数据指针不会被删除/超出范围.在这种情况下,您需要对它进行 clone() 以实现深度复制:
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.
这篇关于OpenCV从堆中的数组创建Mat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!