所以要如果需要访问指定位置的元素,其定点位置即偏移量由如下公式得出:
Offset = row * numCols * numChannels + col * numChannels + Channel
row和col代表行号和列号,Channel带包通道号,numChannels代表通道数,numCols代表矩阵列数。
有一个必须要提的技巧就是,CvMat结构体中有个成员变量step,它表示矩阵一行的字节数,即 step = 1*numCols*numChannels。以创建一个三通道矩阵为例,
以固有数据创建三通道CvMat,并遍历矩阵每个元素,如果需要访问指定位置的元素,其定点位置即偏移量由如下公式得出:
Offset = row * numCols * numChannels + col * numChannels + Channel
row和col代表行号和列号,Channel带包通道号,numChannels代表通道数,numCols代表矩阵列数。
有一个必须要提的技巧就是,CvMat结构体中有个成员变量step,它表示矩阵一行的字节数,即 step = 1*numCols*numChannels。以创建一个三通道矩阵为例,并遍历输出
#include <cv.h>
#include <iostream>#include <stdio.h>
using namespace std;
float sumM(const CvMat *mat){
float s=0.0f;
for(int row=0;row<mat->rows;row++)
{
printf("%d\n",mat->rows);
const float*ptr=(const float*)(mat->data.ptr+row*mat->step);
for(int col=0;col<mat->cols;col++){
printf("%d\n",col);
cout<<*(ptr+3*col)<<endl;
cout<<*(ptr+3*col+1)<<endl;
cout<<*(ptr+3*col+2)<<endl;
s+=*(ptr+3*col);printf("%3.1f\n",s);
s+=*(ptr+3*col+1);printf("%3.1f\n",s);
s+=*(ptr+3*col+2);
printf("%3.1f\n",s);
}
}
return s;
}
int main()
{
float Array[9]={1,2,3,4,5,6,7,8,9};
CvMat Mat = cvMat(1,3,CV_32FC3,Array);//创建1行3列3通道矩阵
//遍历矩阵元素
for (int row = 0; row < Mat.rows; row++)
{
float* ptr = (float*)(Mat.data.ptr + row * Mat.step);//第row行数据的起始指针
for (int col = 0; col < Mat.cols; col++)
{
cout<<*(ptr+3*col)<<endl;
cout<<*(ptr+3*col+1)<<endl;
cout<<*(ptr+3*col+2)<<endl;
}
}
float v=0.0f;
v=sumM(&Mat);
cout<<v<<endl;
}