Opencv undefined reference to `cv::imread() Ubuntu编译

Ubuntu下编译一个C++文件,C++源程序中使用了opencv,opencv的安装没有问题,但是在编译的过程中出现如下错误:

undefined reference to `cv::imread(std::string const&, int)'
undefined reference to `cv::noArray()'
undefined reference to `cv::_OutputArray::_OutputArray(cv::Mat&)'
undefined reference to `cv::_InputArray::_InputArray(cv::Mat const&)'
undefined reference to `cv::imwrite(std::string const&, cv::_InputArray const&, std::vector<int, std::allocator<int> > const&)'
undefined reference to `cv::_InputArray::_InputArray(cv::Mat const&)'
undefined reference to `cv::imshow(std::string const&, cv::_InputArray const&)'
undefined reference to `cv::waitKey(int)'
...

undefined reference to `cv::Mat::deallocate()'
...

网上查了下资料,大概说opencv的静态编译库没有链接到本程序中(也不知道对不对,望大家指正),于是找啊找啊,终于找到一个有用的,记录一下:

在terminal下运行命令: g++ getmask.cpp -o getmask `pkg-config opencv --cflags --libs` // 包含、链接参数一定要放在后面,其实就是在编译C++程序后面加上(`pkg-config opencv --cflags --libs`)

编译成功后生成getmask可执行文件,接着运行命令:./getmask 就能得到结果啦。

 

附上我的源程序:

#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
{
    string img_filename;
    int head_num;
    int posx,posy;
    cv::Point pt;
    vector<Point> coordinate;
    vector<vector<Point> > coordinates;
    ifstream infile("scene01.txt");
    Mat img = imread("scene01.jpg",1);
    //namedWindow("MyWindow", CV_WINDOW_AUTOSIZE);
    //imshow("MyWindow", img);
    //waitKey(0);
    cv::Mat locMask(img.rows,img.cols,CV_8UC1,cv::Scalar(0));
    //imshow("locMask",locMask);
    while (infile >> img_filename >> head_num) {
        for(int i = 0 ; i< head_num;i++) {
            infile >> posx >> posy;
            pt = Point(posx,posy);
            coordinate.push_back(pt);
        }
        coordinates.push_back(coordinate);
    }
    //cout<<coordinate.size()<<endl;
    //cout<<coordinates.size()<<endl;
    for(int i=0;i<coordinates.size();i++)
        cout<<coordinates[i]<<" ";
    drawContours(locMask,coordinates,-1,cv::Scalar::all(255), CV_FILLED);
    imwrite("mask01.jpg",locMask);
    imshow("locMask",locMask);
    waitKey(0);
    return 0;
}

我的文件截图:

版权声明:本文为博主原创文章,欢迎转载,转载请注明原文地址、作者信息。

原文地址:https://www.cnblogs.com/wmr95/p/8193418.html