我想用 Boost.python 用 OpenCV 编译一个 C++ 程序以在 python 脚本中使用

问题描述

首先,我编写了这个 C++ 程序。

#include <iostream>
#include <vector>
#include <string>
#include <filesystem>
#include <cstdlib>
#include <dirent.h>
#include <opencv2/opencv.hpp>
#include <boost/python.hpp>

using namespace std;

string process(string argv){
    std::string input_path = argv;

    cv::Mat input_img = cv::imread("./input/"+input_path,cv::IMREAD_UNCHANGED);
    cout<<input_img.size();
    cv::Mat red_img = input_img.clone();
    red_img = cv::Scalar(0,255);
    cv::Mat gray_img;
    cv::Mat bin_img;
    cv::Mat diff_r;

    cv::absdiff(red_img,input_img,diff_r);

    //RGB image to Grayscale image
    cv::cvtColor(diff_r,gray_img,cv::COLOR_RGB2GRAY);

    //cv::Mat diff_gray = cv::Mat(input_img.size(),CV_16U,cv::Scalar(sum(diff_r.at<cv::Vec3b>())));

    //Grayscale image to Binary image
    cv::threshold(gray_img,bin_img,255,cv::THRESH_BINARY | cv::THRESH_OTSU);

    cv::imwrite("./output/"+input_path,bin_img);
    return input_path;
}

BOOST_PYTHON_MODULE( cv2_cpp )
{
    boost::python::def("process",process);
}

我想编译它以在 Python 中使用。 然后,这样做;

$ g++ -shared -fPIC -std=c++11 -Wall -I/usr/local/include -I/usr/local/Cellar/opencv/4.5.1_2/include/opencv4 -L/usr/local/lib \
    $(python3-config --includes --ldflags --embed) `python-config --ldflags`  -lboost_python39 \
   main.cpp -o cv2_cpp.so

错误

Undefined symbols for architecture x86_64:
  "cv::Mat::Mat()",referenced from:
      process(std::__1::basic_string<char,std::__1::char_traits<char>,std::__1::allocator<char> >) in main-9a3c3f.o
  "cv::Mat::~Mat()",std::__1::allocator<char> >) in main-9a3c3f.o
  "cv::Mat::operator=(cv::Scalar_<double> const&)",std::__1::allocator<char> >) in main-9a3c3f.o
  "cv::imread(std::__1::basic_string<char,std::__1::allocator<char> > const&,int)",std::__1::allocator<char> >) in main-9a3c3f.o
  "cv::absdiff(cv::_InputArray const&,cv::_InputArray const&,cv::_OutputArray const&)",std::__1::allocator<char> >) in main-9a3c3f.o
  "cv::imwrite(std::__1::basic_string<char,std::__1::vector<int,std::__1::allocator<int> > const&)",std::__1::allocator<char> >) in main-9a3c3f.o
  "cv::cvtColor(cv::_InputArray const&,cv::_OutputArray const&,int,std::__1::allocator<char> >) in main-9a3c3f.o
  "cv::threshold(cv::_InputArray const&,double,std::__1::allocator<char> >) in main-9a3c3f.o
  "cv::Mat::clone() const",std::__1::allocator<char> >) in main-9a3c3f.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command Failed with exit code 1 (use -v to see invocation)

我的 Python 是 3.9.0 版,因为我发现 Boost.python 仅适用于 Python 3.9。
在我的环境中,我可以将没有 OpenCV 的 C++ 程序编译为 .so 并在 Python 中使用。
另外,我可以使用 OpenCV 将 C++ 编译为 .out。
但是,当我用 OpenCV 将 C++ 程序编译为 .so 时,出现错误
这是什么原因造成的?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)