DoubleLi

qq: 517712484 wx: ldbgliet

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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,0), cv2.FILLED)  
            max_area = area  
            max_cnt = cnt  
        else:  
            c_min = []  
            c_min.append(cnt)  
            cv2.drawContours(img, c_min, -1, (0,0,0), cv2.FILLED)  
  
    c_max.append(max_cnt)  
    cv2.drawContours(img, c_max, -1, (255, 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,0, 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 )  
   
set(PROJECT_NAME test02)
project(${PROJECT_NAME})  
   
# 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} )  

# OpenCV
find_package(OpenCV REQURIED)
include_directories(${OpenCV_INCLUDE_DIRS})
   
set(SRCS main.cpp)
add_executable(${PROJECT_NAME} ${SRCS})


target_link_libraries(${PROJECT_NAME} ${Boost_LIBRARIES})
target_link_libraries(${PROJECT_NAME} ${PYTHON_LIBRARIES})
target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBRARIES})

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

posted on 2023-01-29 15:43  DoubleLi  阅读(172)  评论(0编辑  收藏  举报