2014-02-11 23 views
0

我需要在值为CV_32FC1(float)的M(变量类型Mat)中分配值,但长时间大小为10000x10000。即:使用OpenCV分配到Mat中

for (i=0 ; i<rows; i++) 
    for (j=0 ; j<cols; j++){ 
     ...build variable NEW_VALUE for indexes i, j 
     M.at<float>(i,j) = NEW_VALUE 
    } 

上面的代码需要1秒aprox。我看到的其他形式是定义联合(复制字节):

typedef union{float _float; uchar _uchar[4];} Bits; 
... 
Bits bits; 
float new_value; 
for (i=0 ; i<rows; i++) 
    for (j=0 ; j<cols; j+=4){ 
    ...//build variable new_value for indexes i, j 
    bits._float = new_value; 
    M.data[i*cols + j] = bits._uchar[0]; 
    M.data[i*cols + j+1] = bits._uchar[1]; 
    M.data[i*cols + j+2] = bits._uchar[3]; 
    M.data[i*cols + j+3] = bits._uchar[3]; 
    } 

这比第一个更快。但不工作。我试过了:

memcpy(&M.data[i*cols + j], bits._uchar[0], 1); 
memcpy(&M.data[i*cols + j+1], bits._uchar[1], 1); 
... 

但是不行。

和:

memcpy(&M.at<float>(i,j), bits._uchar, 4); 

很慢也。

我需要知道如何将NEW_VALUE的字节在M中

回答

1

你的代码是缓慢的,因为你执行的是大量的计算每个像素的正确复制。乘法运算不是一个便宜的操作,你可以明确地(i * cols + j)或隐式(在< float>(i,j))多次使用它。阅读this tutorial以更好地了解如何有效地访问像素。

0

你可以做这样的事情:

float *prtM=(float*)M.data; 
for (i=0 ; i<rows; i++) 
    for (j=0 ; j<cols; j++){ 
     //...build variable NEW_VALUE for indexes i, j 
     *prtM = NEW_VALUE; 
     prtM++; 
    } 
+0

您正在将NEW_VALUE设置为指针,而不是它指向的数据。 –

+0

ups,我错过了*那边,谢谢@MichaelBurdinov – paghdv

+0

不客气。但请注意,此方法仅适用于内存中连续的图像,即您的图像不是某个较大图像的ROI。要解决这个问题,你可以使用'float * prtM = M.ptr (i);'为每一行。 –

0
float* p; 
for (i=0 ; i<rows; i++) 
{ 
    p = M.ptr<float>(i); 
    for (j=0 ; j<cols; j++) 
    { 
     *p++ = NEW_VALUE; 
    } 
} 

paghdv的代码是最好的优化之一,但如果值的int矩阵是不连续将无法正常工作。