<span style="font-size:12px;">//1.使用构造函数,常见的几个如下:
Mat::Mat(); //default
Mat::Mat(int rows, int cols, int type);
Mat::Mat(Size size, int type);
Mat::Mat(int rows, int cols, int type, const Scalar& s);
Mat::Mat(Size size, int type, const Scalar& s);
Mat::Mat(const Mat& m);
//参数说明:
//int rows:高
//int cols:宽
//int type:参见"Mat类型定义"
//Size size:矩阵尺寸,注意宽和高的顺序:Size(cols, rows)
//const Scalar& s:用于初始化矩阵元素的数值
//const Mat& m:拷贝m的矩阵头给新的Mat对象,但是不复制数据!相当于创建了m的一个引用对象
//例子1:创建100*90的矩阵,矩阵元素为3通道32位浮点型
cv::Mat M(100, 90, CV_32FC3);
//例子2:使用一维或多维数组来初始化矩阵,
double m[3][3] = {
{a, b, c}, {d, e, f}, {g, h, i}};
cv::Mat M = cv::Mat(3, 3, CV_64F, m);
//2.使用create函数:
Mat a = create(10, 9, CV_16U); //创建10*9的矩阵,矩阵元素为16位无符号整型
//create的一个特殊用法:如果初始化的时候没有传入size的参数,或者后面需要改变size的参数,可以使用create来调整
// make 7x7 complex matrix filled with 1+3j.
cv::Mat M(7,7,CV_32FC2,Scalar(1,3));
// and now turn M to 100x60 15-channel 8-bit matrix.
// The old content will be deallocated:隐式使用release()释放
M.create(100,60,CV_8UC(15));</span>
- Mat数据类型
在创建Mat矩阵时,通常会需要指定它的存储元素的数据类型以及每个矩阵点的通道数。根据下述规则会有多种定义:
CV_[位数][是否带符号][类型前缀]C[通道数]
比如CV_8UC3表示使用8位的unsigned char 型,每个像素由三个元素组成三通道。
Mat的存储是逐行存储的,矩阵中的数据类型包括:Mat_<uchar>对应的是CV_8U,Mat_<uchar>对应的是CV_8U,Mat_<char>对应的是CV_8S,Mat_<int>对应的是CV_32S,Mat_<float>对应的是CV_32F,Mat_<double>对应的是CV_64F,对应的数据深度如下:
• CV_8U - 8-bit unsigned integers ( 0..255 )
扫描二维码关注公众号,回复: 15019881 查看本文章• CV_8S - 8-bit signed integers ( -128..127 )
• CV_16U - 16-bit unsigned integers ( 0..65535 )
• CV_16S - 16-bit signed integers ( -32768..32767 )
• CV_32S - 32-bit signed integers ( -2147483648..2147483647 )
• CV_32F - 32-bit floating-point numbers ( -FLT_MAX..FLT_MAX, INF, NAN )
• CV_64F - 64-bit floating-point numbers ( -DBL_MAX..DBL_MAX, INF, NAN )
按照上述过程创建出2通道矩阵后,接着我用at函数对矩阵像素点进行访问,具体代码如下。
#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include<opencv2/imgproc/imgproc.hpp> #include <iostream> using namespace std; using namespace cv; int main() { int i, j; Mat dimg(4, 4, CV_64FC2,Scalar(0,1.1));//构造一个4*4的双通道矩阵,数据类型为double cout << "原矩阵" << endl << dimg << endl << endl; for (i = 0; i < dimg.rows; i++) { for (j = 0; j < dimg.cols; j++) { dimg.at<Vec2d>(i, j)[0] = 9.9;//at<type>其中type由矩阵的类型确定,下面会给出详细信息 dimg.at<Vec2d>(i, j)[1] = 100.0; } } cout << "改变后矩阵" << endl << dimg << endl << endl; system("pause"); } /******对应关系******/
template<typename_Tp, int n> class Vec : public Matx<_Tp, n, 1> {...}; typedef Vec<uchar, 2> Vec2b; //无符号双通道 typedef Vec<uchar, 3> Vec3b; //无符号3通道 typedef Vec<uchar, 4> Vec4b; typedef Vec<short, 2> Vec2s; //short型双通道 typedef Vec<short, 3> Vec3s; typedef Vec<short, 4> Vec4s; typedef Vec<int, 2> Vec2i; //整型双通道 typedef Vec<int, 3> Vec3i; typedef Vec<int, 4> Vec4i; typedef Vec<float, 2> Vec2f; //浮点型双通道 typedef Vec<float, 3> Vec3f; typedef Vec<float, 4> Vec4f; typedef Vec<float, 6> Vec6f; typedef Vec<double, 2> Vec2d; //double型双通道 typedef Vec<double, 3> Vec3d; typedef Vec<double, 4> Vec4d; typedef Vec<double, 6> Vec6d;