OpenCV中Mat::clone与Mat::copyTo的区别

本文详细解析了在OpenCV中Mat对象的copyTo与clone方法的使用差异,强调了当目标矩阵与源矩阵具有相同类型和大小时,copyTo不会重新分配内存,而clone则会为新矩阵分配独立的内存空间,避免引用共享。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

"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."

以上文字参考自https://stackoverflow.com/questions/15672600/whats-the-difference-between-matclone-and-matcopyto

简单解释下,当目标矩阵与源矩阵具有相同的type和size时,copyTo不会为目标矩阵重新分配内存,而clone总是会为目标矩阵重新分配内存。以下两段代码很好地解释了两者之间的区别:

Mat mat1 = Mat::ones(1, 5, CV_32F);   // [1,1,1,1,1]
Mat mat2 = mat1;   // mat2与mat1指向同一内存地址
Mat mat3 = Mat::zeros(1, 5, CV_32F);  // [0,0,0,0,0]
mat3.copyTo(mat1); // mat1未被重新分配内存,通过mat1可以改变mat2的内容
cout << mat1 << endl;   // [0,0,0,0,0] 
cout << mat2 << endl;   // [0,0,0,0,0]
Mat mat1 = Mat::ones(1, 5, CV_32F);   // [1,1,1,1,1]
Mat mat2 = mat1;   // mat2与mat1指向同一内存地址
Mat mat3 = Mat::zeros(1, 5, CV_32F);   // [0,0,0,0,0]
mat1 = mat3.clone();   // mat1被重新分配内存,通过mat1不能改变mat2的内容
cout << mat1 << endl;   // [0,0,0,0,0]
cout << mat2 << endl;   // [1,1,1,1,1]

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值