Mat类
Mat是一个类,由两个数据部分组成:矩阵头(包含矩阵尺寸、存储方法、存储地址信息)和一个指向存储所有像素值的矩阵(根据所选存储方法的不同,矩阵可以是不同的维度)的指针;所以应该尽量避免大图像的复制;
为了解决这个问题,OpenCV引用计数机制。其思路是让每一Mat对象有自己的信息头,但共享同一个矩阵。这通过让矩阵指针指向同一地址而实现。而拷贝构造函数只复制信息头和矩阵指针,而不是复制矩阵;
例如:
Mat A ,B ,C;
A=imread("1.jpg");
Mat B(A);
C=A;
以上的结果是所有的Mat对象(A、B、C)都指向同一个也是为一个数据矩阵;
但是:若想复制矩阵本身(不只是复制信息头和矩阵指针),这时可以采用clone()与copyTo();
clone()
//! returns deep copy of the GpuMat, i.e. the data is copied
CV_WRAP GpuMat clone() const;
copyTo()
//! copies the GpuMat content to device memory (Blocking call)
CV_WRAP void copyTo(OutputArray dst) const;
//! copies the GpuMat content to device memory (Non-Blocking call)
CV_WRAP void copyTo(OutputArray dst, Stream& stream) const;
//! copies those GpuMat elements to "m" that are marked with non-zero mask elements (Blocking call)
CV_WRAP void copyTo(OutputArray dst, InputArray mask) const;
//! copies those GpuMat elements to "m" that are marked with non-zero mask elements (Non-Blocking call)
CV_WRAP void copyTo(OutputArray dst, InputArray mask, Stream& stream) const;
着重在于mask的理解:
CV_WRAP void copyTo(OutputArray dst, InputArray mask) const;
可以通过实验进行理解:
#include<opencv2/opencv.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<iostream>
#include<string>
#include<vector>
using namespace cv;
using namespace std;
int main()
{
Mat image1 = imread("C:\\Users\\Desktop\\3x3.jpg");
Mat mask = imread("C:\\Users\\Desktop\\lion_mini3x3.jpg",0);
cout << "image1=\n" << image1 << endl << endl;
cout << "mask=\n" << mask << endl << endl;
Mat image2;
image1.copyTo(image2,mask);
cout << "image2=\n" << image2 << endl << endl;
imshow("【效果图】", image2);
waitKey(0);
}
3x3图如下:
lion_mini3x3如下:
结论;
结论部分参考:https://blog.csdn.net/qq_38392229