您的位置:首页 > 其它

3.2 矩阵和图像类型

2016-02-29 07:34 288 查看
CvArr—>CvMat—>IplImage

CvMat矩阵结构

在OpenCV中没有vector结构,只有列矩阵。

cvMat* cvCreateMat(int rows, int cols, int type);  //新建一个二维矩阵


type在这里可以是任何预定义的类型,预定义结构为 CV_<bit_length>(S|U|F)C<numbers_of_channels>,例如CV_32FC1,CV_8UC3。

//CvMat结构:矩阵头
typedef struct CvMat{
int type;
int step;
int* refcount;    //仅英特尔使用
union{
uchar* ptr;
short* s;
int* i;
float* f1;
double* db;
}data;
union{
int rows;
int heights;
};
union{
int cols;
int width;
};
}CvMat;


#include "cv.h"

int main(int argc, char** argv)
{
float vals[] = {0.866025, -0.500000, 0.500000, 0.866025};

CvMat rotmat;

cvInitMatHeader(
&rotmat,
2,
2,
CV_32FC1,
vals
);
return 0;
}


用固定数据创建一个OpenCV矩阵

矩阵数据的存取

1、简单的方法

//利用CV_MAT_ELEM()宏存取矩阵
CvMat* mat = cvCreateMat(5, 5, CV_32FC1);
float element_3_2 = CV_MAT_ELEM(*mat, float, 3, 2);


//利用CV_MAT_ELEM_PTR()为矩阵设置一个数值
CvMat* mat = cvCreateMat(5, 5, CV_32FC1);
float element_3_2 = 7.7;
*((float*)CV_MAT_ELEM_PTR(*mat, 3, 2)) = element;


2、麻烦的方法

//指针访问矩阵结构,如果是仅仅读取数据可用cvGet*D,返回矩阵元素值
uchar* cvPtr1D(
const CvArr* arr,    //矩阵指针参数
int idx0,            //表示索引的整数值
int* type = NULL    //可选参数,代表输出值的类型
);

uchar* cvPtr2D(
const CvArr* arr,
int idx0,
int idx1,
int* type = NULL
);

uchar* cvPtr3D(
const CvArr* arr,
int idx0,
int idx1,
int* type = NULL
);

uchar* cvPtrND(
const CvArr* arr,
int* idx,
int* type = NULL,
int create_node = 1,
unsigned* precalc_hashaval = NULL
);


//累加一个三通道矩阵中的所有元素
float sum(const CvMat* mat){
float s = 0.0f;
for(int row=0; row<mat->rows; row++){
const float* ptr = (const float*)(mat->data.ptr + row * mat->step);  //指向每一行的头指针
for(int col=0; col<mat->cols; col++){
s += *ptr++;  //先算*ptr,然后ptr++
}
}
return s;
}


自己写一个方法读取。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: