我发现其他答案有点令人困惑:mat.step 是以字节为单位的行大小,而不是(双)元素,它确实已经考虑了通道的数量。要访问 val,您应该使用:
double* array = (double*) mat.data; // was (double) mat.data in the question
double value = array[ ((mat.step)/mat.elemSize1())*c+mat.channels()*r+ch]; // (mat.step)/mat.elemSize1() is the actual row length in (double) elements
您可以验证此方法和其他方法,将它们与.at<> 运算符进行比较,如下所示:
#include <iostream>
#include <opencv2/core.hpp>
using namespace cv;
using namespace std;
int main()
{
const int w0=5;
const int h=3;
const int w=4;
double data[w0*h*3];
for (int y=0; y<h; y++)
for (int x=0; x<w0; x++)
for (int ch=0; ch<3; ch++)
data[3*(x+w0*y)+ch]=1000+100*(y)+10*(x)+ch;
Mat m0(h,w0,CV_64FC3, data);
Rect roi(0,0,w,h);
Mat mat=m0(roi);
int c=3, r=2, ch=1;
Vec3d v = mat.at<Vec3d>(r,c);
cout<<"the 3 channels at row="<<r<<", col="<<c<<": "<<v<<endl;
double* array= (double*) mat.data;
double expect = 1000+100*r+10*c+ch;
double value= array[ ((mat.step)/mat.elemSize1())*r+mat.channels()*c+ch];
cout<<"row="<<r<<", col="<<c<<", ch="<<ch<<": expect="<<expect<<", value="<<value<<endl;
return 0;
}