【C++】自定义函数的封装和调用

在做高翔《一起做RGB-D SLAM》系列过程中,由于工程较大,需要将自己写的函数进行封装,方便调用,将函数的封装和调用过程记录下来,方便查阅

  • 函数的封装

     将需要封装的函数的声明和定义分别放在头文件(.h)和源文件(.cpp)中
     头文件:包含了库的引用,数据类型的定义,结构体定义,函数声明
     源文件:函数定义
    

以特征点检测和匹配的函数为例
feature_detect.h

#pragma once

#include 
#include 

#include 
#include 
#include 
#include 

#include 
#include 

typedef pcl::PointXYZRGBA PointT;
typedef pcl::PointCloud<PointT> PointCloud;

using namespace std;
using namespace cv;

struct CAMERA_INTRINSIC_PARAMETERS
{
    double cx,cy,fx,fy,scale;
};

vector<DMatch> feature_extract(Mat& rgb1,Mat& rgb2);

feature_detect.cpp

vector<DMatch> feature_extract(Mat& rgb1,Mat& rgb2)
{
    Ptr<FeatureDetector> detector;
    Ptr<DescriptorExtractor> descriptor;
    
    detector = ORB::create();
    descriptor = ORB::create();

    
    vector<KeyPoint> kp1,kp2;
    detector->detect(rgb1,kp1);
    detector->detect(rgb2,kp2);
    
    cout<<"Key point if two image:"<<kp1.size()<<", "<<kp2.size()<<endl;
    
    
    
    Mat desp1,desp2;
    descriptor->compute(rgb1,kp1,desp1);
    descriptor->compute(rgb2,kp2,desp2);
    
    vector<DMatch> matches;
    BFMatcher matcher;
    matcher.match(desp1,desp2,matches);
    cout<<"Find total"<<matches.size()<<" matches."<<endl;
    
    vector<DMatch> goodmatches;
    double minDis = 9999;
    for(size_t i = 0;i<matches.size();i++)
    {
        if(matches[i].distance<minDis)
	  minDis = matches[i].distance;
    }
    cout<<"min dis:"<<minDis<<endl;
    
    for(size_t i = 0;i<matches.size();i++)
    {
        if(matches[i].distance<10*minDis)
	  goodmatches.push_back(matches[i]);
    }
   return goodmatches;
}
  • 封装函数的调用
  1. 首先在CMakeLists中加入以下内容:

CMakeLists.txt


//将feature_detect.cpp编译为库feature_detect
add_library(feature_detect feature_detect.cpp)

//添加执行文件
add_executable(main main.cpp)

//为执行文件main链接上feature_detect库
target_link_libraries(main  slambase ${OpenCV_LIBS} ${PCL_LIBRARIES})
  1. 在main.cpp中包含feature_detect.h,调用feature_detect.h中函数
#include 
#include "feature_detect.h"

int main(int argc, char **argv) {
    Mat rgb1 = imread( "./data/rgb1.png");
    Mat rgb2 = imread( "./data/rgb2.png");
    
    vector<DMatch> matches = feature_extract(rgb1,rgb2);
    return 0;
}

你可能感兴趣的:(【C++】自定义函数的封装和调用)