1.认识Mat类
早期的OpenCV中,图像的处理是通过IplImage的C语言结构。从OpenCV2.0开始用C++重新实现,引入Mat类使用引用计数的方式管理内存。
Mat类由两部分组成:矩阵头(包含矩阵的大小,存储类型,存储地址等信息),以及一个指向图像实际内存区域的指针。矩阵头大小是恒定的,矩阵数据本身的大小可以随着图像的不同而变化。Mat类使用引用计数系统,每个Mat对象都有自己的头,但是可以指向同一个内存地址,使矩阵数据可以在两个Mat实例之间共享(参照智能指针)。使用赋值操作符只会将头和数据指针复制到另一个矩阵,而不是数据本身(浅拷贝)。 如下:三者都指向同一个图像
Mat A = imread("F:/Src/image.png", cv::IMREAD_UNCHANGED);
Mat B(A);
Mat C = A;
要想拷贝数据可以通过clone或copyTo接口(深拷贝),如下:
Mat D = A.clone();
Mat E;
A.copyTo(E);
(文档:https://www.w3cschool.cn/opencv/opencv-bedc2caa.html)
2.创建Mat对象 2.1.构造函数OpenCV提供了多个构造函数,目前我初学常用的有默认构造和根据行列进行构造
Mat()
Mat(int rows, int cols, int type)
Mat(Size size, int type)
Mat(int rows, int cols, int type, const Scalar & s)
Mat(Size size, int type, const Scalar & s)
Mat(int ndims, const int* sizes, int type)
Mat(const std::vector< int > & sizes, int type)
Mat(int ndims, const int* sizes, int type, const Scalar & s)
Mat(const std::vector< int > & sizes, int type, const Scalar & s)
Mat(const Mat & m)
Mat(int rows, int cols, int type, void* data, size_t step = AUTO_STEP)
Mat(Size size, int type, void* data, size_t step = AUTO_STEP)
Mat(int ndims, const int* sizes, int type, void* data, const size_t * steps = 0)
Mat(const std::vector< int > & sizes, int type, void* data, const size_t * steps = 0)
Mat(const Mat & m, const Range & rowRange, const Range & colRange = Range::all())
Mat(const Mat & m, const Rect & roi)
Mat(const Mat & m, const Range * ranges)
Mat(const Mat & m, const std::vector< Range > & ranges)
Mat(Mat && m)
//等
下面这个构造创建了一个3*3的四通道纯蓝图像,Scalar顺序一般为BGRA:
cv::Mat M1(3, 3, CV_8UC4, cv::Scalar(255, 0, 0, 255));
std::cout
关注
打赏