1.0 Display picture and 2.0 display picture comparison
在[【循序渐进地学好OpenCV&2】显示图片——OpenCV的“起手式”](http://blog.csdn.net/zgljl2012/article/details/48306299)这篇文章里,我们使用了OpenCV 1.0的API实现了从磁盘读取文件并显示,下面是代码:
#incldue "cv.h"#include "highgui.h"int main(intchar** argv){ IplImage* img = cvLoadImage(argv[1]); cvNamedWindow("Example1", CV_WINDOW_AUTOSIZE); cvShowImage("Example1", img); cvWaitKey(0); cvReleaseImage(&img); cvDestroyWindow("Example1");}
从上面我们可以看出这是明显的C风格的代码,首先是让指针指向一块分配好的内存数据,然后释放内存,如里面的cvReleaseImage。
But in 2.0 of the API, we can not write this, because the open CV2.0 version is already able to implement automated memory management.
下面我们使用2.0的API实现一下显示图片:
"highgui.h""cv.h"namespace cv;int"fruits.jpg"window"显示图片"// 将图片读入一个Mat// 创建一个窗口 namedWindow(window// 显示图片 imshow(window// 等待一个点击键盘事件 waitKey(0return0;}
就不贴了,当然成功了。代码的逻辑和1.0差不多,只是少了释放内存的代码,因为2.0 的OpenCV已经实现自动化内存管理里
Automated memory management for OpenCV 2.0
OpenCV对所有的内存实施自动化管理。首先,std::vector,Mat和其他的数据结构有它们自己的析构函数在需要的时候来负责释放底层的内存缓冲区。这意味着析构函数不是总是释放缓存。 以Mat为例,它是一个类,里面包含两个数据部分,矩阵头和一个指向存储所有像素值的矩阵的指针。矩阵头的大小是常数值,而矩阵的大小就与图像的大小有关,一般都会比矩阵头大上几个数量级。在OpenCV中,要进行大量的图像处理,因此也常常要在函数中传递Mat,这个时候,如果每次传递都将图像矩阵占据的内存一块拷贝一份的话,就会减慢处理速度;所以,除非有特殊要求,否则不应该传递图像数据。 所以,在我们拷贝Mat时OpenCV不会在给图像矩阵分配新内存了,而是给Mat创建了一个指向它的指针。并引用了计数机制,每添加一个Mat指向同一块图像矩阵的引用,计数加1;释放后计数减1。当计数为0时,表明没有指向它的指针,就释放这块内存。所以,OpenCV2.0能自动管理内存。
Let's look at the example below:
void Mat () {//Create a large matrix of 8MMat A ( +, +, cv_64f);//Create another same matrix header //This is an instantaneous operation because the size of the matrix is ignored.Mat B = A;//Create a matrix header that contains only the third row of a and no data is copiedMat C = B.row (3);//clone can copy the matrix itself, here is a copy of the matrix createdMat D = B.Clone();//CopyTo can also copy the matrix itself, but because a, B, C point to the same piece of matrix data //So this is the 5th line of the original matrix data is copied to line 3rdB.row (5). CopyTo (C);///Now let A and D share the data, but the matrix of the original A is also referenced by B and CA = D;//empty B (i.e. let it not reference memory), //The original a matrix is now only C also quoted, although C is just a row of dataB.release ();///Finally, copy a block of C-pointing memory, let C point to its new memory, so that the original a matrix data is released, //Because at this time, it is not referenced by any variablesc = C.Clone();}
PTR introduction
The mat above is OPENCV for automated memory management, so it's easy to use. But what about high-class classes and user-defined classes that implement automated memory management? OPENCV also provides these classes with Ptr<> template classes similar to the C++STL standard library. Just use it instead of the original pointer:
TT(...);//替换为:Ptr<TT(...);
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Learn opencv&4 gradually" Use the 2.0 API to display pictures and OpenCV's automated memory management