OpenCV4.5.5学习笔记(四):OpenCV的常识学习(API,自动内存管理,argc与argv)

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

笔者本科时候有幸接触了OpenCV3.2.0版本的学习,后因考研压力不得不暂时停下学习的脚步,现在考研任务结束了,未来的导师也是从事的该方向,笔者又开始了新一轮的学习。回来发现OpenCV已经出到了4.5.5版本,遂重新下载新版本并决定记录这一学习历程。由于笔者水平有限,可能有错误之处还请诸位大佬多多包涵并烦请指出,让我们一起学习,共同进步。
首先需要说明的是:我是按着毛星云前辈编写的OpenCV3编程入门进行学习的,我会尽力把星云前辈的程序转成符合OpenCV4.5.5版本的。毛星云前辈于2021年12月11日不幸过世,他是我非常敬仰的一位业内大佬,我也是看他的书才开始接触OpenCV。


一、API 概念

所有OpenCV类和函数都放置在cv命名空间中。因此,要从代码中访问此功能,需要使用说明cv::符或using namespace cv指令:
如:

#include " opencv2/core.hpp "

cv::Mat H = cv::findHomography (points1, points2, cv::RANSAC , 5);

或者:

#include " opencv2/core.hpp "

using namespace cv;
Mat H = findHomography (points1, points2, RANSAC , 5);

需要说明的是,第二种形式有可能出现和其他命名空间冲突的风险。比如某个函数同时存在与两个命名空间之中,你必须指定自己使用的是究竟是哪个空间的这个函数。


二、自动内存管理

OpenCV 自动处理所有内存。
首先,函数和方法使用的 std::vector、cv::Mat和其他数据结构具有在需要时释放底层内存缓冲区的析构函数。这意味着析构函数并不总是像 Mat 那样释放缓冲区。他们考虑了可能的数据共享。析构函数递减与矩阵数据缓冲区关联的引用计数器。当且仅当引用计数器达到零时,即当没有其他结构引用同一缓冲区时,才会释放缓冲区。同样,当复制 Mat 实例时,并没有真正复制任何实际数据。相反,引用计数器会增加以记住相同数据的另一个所有者。还有一个 Mat::clone 方法可以创建矩阵数据的完整副本(在学习Mat时会详细说明这件事)。请参见官网上给出的示例:

代码如下(示例):

// create a big 8Mb matrix
Mat A(1000, 1000, CV_64F);
// create another header for the same matrix;
// this is an instant operation, regardless of the matrix size.
Mat B = A;
// create another header for the 3-rd row of A; no data is copied either
Mat C = B.row(3);
// now create a separate copy of the matrix
Mat D = B.clone();
// copy the 5-th row of B to C, that is, copy the 5-th row of A
// to the 3-rd row of A.
B.row(5).copyTo(C);
// now let A and D share the data; after that the modified version
// of A is still referenced by B and C.
A = D;
// now make B an empty matrix (which references no memory buffers),
// but the modified version of A will still be referenced by C,
// despite that C is just a single row of the original A
B.release();
// finally, make a full copy of C. As a result, the big modified
// matrix will be deallocated, since it is not referenced by anyone
C = C.clone();

三、argc与argv

在学习OpenCV的过程中,尤其是在官方程序和官方书籍《Learning OpenCV 3》中,我们经常能看到argc与argv这两个参数经常会出现在函数中作为形参传递,如该书中的第一个示例程序:
请添加图片描述
argc与argv中的arg表示的是“参数”,其中argc经常表现的是是int类型的整数,而argv带上*表示字符串数组。


总结

这一部分让我对OpenCV有了一个宏观的认识,了解了一些非常实用的常识。

猜你喜欢

转载自blog.csdn.net/qq_43264167/article/details/124212202
今日推荐