OpenCV中Mat操作“ =“ 、clone() 与copyto()的区别

1、“=” 浅拷贝

浅拷贝 - 不复制数据只创建矩阵头,数据共享(更改a,b,c的任意一个都会对另外2个产生同样的作用)

Mat a = imread("1.jpg");

Mat b = a; //a "copy" to b

Mat c(a); //a "copy" to c

a.col(10)=0;//把a的第十列全置0,b和c也相应发生变化

2、"clone()" 完全深拷贝

clone 是完全的深拷贝,在内存中申请新的空间

Mat A  = Mat::ones(4,5,CV_32F);

Mat B = A.clone()    //clone 是完全的深拷贝,在内存中申请新的空间,与A独立

3、"copyTo()" 也是深拷贝

copyTo 也是深拷贝,但是否申请新的内存空间,取决于dst矩阵头中的大小信息是否与src一至,若一致则只深拷贝并不申请新的空间,否则先申请空间后再进行拷贝.

Mat A  = Mat::ones(4,5,CV_32F);

Mat C;

A.copyTo(C) //此处的C矩阵大小与A大小不一致,则申请新的内存空间,并完成拷 贝,等同于clone()

Mat D = A.col(1);

A.col(0).copyTo(D) //此处D矩阵大小与A.col(0)大小一致,因此不会申请空间,而是直接进行拷贝,相当于把A的第1列赋值给第二列


// Mat is basically a class with two data parts: the matrix header and 

//a pointer to the matrix containing the pixel values 

 

#include <iostream>

#include <highgui.h>

 

using namespace std ;

using namespace cv ;

 

int main()

{

	Mat image = imread("1.png" , 0) ;

	

	//Mat image1(image) ;//仅是创建了Mat的头部分,image1与image共享数据区

	//Mat image1 = image ;//仅是创建了Mat的头部分,image1与image共享数据区

	//Mat image1 = image.clone() ;//完全拷贝,把image中的所有信息拷贝到image1中

	Mat image1 ;

	image.copyTo(image1) ;//拷贝image的数据区到image1中,在拷贝数据前会有一步:image1.create(this->size , this->type)

	for(int h = 0 ; h < image1.rows ; ++ h)

	{

		uchar* ptr = image1.ptr(h) ;

		for(int w = 0 ; w < image1.cols ; ++ w)

		{

			ptr[w] = 0 ;

		}

	}

	imshow("image" , image) ;

	imshow("image1" , image1) ;

	waitKey() ;

	return 0 ;

}

猜你喜欢

转载自blog.csdn.net/my_angle2016/article/details/113991586
今日推荐