ITO Yosei
ITO Yosei

Reputation: 959

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

Upvotes: 54

Views: 44302

Answers (4)

Nathan G
Nathan G

Reputation: 1781

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

Upvotes: 3

yangjie
yangjie

Reputation: 6725

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]

Upvotes: 83

Timothy Shields
Timothy Shields

Reputation: 79551

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.

Upvotes: 24

Safir
Safir

Reputation: 902

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

Upvotes: 33

Related Questions