将Mat转换为** float

时间:2011-10-17 12:27:03

标签: c++ opencv matrix

我有一个OpenCV函数,返回类型是Mat。 如何将其转换为二维浮点数组(** float)?

可能非常简单,但我自己无法做到。

2 个答案:

答案 0 :(得分:2)

快速查看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::vectorboost::multi_array来避免内存分配/解除分配,并减少泄漏的可能性。

使用Mat::ptr<float>(n)获取float*矩阵的n行也可能会有一些运气,但如果你不复制数据,我就是不确定保证指针保持有效的时间。

答案 1 :(得分:1)

如果你的意思是,

float a[M][N]; //M and N are compile-time constants!
float **p = a; //error
那时你不能这样做。

但是,你可以这样做:

float (*p)[N] = a; //ok

但是,如果这对您没有任何帮助而您想要float**,那么请使用两个for循环,并手动执行此操作,将每个元素从a复制到p {{1}}:

相关问题