Ubuntu环境下Python+Opencv 与C++ 联合编程

  在之前的工作中遇到需要在C++的工程中调用python函数处理图片的问题,并且需要在python和C++之间传递opencv读取的图片文件。经过一番研究和尝试之后,找到了一个可行的解决方法,特此整理一下,避免遗忘。
  这个工作主要还是借鉴参考了Github上的两个开源项目,因此首先把两个项目clone下来

git clone https://github.com/Algomorph/pyboostcvconverter.git
git clone https://github.com/myBestLove/cppPython.git

  第一个项目提供了将C++中cv::Mat形式的图片转换成python中array格式的方法,第二个项目则是提供了两个C++和Python连个编程的样例
  首先编译第一个项目

cd pyboostcvconverter
mkdir build
cd build
cmake ..

  这一步可能会报错,因为这个项目默认python版本为python3,如果系统自带python3路径没有设置对或者numpy库没有安装,可能会出现如下错误

ModuleNotFoundError: No module named 'numpy'
CMake Warning at /usr/share/cmake-3.10/Modules/FindBoost.cmake:1626 (message):
  No header defined for python3; skipping header check
Call Stack (most recent call first):
  CMakeLists.txt:60 (find_package)


-- Could NOT find Python (missing: PYTHON_NUMPY_INCLUDE_DIRS) 
CMake Error at CMakeLists.txt:94 (message):
  Not all requred components of Numpy/Python found.

  目前有两个解决方案,一个就是把默认版本换成Python2的,而且将要介绍的第二个项目目前也只支持Python2,如果使用Python3会各种报错,我暂时还没解决。将默认版本改为python2,只需要在cmake时增加一个指令

cmake .. -DPYTHON_DESIRED_VERSION=2.X

  另一个解决方案就是手动添加一下python3的路径,这里使用cmake-gui比较方便

sudo apt install cmake-gui
cmake-gui ..

在这里插入图片描述
  需要设置PYTHON_NUMPY_INCLUDE_DIRS的路径,我这里已经设置好了,我的路径为/home/fyj/.local/lib/python3.6/site-packages/numpy/core/include,自己需要根据安装路径进行修改。修改完成后点击Configure按键,再点击Generate按键出现以下内容,就cmake完成了。
在这里插入图片描述
  关闭窗口,开始编译

make

  没有报错的话第一个项目就编译完成了,然后处理第二个项目。还是相似的过程cmake make等等

cd cppPython
mkdir build
cd build
cmake ..
make

  这里可能会出现一个报错

In file included from /home/fyj/ImageMatch/cppPython/src/pyboost_cv3_converter.cpp:164:0:
/usr/include/c++/7/iostream:60:10: error: ‘istream’ does not name a type; did you mean ‘strcat’?
   extern istream cin;  /// Linked to standard input
          ^~~~~~~
          strcat
/usr/include/c++/7/iostream:61:10: error: ‘ostream’ does not name a type; did you mean ‘strcat’?
   extern ostream cout;  /// Linked to standard output
          ^~~~~~~
          strcat
/usr/include/c++/7/iostream:62:10: error: ‘ostream’ does not name a type; did you mean ‘strcat’?
   extern ostream cerr;  /// Linked to standard error (unbuffered)
          ^~~~~~~
          strcat
/usr/include/c++/7/iostream:63:10: error: ‘ostream’ does not name a type; did you mean ‘strcat’?
   extern ostream clog;  /// Linked to standard error (buffered)
          ^~~~~~~
          strcat
/usr/include/c++/7/iostream:66:10: error: ‘wistream’ does not name a type; did you mean ‘system’?
   extern wistream wcin;  /// Linked to standard input
          ^~~~~~~~
          system
/usr/include/c++/7/iostream:67:10: error: ‘wostream’ does not name a type; did you mean ‘system’?
   extern wostream wcout; /// Linked to standard output
          ^~~~~~~~
          system
/usr/include/c++/7/iostream:68:10: error: ‘wostream’ does not name a type; did you mean ‘system’?
   extern wostream wcerr; /// Linked to standard error (unbuffered)
          ^~~~~~~~
          system
/usr/include/c++/7/iostream:69:10: error: ‘wostream’ does not name a type; did you mean ‘system’?
   extern wostream wclog; /// Linked to standard error (buffered)
          ^~~~~~~~
          system
/usr/include/c++/7/iostream:74:10: error: ‘ios_base’ does not name a type; did you mean ‘isspace’?
   static ios_base::Init __ioinit;
          ^~~~~~~~
          isspace
CMakeFiles/add.dir/build.make:110: recipe for target 'CMakeFiles/add.dir/src/pyboost_cv3_converter.cpp.o' failed
make[2]: *** [CMakeFiles/add.dir/src/pyboost_cv3_converter.cpp.o] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/add.dir/all' failed
make[1]: *** [CMakeFiles/add.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

  此时只需要把/pyboostcvconverter/src/里的pyboost_cv3_converter.cpp文件复制到/cppPython/src/中取代原有的文件。再次编译,成功后可以测试项目提供的两个样例

./add

出现以下内容

Hello Python!
10
20
10+20=30

  第二个样例,是将图片旋转90度显示出来,这里要注意修改图片的路径,一起看一下src/image.cpp文件的内容

#define PY_ARRAY_UNIQUE_SYMBOL pbcvt_ARRAY_API

#include <boost/python.hpp>
#include <pyboostcvconverter/pyboostcvconverter.hpp>
#include <Python.h>
#include <string>
#include <opencv2/opencv.hpp>
#include <fstream>
#include <sys/time.h>




using namespace cv;
using namespace std;
using namespace pbcvt;

    using namespace boost::python;



#if (PY_VERSION_HEX >= 0x03000000)

    static void *init_ar() {
#else
        static void init_ar(){
#endif
        Py_Initialize();

        import_array();
        return NUMPY_IMPORT_ARRAY_RETVAL;
    }


    

PyObject *pModule,*pFunc,*pDict;
//定义一个图像处理函数
void trans(cv::Mat image){

    /* import */
    pModule = PyImport_ImportModule("image_module");//加载Python文件,image_module是Python文件的名字
    if (pModule == NULL) {  
        cout<<"ERROR importing module"<<endl; 
        return ; 
    } 

    pDict = PyModule_GetDict(pModule);//获取Python文件中函数字典

    pFunc = PyDict_GetItemString(pDict, (char*)"trans_image");//获取Python文件中的函数,trans_image是函数名称

    PyObject  *iArgs = pbcvt::fromMatToNDArray(image);//讲cv::Mat格式的图片转换成Python中的array格式

    PyObject *pValue;//创建对象保存函数返回值
    if(pFunc != NULL) { 
        pValue = PyObject_CallFunction(pFunc, "O",iArgs );
        //调用Python函数,并将iArgs对应的参数传递进去,“O”(字母O)表示只有一个参数,“OO”则表示有两个参数,依次类推
    }
    cv::Mat trans_image = pbcvt::fromNDArrayToMat(pValue);//把Python格式的图像转换为cv::Mat格式
    imshow("a",trans_image);//显示图片
    waitKey(0);
}


int main(int argc, char *argv[])
{
    // Py_Initialize();
    // import_array();
    init_ar();
    char str[] = "Python";
    Py_SetProgramName(str);
    if(!Py_IsInitialized())
        cout << "init faild/n" << endl;
    // 下面可以只是方便调试,可以不用。
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('../python')");
    PyRun_SimpleString("import os");
    PyRun_SimpleString("print os.getcwd()");
    PyRun_SimpleString("print ('Hello Python!')\n");

    cv::Mat image = cv::imread("/home/fyj/ImageMatch/20.jpg",0);//读取图片,注意此处的路径需要修改为自己图片所在路径
    trans(image);//执行上面定义的函数
    return 0;
}

  修改好图片路径后,重新make编译一下,然后执行./image

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

深视

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值