# 在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
提取的特征更多。