What’s the difference between Mat::clone and Mat::copyTo?

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]

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)