opencv中为矩阵复制提供了copyTo函数、clone函数、重载运算符和拷贝构造函数,用法非常简单:
Mat srcimage = imread("1.jpg"); Mat firstimage,secondimage,thirdimage; srcimage.copyTo(firstimage); secondimage = srcimage.clone(); thirdimage = srcimage; Mat fourthimage(srcimage);
但是在他们四者间存在着较大的区别,我们先写个简单的代码测试一下:
Mat srcimage = imread("2.jpg"); Mat firstimage,secondimage,thirdimage; double t1 = (double)getTickCount(); srcimage.copyTo(firstimage); t1 = (double)getTickCount() - t1; double t2 = (double)getTickCount(); secondimage = srcimage.clone(); t2 = (double)getTickCount() - t2; double t3 = (double)getTickCount(); thirdimage = srcimage; t3 = (double)getTickCount() - t3; double t4 = (double)getTickCount(); Mat fourthimage(srcimage); t4 = (double)getTickCount() - t4; printf("copyTo execution time = %lfms\n", t1*1000. / getTickFrequency()); printf("clone execution time = %lfms\n", t2*1000. / getTickFrequency()); printf(" = execution time = %lfms\n", t3*1000. / getTickFrequency()); printf(" 构造函数 execution time = %lfms\n", t4*1000. / getTickFrequency()); getchar();
为了让效果明显,选择了一张很大的图片,这样图片的尺寸是3120*4160,实验结果如下:

我们可以看到,copyTo函数、clone函数占用时间差不多,但是“= ”运算符与拷贝构造函数用的时间却非常少,这是为什么呢?
造成这样的情况的原因是因为Mat的数据类型以及它的数据组成造成的。
Mat类
从上面的话我们可以看到,copyTo函数、clone函数拷贝的不仅仅是信息头,还有矩阵本身,而“= ”运算符与拷贝构造函数仅仅拷贝了信息头,他们指向的其实是一个矩阵,也就是在上的程序中,我们改变srcimage ,thirdimage和fourthimage中的任何一个,另外两个也会跟着变化,我们再改一下代码测试一下(为了屏幕能放下,我们把图片换一下):
Mat srcimage = imread("1.jpg"); Mat firstimage,secondimage,thirdimage; imshow("result1",srcimage); double t1 = (double)getTickCount(); srcimage.copyTo(firstimage); Point center = Point(55,55); int r = 10; circle(firstimage,center,r,Scalar(0,0,255),-1); t1 = (double)getTickCount() - t1; imshow("result2",firstimage); double t2 = (double)getTickCount(); secondimage = srcimage.clone(); t2 = (double)getTickCount() - t2; double t3 = (double)getTickCount(); thirdimage = srcimage; t3 = (double)getTickCount() - t3; double t4 = (double)getTickCount(); Mat fourthimage(srcimage); t4 = (double)getTickCount() - t4; Point a = Point (0,0); Point b = Point (thirdimage.cols,thirdimage.rows); line(thirdimage,a,b,Scalar(255,0,0)); printf("copyTo execution time = %lfms\n", t1*1000. / getTickFrequency()); printf("clone execution time = %lfms\n", t2*1000. / getTickFrequency()); printf(" = execution time = %lfms\n", t3*1000. / getTickFrequency()); printf(" 构造函数 execution time = %lfms\n", t4*1000. / getTickFrequency()); imshow("result3",srcimage); waitKey(0); getchar();
可以看到,在原图刚刚读入的时候,显示了窗口result1,此时显示的就是读入的图片,firstimage是由srcimage通过copyTo的方法拷贝的,我们把firstimage画一个圆,然后用result2窗口显示,thirdimage是由srcimage通过“=”运算符拷贝的,我们将thirdimage画个线,并用result3再一次显示srcimage,然后我们可以看到,result3中srcimage已经变了,变成了和thirdimage一样的效果,说明之前的说法是正确的,他们共有了同一个矩阵。



发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/229990.html原文链接:https://javaforall.net
