我需要在值为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中
您正在将NEW_VALUE设置为指针,而不是它指向的数据。 –
ups,我错过了*那边,谢谢@MichaelBurdinov – paghdv
不客气。但请注意,此方法仅适用于内存中连续的图像,即您的图像不是某个较大图像的ROI。要解决这个问题,你可以使用'float * prtM = M.ptr(i);'为每一行。 –