2011-10-17 421 views

回答

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矩阵的第n行也许会有一些运气,但是如果您不复制数据,我不确定您会保留多长时间该指针将保持有效。

+0

谢谢!代码示例非常好! – 2011-10-17 13:24:45

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