SlamBook14讲-FeatureExtraction

ch7

FeatureExtraction 在书中源码的基础上简单修改 自己敲了一遍 顺便复习vector迭代器

需要安装opencv3 涉及到opencv共存问题

执行前可以先查看opencv版本

pkg-config --modversion opencv

参考这篇文章:

Ubuntu下多版本OpenCV共存和切换_W_Tortoise的博客-CSDN博客_ubuntu opencv多版本

源码:

#include 
#include 
#include 

int main(){

    cv::Mat img1 = cv::imread("../1.png",1);
    cv::Mat img2 = cv::imread("../2.png",1);

    std::vector KeyPoint1,KeyPoint2;
    cv::Mat descriptors1,descriptors2;
    cv::Ptr detector = cv::ORB::create();//represented as vectors in a multidimensional space
    cv::Ptr descriptor = cv::ORB::create();//初始化描述子 descriptor为指针
    cv::Ptr matcher = cv::DescriptorMatcher::create("BruteForce-Hamming");

    detector->detect(img1,KeyPoint1);
    detector->detect(img2,KeyPoint2);

    descriptor->compute(img1,KeyPoint1,descriptors1);
    descriptor->compute(img2,KeyPoint2,descriptors2);

    // cv::Mat outimg1;
    // cv::drawKeypoints(img1,KeyPoint1,outimg1);
    // cv::imshow("img1特征点",outimg1);
    //可以看出descriptor描述子每个元素都是0-255 意味着二进制的编码
    //std::cout << descriptors1 << std::endl;
    std::vector matches;
    matcher->match(descriptors1,descriptors2,matches);
    //可以看到结果不理想,很多误匹配的点,需要设置阈值筛选
    // cv::Mat matchimg;
    // cv::drawMatches(img1,KeyPoint1,img2,KeyPoint2,matches,matchimg);
    // cv::imshow("特征匹配",matchimg);

    //迭代器遍历 for遍历也行
    double min = 10000,max = 0;
    min = min_element( matches.begin(), matches.end(), [](const cv::DMatch& m1, const cv::DMatch& m2) {return m1.distancedistance;
    max = max_element( matches.begin(), matches.end(), [](const cv::DMatch& m1, const cv::DMatch& m2) {return m1.distancedistance;

    std::vector GoodMatches;
    for(auto i = matches.begin(); i < matches.end(); i++){
        if(i->distance <= std::max( 2*min, 30.0 )){
            GoodMatches.push_back(*i);
        }
    }

    cv::Mat GoodMatchimg;
    cv::drawMatches(img1,KeyPoint1,img2,KeyPoint2,GoodMatches,GoodMatchimg);
    cv::imshow("特征匹配",GoodMatchimg);

    cvWaitKey(0);
    return 0;
}

其中imshow注意路径为"../xxxxx",文件放在build文件夹上层

使用的vscode联合CMake

CMakeLists:

cmake_minimum_required(VERSION  2.8)

project(vo1)

set(CMAKE_BUILD_TYPE "release")
set(CMAKE_CXX_FLAGS "-std=c++11 -O3")

list( APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake_modules )
find_package( OpenCV REQUIRED)

include_directories("/usr/local/opencv3")

add_executable(FeatureExtraction feature_extraction.cpp)
target_link_libraries(FeatureExtraction ${OpenCV_LIBS})

主要是find_package,之后把opencv3的路径包含进来即可,需要在安装的时候sudo make install指定目录OpenCV是包,LIBS是库,INCLUDE_DIR是头文件。

cmake .. make ./FeatureExtraction运行结果

SlamBook14讲-FeatureExtraction_第1张图片

 

你可能感兴趣的:(opencv,计算机视觉,c++)