# 在OpenCV中使用SURF

作为图像对齐常使用的特征提取算法,ORB速度最快,但是效果较差,对光照变化的处理也差一些,有时候提取取的特征点比较少,影响使用。SIFT准确率最高,但速度很慢。作为SIFT的替代,SURF特征提取方法是性能和速度比较平衡的方法,不过SURF算法目前还受专利保护,在OpenCV中的实现在contrib包中,且必须打开OPENCV_ENABLE_NONFREE cmake编译选项,这在研究中使用是允许的,但用于商业盈利活动就会侵权。

# 编译报错及解决

"""
terminate called after throwing an instance of 'cv::Exception'
  what():  OpenCV(4.5.5) /home/xx/opencv/opencv_contrib-4.x/modules/xfeatures2d/src/surf.cpp:1027: error: (-213:The function/feature is not implemented) This algorithm is patented and is excluded in this configuration; Set OPENCV_ENABLE_NONFREE CMake option and rebuild the library in function 'create'

Aborted (core dumped)
"""

使用SURF的应用程序编译成功了,但是在运行时报错如上,正如提示中所说,要想使用SURF需要在OpenCV源码编译时设置参数OPENCV_ENABLE_NONFREE=ON

cmake -DOPENCV_EXTRA_MODULES_PATH=opencv_contrib/modules -DOPENCV_GENERATE_PKGCONFIG_INFO=YES -DCMAKE_INSTALL_PREFIX=XXX -DCMAKE_BUILD_TYPE=RELEASE -DOPENCV_ENABLE_NONFREE=ON ..

# OpenCV 使用SURF示例

#include <opencv2/xfeatures2d.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/features2d.hpp>

int main()
{
    cv::Ptr<cv::Feature2D> feat_extractor = cv::xfeatures2d::SURF::create(400);
    std::vector<cv::KeyPoint> kpts;
    cv::Mat descs;
    std::string image_file = "/mnt/data/code/basic_cplusplus_examples/data/lk_optical_flow/000000.png";
    cv::Mat img = cv::imread(image_file);
    feat_extractor->detectAndCompute(img, cv::noArray(), kpts, descs);
    cv::drawKeypoints(img, kpts, img, cv::Scalar(129,189,11));
    cv::imshow("image", img);
    cv::waitKey(0);
}

编译:

g++ main.cpp -o main `pkg-config --cflags --libs opencv4`
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/mnt/data/sw/opencv/opencv48/install/lib

执行的结果如下:

可以看到SURF提取的特征更多。

(adsbygoogle = window.adsbygoogle || []).push({});