opencv Mat数据的三种标准访问方式
·at(i,j)访问
这种方式在Debug模式下的访问速度是最慢的,但是在Release模式下的访问速度也是相当快的,和其他两种方式相近。
int ROWS = 100; // height
int COLS = 200; // width
Mat img1(ROWS , COLS , CV_32FC1);
for (int i=0; i<ROWS ; i++)
{
for (int j=0; j<COLS ; j++)
{
img1.at<float>(i,j) = 3.2f;
}
}
如果要访问多通道图像
int ROWS = 100; // height
int COLS = 200; // width
Mat img1(ROWS , COLS , CV_8UC3);
for (int i=0; i<ROWS ; i++)
{
for (int j=0; j<COLS ; j++)
{
img1.at<vec3b>(i,j)[0]= 3.2f; // B 通道
img1.at<vec3b>(i,j)[1]= 3.2f; // G 通道
img1.at<vec3b>(i,j)[2]= 3.2f; // R 通道
}
}
类型对应表如下
Mat_<uchar>---------CV_8U
Mat<char>-----------CV_8S
Nat_<short>---------CV_16S
Mat_<ushort>--------CV_16U
Mat_<int>-----------CV_32S
Mat_<float>----------CV_32F
Mat_<double>--------CV_64F
·ptr(i) [j] 方式
int ROWS = 100; // height
int COLS = 200; // width
Mat img1(ROWS , COLS , CV_32FC1);
for (int i=0; i<ROWS ; i++)
{
float* pData1=img5.ptr<float>(i);
for (int j=0; j<COLS ; j++)
{
pData1[j] = 3.2f;
}
}
·img.data + step[0]*i + step[1]*j 方式
Mat channel_H(ROWS,COLS,CV_32FC1,Scalar(0.5));
Mat channel_S(ROWS,COLS,CV_32FC1,Scalar(0.5));
int hs_map[20][20] = {0};
for (int i = 0; i < ROWS; i++)
{
float* Hdata = (float*)(channel_H.data + channel_H.step[0] * i); //可以观察到channel_S.dims不断增加,不知何故
float* Sdata = (float*)(channel_S.data + channel_S.step[0] * i);
for (int j = 0; j < COLS; j++)
{
int x = (int)floor(Hdata[channel_H.step[1]*j]* 20);
int y = (int)floor(Hdata[channel_S.step[1]*j]* 20);
if (x >= 20)
x = 19;
if (y >= 20)
y = 19;
hs_map[x][y]++;
}
}