51

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

ITO Yosei
  • 949
  • 2
  • 8
  • 21

4 Answers4

78

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]
yangjie
  • 6,619
  • 1
  • 33
  • 40
33

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().

Safir
  • 902
  • 7
  • 9
  • Whats the difference from clone to assignment? Like: Mat m1; Mat m2; m1 = m2; – Derzu May 06 '18 at 00:59
  • What is the `const` after `Mat::clone()` ? – Hasani Jun 17 '18 at 08:55
  • What you wrote is not right. See the answer below of @yangjie and OpenCV documentation: "When the operation mask is specified, if the Mat::create call shown above reallocates the matrix, the newly allocated matrix is initialized with all zeros before copying the data." but when you DO NOT provide a mask data are copied without reallocation, this means that other Mat pointing to that matrix will have values modified! – giuseppe Sep 24 '18 at 13:39
24

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.

Timothy Shields
  • 75,459
  • 18
  • 120
  • 173
3

copyTo doesn't allocate new memory in the heap which is faster.

Nathan B
  • 1,625
  • 1
  • 17
  • 15