You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu18.04下OpenCV3.2倒角距离代码编译报错解决问询

解决OpenCV 3.2中倒角距离计算代码的头文件问题

问题描述

  • 系统环境:64位Ubuntu 18.04,OpenCV 3.2
  • 编译错误:
    fatal error: opencv2/contrib/contrib.hpp: No such file or directory
    
  • 已通过Synaptic安装libopencv-contrib-dev和libopencv-contrib-3.2,但在/usr/include/opencv2和/usr/lib/x86_64-linux-gnu路径下未找到contrib相关文件或文件夹
  • 待编译代码:
    #include "opencv2/imgproc/imgproc.hpp"
    #include "opencv2/highgui/highgui.hpp"
    #include "opencv2/contrib/contrib.hpp"
    #include <iostream>
    
    using namespace cv;
    using namespace std;
    
    int main( int argc, const char** argv )
    {
        Mat img = imread(argv[1], 0);
        Mat tpl = imread(argv[2], 0);
    
        Mat cimg;
        cvtColor(img, cimg, CV_GRAY2BGR);
    
        vector<vector<Point> > results;
        vector<float> costs;
        int best = chamerMatching( img, tpl, results, costs );
    
        return 0;
    }
    

解决方案

OpenCV 3.x版本对模块结构做了调整,原contrib模块的功能被拆分到多个子模块中,chamerMatching(倒角距离匹配)函数现在归属ximgproc扩展图像处理模块,需要按以下步骤修改:

  1. 替换头文件
    删除原有的#include "opencv2/contrib/contrib.hpp",替换为:
#include "opencv2/ximgproc/ximgproc.hpp"
  1. 编译时链接对应库
    编译命令需要额外添加-lopencv_ximgproc参数,以链接到倒角距离的实现代码。例如使用g++编译的命令:
g++ your_code.cpp -o output `pkg-config opencv --cflags --libs` -lopencv_ximgproc

pkg-config opencv --cflags --libs会自动引入OpenCV核心库的编译参数,补充-lopencv_ximgproc才能正确链接到目标函数。

  1. 验证库文件完整性
    如果仍出现链接错误,可重新安装libopencv-contrib-dev包,确保libopencv_ximgproc.so存在于/usr/lib/x86_64-linux-gnu目录:
sudo apt-get reinstall libopencv-contrib-dev

修正后的完整代码

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/ximgproc/ximgproc.hpp"
#include <iostream>

using namespace cv;
using namespace std;

int main( int argc, const char** argv )
{
    Mat img = imread(argv[1], 0);
    Mat tpl = imread(argv[2], 0);

    if (img.empty() || tpl.empty()) {
        cerr << "无法读取图像文件" << endl;
        return -1;
    }

    Mat cimg;
    cvtColor(img, cimg, CV_GRAY2BGR);

    vector<vector<Point> > results;
    vector<float> costs;
    int best = ximgproc::chamerMatching( img, tpl, results, costs );

    cout << "最佳匹配索引:" << best << endl;
    return 0;
}

注:添加了图像读取失败的判断逻辑,同时调用chamerMatching时需要加上ximgproc::命名空间前缀,避免命名冲突。

内容的提问来源于stack exchange,提问作者user27665

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 12:40:24