ubuntu下C++与Python混编,opencv中mat类转换

C++ 与 Python 混编

因为赶项目进度,需要使用到深度学习的内容,不过现有的深度学习框架大多使用python代码,对于不会改写C++的朋友来说,需要耗费大量的时间去改写,因此,使用python与C++混编可以快速的查看效果,并作出选择。

在c++中使用混编python需要用到基础头文件Python.h,最好需要使用boost中的python,boost将底层python重新封装,更好的使用c++调用python。

头文件需要包括

#include <Python.h>
#include <boost/python.hpp>

using namespace boost::python;

c++调用python需要先初始python的相关东西。根据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;
    }

在项目的开始需要调用inti_ar()。代码片段图下:

    init_ar();
    char str[] = "Python";
    Py_SetProgramName(str);

然后判断python是否已经初始化

if(!Py_IsInitialized())
        cout << "init faild/n" << endl;

之后可以测试一下python是否可用直接在c++中写python语句,如下:

    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");

之后需要调用python的文件:

    PyObject *pModule,*pFunc,*pDict;
    PyObject *pArgs, *pValue;

    pModule = PyImport_ImportModule("add_module"); //    调用python文件
    if (pModule == NULL) {  
        cout<<"ERROR importing module"<<endl; 
        return false; 
    } 

    pDict = PyModule_GetDict(pModule);

    pFunc = PyDict_GetItemString(pDict, (char*)"add");  //得到函数


    /* build args */

    PyObject *pArgs1 = Py_BuildValue("i", 5);
    PyObject *pArgs2 = Py_BuildValue("i", 3);


    if(pFunc != NULL) { 
        pValue = PyObject_CallFunction(pFunc, "OO",pArgs1,pArgs2 );   //传入两个值
    }else{
        cout<<"function error!"<<endl;
        
    }

其中add_module是python的文件名,add是python中的函数名。 这样就可以通过调用python的加法运算。

C++与Python传输Mat类

opencv中有C++和Python两个接口,其中cv2.hpp中就有两者转换的代码,但是估计很多人不会使用,因此就有人提取出来,在github上搜pyboostcvconverter这个就可以搜到https://github.com/Algomorph/pyboostcvconverter,我这里就讲一下如何使用。

原项目中cmakelist有点复杂,简化一下:

cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
project("pbcvt")

#----------------------------CMAKE & GLOBAL PROPERTIES-------------------------#
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")

###============= C++11 support====================================
include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if (COMPILER_SUPPORTS_CXX11)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif (COMPILER_SUPPORTS_CXX0X)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else ()
    message(FATAL_ERROR "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
endif ()


#=============== Find Packages 
find_package(OpenCV  REQUIRED)
include("DetectPython")

find_package(Boost COMPONENTS REQUIRED python)


#========pick python stuff========================================

SET(PYTHON_INCLUDE_DIRS /usr/include/python2.7)
SET(PYTHON_LIBRARIES ${PYTHON2_LIBRARY})
SET(PYTHON_EXECUTABLE ${PYTHON2_EXECUTABLE})
SET(PYTHON_PACKAGES_PATH ${PYTHON2_PACKAGES_PATH})
SET(ARCHIVE_OUTPUT_NAME pbcvt_py2)


add_executable(project 
${CMAKE_CURRENT_SOURCE_DIR}/src/pyboost_cv2_converter.cpp 
${CMAKE_CURRENT_SOURCE_DIR}/src/test.cpp 
${CMAKE_CURRENT_SOURCE_DIR}/src/pyboost_cv3_converter.cpp 
${CMAKE_CURRENT_SOURCE_DIR}/include/pyboostcvconverter/pyboostcvconverter.hpp)

target_include_directories(project PUBLIC 
${CMAKE_CURRENT_SOURCE_DIR}/include 
${Boost_INCLUDE_DIRS} 
${OpenCV_INCLUDE_DIRS} 
${PYTHON_INCLUDE_DIRS}
${PCL_INCLUDE_DIRS})

target_link_libraries(project ${Boost_LIBRARIES} ${OpenCV_LIBS} ${PYTHON_LIBRARIES} ${PCL_COMMON_LIBRARIES} ${PCL_IO_LIBRARIES})




代码中名空间需要加上using namespace pbcvt; 传如图片和化先将图片转化为PyObject类型在进行传输就可以了。注意python中image是使用numpy类型。

代码如下:https://github.com/myBestLove/cppPython

猜你喜欢

转载自my.oschina.net/u/1046919/blog/1821122