如何在 OpenCV 3.0 中使用 SIFT 和 c++

How do I use SIFT in OpenCV 3.0 with c++?

本文关键字:SIFT c++ OpenCV      更新时间:2023-10-16

我有OpenCV 3.0,我已经用opencv_contrib模块编译并安装了它,所以这不是问题。不幸的是,以前版本的示例不适用于当前版本,因此,尽管这个问题已经被问了不止一次,但我想要一个我可以实际使用的更新示例。即使是官方示例也在此版本中不起作用(功能检测有效,但不适用于其他功能示例(,并且无论如何它们都使用 SURF。

那么,如何在C++上使用OpenCV SIFT?我想抓住两张图像中的关键点并匹配它们,类似于此示例,但即使只是获得点和描述符也足够帮助。帮助!

  1. 获取opencv_contrib存储库
  2. 花点时间阅读自述文件,将其添加到您的主要 OpenCV CMAKE 设置中
  3. 在主 OpenCV 存储库中重新运行 cmake/make/install

然后:

   #include "opencv2/xfeatures2d.hpp"
  // 
  // now, you can no more create an instance on the 'stack', like in the tutorial
  // (yea, noticed for a fix/pr).
  // you will have to use cv::Ptr all the way down:
  //
  cv::Ptr<Feature2D> f2d = xfeatures2d::SIFT::create();
  //cv::Ptr<Feature2D> f2d = xfeatures2d::SURF::create();
  //cv::Ptr<Feature2D> f2d = ORB::create();
  // you get the picture, i hope..
  //-- Step 1: Detect the keypoints:
  std::vector<KeyPoint> keypoints_1, keypoints_2;    
  f2d->detect( img_1, keypoints_1 );
  f2d->detect( img_2, keypoints_2 );
  //-- Step 2: Calculate descriptors (feature vectors)    
  Mat descriptors_1, descriptors_2;    
  f2d->compute( img_1, keypoints_1, descriptors_1 );
  f2d->compute( img_2, keypoints_2, descriptors_2 );
  //-- Step 3: Matching descriptor vectors using BFMatcher :
  BFMatcher matcher;
  std::vector< DMatch > matches;
  matcher.match( descriptors_1, descriptors_2, matches );

另外,不要忘记链接opencv_xfeatures2d!

有有用的答案,但我会添加我的版本(对于 OpenCV 3.X(,以防上述版本不清楚(经过测试和尝试(:

  1. 将 opencv 从 https://github.com/opencv/opencv 克隆到家庭目录
  2. 将opencv_contrib从 https://github.com/opencv/opencv_contrib 克隆到主目录
  3. 在 opencv 中,创建一个名为 build 的文件夹
  4. 使用此 CMake 命令激活非自由模块:cmake -DOPENCV_EXTRA_MODULES_PATH=/home/YOURUSERNAME/opencv_contrib/modules -DOPENCV_ENABLE_NONFREE:BOOL=ON ..(请注意,我们显示了 contrib 模块所在的位置,并激活了非自由模块(
  5. make事后make install

上述步骤应该适用于OpenCV 3.X

之后,您可以使用带有相应标志的 g++ 运行以下代码:

g++ -std=c++11 main.cpp `pkg-config --libs --cflags opencv` -lutil -lboost_iostreams -lboost_system -lboost_filesystem -lopencv_xfeatures2d -o surftestexecutable

不要忘记将 xfeatures2D 库与 -lopencv_xfeatures2d 链接,如命令所示。main.cpp文件是:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "opencv2/xfeatures2d.hpp"
#include "opencv2/xfeatures2d/nonfree.hpp"
using namespace cv;
using namespace std;
int main(int argc, const char* argv[])
{
    const cv::Mat input = cv::imread("surf_test_input_image.png", 0); //Load as grayscale
    Ptr< cv::xfeatures2d::SURF> surf =  xfeatures2d::SURF::create();
    std::vector<cv::KeyPoint> keypoints;
    surf->detect(input, keypoints);
    // Add results to image and save.
    cv::Mat output;
    cv::drawKeypoints(input, keypoints, output);
    cv::imwrite("surf_result.jpg", output);

    return 0;
}

这应该创建并保存带有冲浪关键点的图像。