What do we do when we want to copy the data of one Mat object to another Mat object?
We find that OPENCV provides the overloaded operator Mat::operator =, so is it easy to do the assignment of an object according to the following statement?
Mat A; Mat B = A;
The answer is NO!
We can see from the reference manual:
Mat::operator =
Provides matrix assignment operators.
C + +: mat& mat::operator= (const mat& m)
Parameters
m–assigned, Right-hand-side Matrix. Matrix assignment is an O (1) operation. This means-no data is copiedbut the data is GKFX and the reference counter, if any, is increment Ed. Before assigning new data, the old data is de-referenced via Mat::release ().
This means that after the operation, B and a will share the same piece of data, and no duplication of data will occur.
Again, we can see from the source code that:
inline mat& mat::operator = (const mat& m) { if (this = &m) { if (m.refcount) Cv_xadd (M.REFC Ount, 1); Release (); Flags = M.flags; if (dims <= 2 && m.dims <= 2) { dims = m.dims; rows = m.rows; cols = M.cols; Step[0] = m.step[0]; STEP[1] = m.step[1]; } else copysize (m); data = M.data; Datastart = M.datastart; Dataend = M.dataend; Datalimit = M.datalimit; RefCount = M.refcount; allocator = M.allocator; } return *this;}
The overloaded operator simply assigns the address of each data pointer and does not copy the data.
So what should we do if we need to copy the Mat object?
(1) Mat::copyto function
Mat A; Mat B;a.copyto (b);
(2) Mat::clone function
Mat A; Mat B = A.clone ();
So what is the difference between these two functions?
We look at the source code:
Inline Mat mat::clone () const{ mat m; CopyTo (m); return m;}
From the source code can be found, in fact, the Clone () function is another implementation of CopyTo ().