【发布时间】:2011-10-17 12:27:03
【问题描述】:
我有一个返回类型为 Mat 的 OpenCV 函数。 如何将其转换为二维浮点数组(** 浮点数)?
可能非常简单,但我自己无法做到。
【问题讨论】:
我有一个返回类型为 Mat 的 OpenCV 函数。 如何将其转换为二维浮点数组(** 浮点数)?
可能非常简单,但我自己无法做到。
【问题讨论】:
快速查看the documentation for the Mat class 并没有发现任何明显的“转换为float**”运算符,但您可以手动完成:
Mat mat = (Mat_<float>(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);
// allocate and initialize a 2d float array
float **m = new float*[mat.Rows];
for (int r = 0; r < mat.Rows; ++r)
{
m[r] = new float[mat.Cols];
for (int c = 0; c < mat.Cols; ++c)
{
m[r][c] = mat.at(r, c);
}
}
// (use m for something)
// don't forget to clean up!
for (int r = 0; r < mat.Rows; ++r)
{
delete[] m[r];
}
delete[] m;
如果您不死心使用float**,您可以使用std::vector 或boost::multi_array 来避免尴尬的内存分配/释放并减少泄漏的可能性。
您可能还可以使用Mat::ptr<float>(n) 获得float* 到矩阵的nth 行,但如果您不将数据复制出来,我不确定什么可以保证您将知道该指针将保持有效多长时间。
【讨论】:
如果你是这个意思,
float a[M][N]; //M and N are compile-time constants!
float **p = a; //error
那么你不能这样做。
但是,您可以这样做:
float (*p)[N] = a; //ok
但是,如果这对您没有帮助,并且您不惜一切代价想要 float**,则使用两个 for 循环,并手动执行此操作,将每个元素从 a 复制到 p:
【讨论】: