时令

导航

 

 

 

OpenCV中Mat类实现自动内存管理机制,若非必须纯C,Ipl基本抛弃了,新版本的函数更多的只支持Mat,但要尤其注意赋值时深拷贝和浅拷贝问题。

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

 

//注意:深拷贝  
Mat a;  
Mat b = a.clone(); //a copy to b  
Mat c;  
a.copyTo(c); //a copy to c  

 

以下测试了OpenCV Mat类的常用拷贝的效率,详见代码

 1 int main(int argc, char* argv[])  
 2 {  
 3     Mat preFrame;  
 4     Mat curFrame;  
 5   
 6     preFrame = imread("E:\\001.bmp");  
 7     curFrame = imread("E:\\005.jpg");  
 8   
 9     cout<<"========直接用swap(浅拷贝)=========\n";  
10     int64 st1,et1;  
11     st1 = cvGetTickCount();  
12     for (int i=0;i<1001;i++)  
13     {  
14         swap(preFrame,curFrame);  
15     }  
16     et1 = cvGetTickCount();   
17     printf("swap 1000 times cost: %f milliseconds\n\n", (et1-st1)/(double)cvGetTickFrequency()/1000.0);   
18     imshow("frame 1",preFrame);  
19     imshow("frame 2",curFrame);  
20     cvWaitKey(-1);  
21   
22     cout<<"========通过第三者交换(浅拷贝)=========\n";  
23     Mat tmp;  
24     st1 = cvGetTickCount();  
25     for (int i=0;i<1001;i++)  
26     {  
27         tmp = preFrame;  
28         preFrame = curFrame;  
29         curFrame = tmp;  
30     }  
31     et1 = cvGetTickCount();   
32     printf("swap 1000 times cost: %f milliseconds\n\n", (et1-st1)/(double)cvGetTickFrequency()/1000.0);   
33       
34     imshow("frame 1",preFrame);  
35     imshow("frame 2",curFrame);  
36     cvWaitKey(-1);  
37   
38     cout<<"========强行拷贝(深拷贝)=========\n";  
39     st1 = cvGetTickCount();  
40     for (int i=0;i<1001;i++)  
41     {  
42         preFrame.copyTo(tmp);  
43         curFrame.copyTo(preFrame);  
44         tmp.copyTo(curFrame);  
45     }  
46     et1 = cvGetTickCount();   
47     printf("swap 1000 times cost: %f milliseconds\n", (et1-st1)/(double)cvGetTickFrequency()/1000.0);   
48     imshow("frame 1",preFrame);  
49     imshow("frame 2",curFrame);  
50     cvWaitKey(-1);  
51   
52     getchar();  
53     return 0;  
54 }  

结果为:

 

posted on 2016-12-15 10:20  时令  阅读(1023)  评论(0编辑  收藏  举报