OpenCv_learn

Mat的理解

Mat的好处是可以自动的释放内存

Mat是一个基础的类有两个部分

  1. 矩阵头(包括矩阵大小,存储方式,存储地址等信息)
  2. 能指向存储像素信息的矩阵

Mat is basically a class with two data parts: the matrix header (containing information such as the size of the matrix, the method used for storing, at which address is the matrix stored, and so on) and a pointer to the matrix containing the pixel values (taking any dimensionality depending on the method chosen for storing)?

opencv考虑减少对大图片不必要的拷贝,opencv使用reference counting system。每一个mat对象都有自己的矩阵头,但是实际的图片矩阵可以被多个对象的指针共享,即多个指针指向同一个地址。copy操作只会拷贝矩阵头和指向的指针不会拷贝数据本身。

1
2
3
4
5
6
Mat A, C;                          // creates just the header parts
A = imread(argv[1], IMREAD_COLOR); // here we'll know the method used (allocate matrix)

Mat B(A); // Use the copy constructor

C = A; // Assignment operator

A,B,C的header是不同的,但是指向的是同一块内存,通过指针修改内存的数值会导致三个的存储的值改变。

可以通过建立新的hearder来产生ROI。

1
2
Mat D (A, Rect(10, 10, 100, 100) ); // using a rectangle
Mat E = A(Range::all(), Range(1,3)); // using row and column boundaries

但所有的对象都不用了之后,内存就会被释放。利用的reference counting mechanism。

如果希望拷贝数据本身的话,opencv提供clone()copyTo()这两个函数

1
2
3
Mat F = A.clone();
Mat G;
A.copyTo(G);

Summary:

  • Output image allocation for OpenCV functions is automatic (unless specified otherwise).
  • You do not need to think about memory management with OpenCVs C++ interface.
  • The assignment operator and the copy constructor only copies the header.
  • The underlying matrix of an image may be copied using the clone() and copyTo() functions.