What's the difference between Mat::clone and Mat::copyTo?
I know 'copyTo' can handle mask. But when mask is not needed, can I use both equally?
http://docs.opencv.org/modules/core/doc/basic_structures.html#mat-clone
Actually, they are NOT the same even without mask.
The major difference is that when the destination matrix and the source matrix have the same type and size, copyTo
will not change the address of the destination matrix, while clone
will always allocate a new address for the destination matrix.
This is important when the destination matrix is copied using copy assignment operator before copyTo
or clone
. For example,
Using copyTo
:
Mat mat1 = Mat::ones(1, 5, CV_32F);
Mat mat2 = mat1;
Mat mat3 = Mat::zeros(1, 5, CV_32F);
mat3.copyTo(mat1);
cout << mat1 << endl;
cout << mat2 << endl;
Output:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
Using clone
:
Mat mat1 = Mat::ones(1, 5, CV_32F);
Mat mat2 = mat1;
Mat mat3 = Mat::zeros(1, 5, CV_32F);
mat1 = mat3.clone();
cout << mat1 << endl;
cout << mat2 << endl;
Output:
[0, 0, 0, 0, 0]
[1, 1, 1, 1, 1]
This is the implementation of Mat::clone()
function:
inline Mat Mat::clone() const
{
Mat m;
copyTo(m);
return m;
}
So, as @rotating_image had mentioned, if you don't provide mask
for copyTo()
function, it's same as clone()
.
Mat::copyTo
is for when you already have a destination cv::Mat
that (may be or) is already allocated with the right data size. Mat::clone
is a convenience for when you know you have to allocate a new cv::Mat
.
copyTo doesn't allocate new memory in the heap which is faster.