OpenCV3.4.X中Nonfree模块的使用-SURF为例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhoukehu_CSDN/article/details/83145026

作者使用OpenCV3.4.3+VS2015+CMake3.8.2编译了包含opencv3.4.3以及opencv_contrib的完整的OpenCV库,因而能够使用tracking、saliency等非稳定模块。

在后续工作中又需要利用SURF进行实验,代码如下:

Ptr<SURF> surf = SURF::create(100);

但是运行时直接报错,控制台提示如下(Debug模式下):

【这里是坑,可跳到最后看如何解决】这里的意思大概是说,SURF属于收费模块,在CMake编译时要指定:OPENCV_ENABLE_NONFREE,于是作者重新设置CMake编译选项生成VS工程,并完整编译OpenCV库:

但是编译完成后,更新Opencv库,运行之前的代码时发现仍然报相同的错误。

【问题定位】最后作者想到根据异常信息来定位问题,根据之前的异常提示:输出异常的位置是Surf.cpp的1016行,打开源文件如下:

#include "precomp.hpp"
#include "surf.hpp"

namespace cv
{
namespace xfeatures2d
{

#ifdef OPENCV_ENABLE_NONFREE

//...

Ptr<SURF> SURF::create(double _threshold, int _nOctaves, int _nOctaveLayers, bool _extended, bool _upright)
{
    return makePtr<SURF_Impl>(_threshold, _nOctaves, _nOctaveLayers, _extended, _upright);
}

#else // ! #ifdef OPENCV_ENABLE_NONFREE
Ptr<SURF> SURF::create(double, int, int, bool, bool)
{
    CV_Error(Error::StsNotImplemented,
        "This algorithm is patented and is excluded in this configuration; "
        "Set OPENCV_ENABLE_NONFREE CMake option and rebuild the library");
}
#endif

}
}

仔细一看,如果在编译时如果定义了OPENCV_ENABLE_NONFEE那么就抛出异常提示:SURF不能使用,反之正常编译。所以问题出在这里:1)不清楚哪里定了的OPENCV_ENABLE_NONFREE,因为作者在利用CMake编译时,勾选或者不勾选OPENCV_ENABLE_NONFREE时现象一样;2)定义了ENABLE_NONFREE,反而不让你用,不能理解。

【解决方法】但是,显然这还比较好解决的,稍微改下Surf.cpp代码去掉条件编译指令,如下:

#include "precomp.hpp"
#include "surf.hpp"

namespace cv
{
namespace xfeatures2d
{

//#ifdef OPENCV_ENABLE_NONFREE

//...

//#else // ! #ifdef OPENCV_ENABLE_NONFREE
//Ptr<SURF> SURF::create(double, int, int, bool, bool)
//{
//    CV_Error(Error::StsNotImplemented,
//        "This algorithm is patented and is excluded in this configuration; "
//        "Set OPENCV_ENABLE_NONFREE CMake option and rebuild the library");
//}
//#endif

}
}

然后,也不需要完全重新编译整个OpenCV工程,仅需要编译xfeatures2d项目即可,新生成的文件如下:

最后将生成的新的dll和lib覆盖原来的,用之前的代码进行测试,发现SURF就可以正常使用了。

猜你喜欢

转载自blog.csdn.net/zhoukehu_CSDN/article/details/83145026
今日推荐