ubuntu下C++如何调用python程序,gdb调试C++代码

前端之家收集整理的这篇文章主要介绍了ubuntu下C++如何调用python程序,gdb调试C++代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Linux下gdb调试C++代码:http://jingyan.baidu.com/article/acf728fd464984f8e410a369.html

主要ubuntu下使用C++调用Python:

#python代码:(processing_module.py)

import cv2    

def pre_processing():
    imgfile = "./IMG_3200.png"    
    img = cv2.imread(imgfile)    
    h,w,_ = img.shape    
    
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)    
    
    ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)    
    
    # Find Contour    
    _,contours,hierarchy = cv2.findContours( thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)    
    
    # 需要搞一个list给cv2.drawContours()才行!!!!!    
    c_max = []  
    max_area = 0  
    max_cnt = 0  
    for i in range(len(contours)):  
        cnt = contours[i]  
        area = cv2.contourArea(cnt)  
        # find max countour  
        if (area>max_area):  
            if(max_area!=0):  
                c_min = []  
                c_min.append(max_cnt)  
                cv2.drawContours(img,c_min,-1,(0,0),cv2.FILLED)  
            max_area = area  
            max_cnt = cnt  
        else:  
            c_min = []  
            c_min.append(cnt)  
            cv2.drawContours(img,cv2.FILLED)  
  
    c_max.append(max_cnt)  
    cv2.drawContours(img,c_max,(255,255),thickness=-1)    
    
    cv2.imwrite("mask.png",img)    
    #cv2.imshow('mask',img)    
    #cv2.waitKey(0)  

def p(a):
    return a+1

if __name__ == "__main__":
    pre_processing()
    print (p(1))


C++代码:(cpp_python.cpp)

#include <Python.h> 
#include <iostream>
#cinlude <string>

using namespace std;

void img_processing();
int great_function_from_python(int a);

int main() 
{ 
    Py_Initialize(); 

    //python 2.7 和 python 3.5是有区别的。
    //python 3.5需要用wchar_t
    char str[] = "Python";
    Py_SetProgramName(str);
    if(!Py_IsInitialized())
        cout << "init faild/n" << endl;
    # 下面可以只是方便调试,可以不用。
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");
    PyRun_SimpleString("import cv2");
    PyRun_SimpleString("import numpy as np");
    PyRun_SimpleString("print ("Hello Python!")\n");

    img_processing();

    int sum = great_function_from_python(2);
    cout << "sum:" << sum << endl;

    Py_Finalize(); 

    return 0; 
} 

# 不需要传入参数和返回参数
void img_processing()
{
    PyObject * pModule = NULL; 
    PyObject * pFunc   = NULL; 

    pModule = PyImport_ImportModule("processing_module");
    if (pModule == NULL) {
        printf("ERROR importing module");
    } 

    pFunc  = PyObject_GetAttrString(pModule,"pre_processing"); 
    if(pFunc != NULL) {
        PyObject_CallObject(pFunc,NULL); 
    }
    else {
        cout << "pFunc returned NULL" <<endl;
    }

}

#需要输入参数和返回参数
int great_function_from_python(int a) 
{

    int res;

    PyObject *pModule,*pFunc;
    PyObject *pArgs,*pValue;
    
    /* import */
    pModule = PyImport_Import(PyString_FromString("processing_module"));

    /* great_module.great_function */
    pFunc = PyObject_GetAttrString(pModule,"p");
 
    /* build args */
    pArgs = PyTuple_New(1);
    PyTuple_SetItem(pArgs,PyInt_FromLong(a));

    /* call */
    pValue = PyObject_CallObject(pFunc,pArgs);
    
    res = PyInt_AsLong(pValue);

    return res;

}


g++:
g++ cpp_python.cpp -I /usr/include/python2.7 -L /usr/lib/python2.7/config-x86_64-linux-gpu -lpython2.7

CMakeLists.txt:

cmake_minimum_required(VERSION 2.8)

set(PROJECT_NAME test02)

project(${PROJECT_NAME})

configure_file(processing_module.py processing_module.py COPYONLY)
configure_file(IMG_3204.png IMG_3204.png COPYONLY)


set(PYTHON_ROOT /usr)
include_directories(${PYTHON_ROOT}/include/python2.7/)
link_directories(${PYTHON_ROOT}/lib/python2.7/config-x86_64-linux-gpu/)

set(SRCS cpp_python.cpp)

add_executable(${PROJECT_NAME} ${SRCS})
target_link_libraries(${PROJECT_NAME} -lpython2.7)

set(CMAKE_CXX_FLAGS_RELEASE "-Wall -std=c++11")
set(CMAKE_CXX_FLAGS_DEBUG "-Wall -g -std=c++11")
set(CMAKE_BUILD_TYPE Debug)


很不错的参考:http://gashero.yeax.com/?p=38

C++与python传参多维数组:http://blog.csdn.net/stu_csdn/article/details/69488385


C++调用boost.python、boost.Numpy:

boost.Numpy的安装:

下载:git clone https://github.com/ndarray/Boost.NumPy.git 
cd Boost.Numpy 
mkdir build 
cd build 
cmake .. 
make
make install

CMakeLists.txt

cmake_minimum_required( VERSION 2.8 )
 
project( BoostPythonHelloWorld )
 
# Find necessary packages
find_package( PythonLibs 2.7 required )
include_directories( ${PYTHON_INCLUDE_DIRS} )
 
find_package( Boost COMPONENTS python required )
include_directories( ${Boost_INCLUDE_DIR} )
 
# Build our library
add_library( greet SHARED greet.cpp )
 
# Define the wrapper library that wraps our library
add_library( greet_ext SHARED greet_ext.cpp )
target_link_libraries( greet_ext ${Boost_LIBRARIES} greet )


C++调用Python时,传递参数为数组可参考:

(1)boost.python:https://feralchicken.wordpress.com/2013/12/07/boost-python-hello-world-example-using-cmake/

(2)boost.Numpy使用:http://blog.csdn.net/shizhuoduao/article/details/67673604

(3)https://ubuntuforums.org/archive/index.PHP/t-1266059.html

(4)http://blog.numerix-dsp.com/2013/08/how-to-pass-c-array-to-python-solution.html

(5)https://docs.scipy.org/doc/numpy/reference/c-api.array.html#c.PyArray_FILLWBYTE

(6)https://svn.ssec.wisc.edu/repos/collocation/tags/airsmod-eweisz/c++/python.cpp

C++调用Python参考:https://www.zhihu.com/question/23003213

Linux下gdb调试C++代码:http://jingyan.baidu.com/article/acf728fd464984f8e410a369.html

猜你在找的Ubuntu相关文章