the implementation of clone() function:
inline Mat Mat::clone() const
{
Mat m;
copyTo(m);
return m;
}
clone()和copyTo()最大的区别在于clone()会给目标矩阵分配新地址,而copyTo()不会。
举个例子,
Mat img1 = ones(1, 5, CV_32F);
Mat img2 = img1;
Mat img3 = zeros(1, 5, CV_32F);
img3.copyTo(img1);
cout << img1 << endl;
cout << img2 << endl;
output:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
Mat img1 = ones(1, 5, CV_32F);
Mat img2 = img1;
Mat img3 = zeros(1, 5, CV_32F);
img1 = img3.clone();
cout << img1 << endl;
cout << img2 << endl;
output:
[0, 0, 0, 0, 0]
[1, 1, 1, 1, 1]
例2中可见clone()替img1申请了一块新内存,而img2仍指向原来的img1的地址,所以img2不变