OpenCV 学习笔记 -- Mat类 - The Basic Image Container
Posted on 2012-08-23 00:05 theEagles 阅读(837) 评论(0) 收藏 举报Mat -- the Basic Image Container
Mat 是OpenCV中最基本的数据结构,它包括头部和矩阵数据两个部分。
1 enum { MAGIC_VAL=0x42FF0000, AUTO_STEP=0, CONTINUOUS_FLAG=CV_MAT_CONT_FLAG, SUBMATRIX_FLAG=CV_SUBMAT_FLAG }; 2 3 /*! includes several bit-fields: 4 - the magic signature 5 - continuity flag 6 - depth 7 - number of channels 8 */ 9 int flags; 10 //! the matrix dimensionality, >= 2 11 int dims; 12 //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions 13 int rows, cols; 14 //! pointer to the data 15 uchar* data; 16 17 //! pointer to the reference counter; 18 // when matrix points to user-allocated data, the pointer is NULL 19 int* refcount; 20 21 //! helper fields used in locateROI and adjustROI 22 uchar* datastart; 23 uchar* dataend; 24 uchar* datalimit; 25 26 //! custom allocator 27 MatAllocator* allocator;
Mat 采用引用计数来管理内存,通过‘=’、拷贝构造函数创建新的Mat 对象,只copy头部,而实际的矩阵数据是不copy的,原对象和新的对象的引用计数都会自增1.
数据存储方法
数据存储方法是关于颜色空间和数据类型选择的问题。
Mat类支持下面5种数据类型和6中颜色:灰度,RGB,RGBA,HSV, YCrCb,CIE Lab
union { uchar* ptr; short* s; int* i; float* fl; double* db; } data;
构造函数
// 默认构造函数构造一个对象 // Mat(); Mat mtx; //构造二维的Mat对象 //Mat(int rows, int cols, int type); //Mat(Size size, int type); //Mat(int rows, int cols, int type, const Scalar& s); //specify value _s. //Mat(Size size, int type, const Scalar& s); //specify value _s. Mat A(2,2, CV_8UC1); Size sz(2,2); Mat B(sz, CV_8UC3); Mat C(sz, CV_8UC3, Scalar(255,0,0)); Mat M(2,2, CV_8UC3, Scalar(0,0,255)); cout << "M = " << endl << " " << M << endl << endl;// 构造一个指定维数(3)的Mat对象 int sz[3] = {2,2,2}; Mat L(3,sz, CV_8UC(1), Scalar::all(0)); // 根据给定的IplImage,构造一个Mat头部 IplImage* img = cvLoadImage("greatwave.png", 1); Mat mtx(img); // convert IplImage* -> Mat // 用Create函数构造一个Mat对象 M.create(4,4, CV_8UC(2)); cout << "M = "<< endl << " " << M << endl << endl;
// 用静态函数eye,ones, zeros初始化一个对角矩阵、单位矩阵、零矩阵 Mat E = Mat::eye(4, 4, CV_64F); cout << "E = " << endl << " " << E << endl << endl; Mat O = Mat::ones(2, 2, CV_32F); cout << "O = " << endl << " " << O << endl << endl; Mat Z = Mat::zeros(3,3, CV_8UC1); cout << "Z = " << endl << " " << Z << endl << endl;
// 构造并初始化一个小型的Mat对象 Mat C = (Mat_<double>(3,3) << 0, -1, 0, -1, 5, -1, 0, -1, 0); cout << "C = " << endl << " " << C << endl << endl;// 用clone()/copyTo() 函数复制一个Mat对象 Mat H1 = C.row(0).clone(); Mat H2; C.row(1).copyTo(H2);//copyTo 函数的参数是一个Mat类型的引用,copyTo(Mat& m);
Range类
对std::cout的支持
可以直接通过cout输出格式化的字符串
vector<float> v; v.push_back( (float)CV_PI); v.push_back(2); v.push_back(3.01f); cout << "Vector of floats via Mat = " << Mat(v) << endl << endl;

从这里获得支持std::cout的例子程序.
参考文献:
本章结束!

浙公网安备 33010602011771号