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

C++ 与 Python 混编

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

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

头文件须要包括git

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

using namespace boost::python;

c++调用python须要先初始python的相关东西。根据python的版本分开github

#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()。代码片断图下:app

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

而后判断python是否已经初始化框架

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

以后能够测试一下python是否可用直接在c++中写python语句,以下:python2.7

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)
#python能够直接使用下面这个
#find_package(PythonLibs REQUIRED)
#或者自定义lib和include
#SET(PYTHON_INCLUDE_DIRS /usr/include/python2.7)
#SET(PYTHON_LIBRARIES ${PYTHON2_LIBRARY})
#========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

相关文章
相关标签/搜索