首页 > 系统相关 >ubuntu下C++如何调用python程序,gdb调试C++代码

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

时间:2023-01-29 15:58:26浏览次数:42  
标签:NAME python max cv2 C++ PROJECT gdb

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

标签:NAME,python,max,cv2,C++,PROJECT,gdb
From: https://www.cnblogs.com/lidabo/p/17072874.html

相关文章

  • python绘制折线图
    importdatetimeimportmatplotlib.pyplotaspltimportpylabasmplimportnumpyasnp#数据源list_date=['20191005','20191014','20191021','20191217','20......
  • C++ 设计模式--模板方法Template Method
    1.定义定义一个操作中的算法的骨架(稳定),而将一些步骤延迟(变化)到子类中。TemplateMethod使得子类可以不改变(复用)一个算法的结构即可重定义(override重写)该算法的某......
  • Python字典对象的创建(9种方式)
    第一种方式:使用{}firstDict={"name":"wangyuanwai","age":25} 说明:{}为创建一个空的字典对象第二种方式:使用fromkeys()方法second_dict=dict.f......
  • 【C++】char使用汇总
    一、char*字符串格式化根据输入的int型参数,与字符串拼接。char*可以替换为char[]intnum=1;chartmpStr[5];sprintf(tmpStr,"Test%d",num);//tmpStr=Test1......
  • 【奇妙的数据结构世界】用图像和代码对堆栈的使用进行透彻学习 | C++
    第十章堆栈:::hljs-center目录第十章堆栈●前言●一、堆栈是什么?1.简要介绍●二、堆栈操作的关键代码段1.类型定义2.顺序栈的常用操作3.链式栈的常用......
  • 常见的6个Python数据可视化库!
    提到数据可视化库,相信大家对这个都不陌生,而且Python中内置了很多数据可视化库,是我们工作的好帮手。本文为大家介绍一下常见的6个Python数据可视化库,希望对你们有帮助。......
  • python 实现app性能测试(cpu、内存占用情况)
    一、获取appcpu占用情况1、实现代码importos,csvimporttimeimportnumpyasnpfrommatplotlibimportpyplotaspltfromcheck_packageimportcheck_package......
  • Python 的垃圾回收机制【译】
    几乎所有的高级编程语言都有自己的垃圾回收机制,开发者不需要关注内存的申请与释放,Python也不例外。Python官方团队的文章https://devguide.python.org/internals/garba......
  • Python工具箱系列(二十三)
    基于游标得操作游标是数据库操作的相对底层的能力。简单的操作如下:importmysql.connectorimportrandomhost='localhost'user='root'password='8848is8848'......
  • Python字符串中用于转义的字符很多
    Python字符串中用于转义的字符很多,这里列举了几个比较常用的几个,更多的转义应用会放在合集的文章里。\n换行符:可以在一行内创建多行输出的字符串;\t制表符:相当于四个空格......