背景
现在用c++重构了python工程,有一部分后处理不想再花时间重构了,所以直接拿过来调用。边搜资料边做的,做这个demo花了些时间,所以记下来以防忘记。
资料
找了很多的c++调用python的方法,首先可以肯定的有不止一种方式,直接使用python库、numpy arrayobject库来做;另外一种是使用boost/python boost/numpy的方式。后一种没有调通,是链接库的问题,也记录下来放在后面了。
1)常规的方式
- 调包的基本结构 C/C++调用Python(OpenCV与Numpy)作者收集了很多的信息,帮助蛮大的。
- 编译,收集自stackoverflow: how to build this project
g++ -o cc cc.cpp `pkg-config --cflags --libs opencv` -I/usr/include/python3.5 -lpython3.5m
值得说明一下的是,python3.5m是在路径/usr/lib/x86_64-linux-gnu/libpython3.5m.so
下,可以自行搜素。另外,代码中有个warning,使用宏定义就可以去掉了,在代码中也有说明 - 代码块
- c++: cc.cpp。 1
- c++代码中有个需要说明的地方【1】,需要指定python搜索的路径,防止import ***(PyImport_Import) 时出错;设定搜索路径的时候也可以这样PyRun_SimpleString ("import sys; sys.path.insert(0, '/home/ely/Desktop/Python/C-Python/')");
- python:simple_module.py. 2
- c++处理有多个numpy类型的返回值的python代码
- 参考文献:PyArg_ParseTuple官方文档,里面提到了此函数的标准用法。不过有更方便的函数,此链接的网页向上一点的PyArg_UnpackTuple函数,完全等同与PyArg_ParseTuple函数,用起来更聪明一点.
- 处理有多个numpy类型的返回值代码
- 补充
- import_array()有奇怪的返回值,这篇博客也提到了解决方法 import_array()报错,返回值类型与函数类型不匹配。但是要删东西,还有不报错误的风险。这儿我忘记了在哪看到的代码了,也没能在历史记录里找到,先把代码贴过来。其实就是将这个函数加一个壳。然后用init替换import_array。
size_t init() {
import_array();
}
-
一个小插曲,c++主函数需要使用多线程,python放在子线程中执行。在子线程中异步调用时会有segment fault,而相同代码顺序执行的没有问题。我一度怀疑是多线程的锅,所以尝试了小半天的c++多线程调用python,顺便把筛选的资料附录在下面;也尝试了子线程加锁mutex。哦,忘记说了,多线程调用python时,也是给python解释器加锁。那下面就是C++多线程调用python的链接,按优先顺序排放。
c++多线程调用python
C++调用PythonAPI线程状态和全局解释器锁
C++ 多线程调用Python脚本 -
c++调用python类
通过c++去调用python类的资料我收集了一部分。比如1).c++访问python3-实例化类的方法、2).c++ 调用 python 实例 涉及 类 多参数 列表作为参数、3).c++调用python的代码、函数、类。这些在传递numpy的时候没有找到合适的示例,这儿没有说明文档始终调不通。所以最后还是通过按照上面调用python函数的方法,创建一个全局类对象来调用完成。 -
segmentation 错误 以及程序假死
python异常时,c++调用python的报错信息不及时且信息少。所以,出现假死或段错误等奇怪的现象时,优先排查python代码
2) boost库的方式
- 调包的基本结构 C++调用python并传递数组
- debug出现的错误,主要是boost/numpy问题,安装之后还是出现找不到库的情况,stackoverflow上有个对话,是统一的问题,需要修改环境变量后解决了,先在这儿记下来吧
- boost库的安装
cc.cpp
// c++: cc.cpp
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION //需要放在numpy/arrayobject.h之前
#include<opencv/cv.hpp>
#include <Python.h>
#include <iostream>
#include <numpy/arrayobject.h>
using namespace cv;
using namespace std;
int main(int argc, char *argv[]) {
wchar_t *program = Py_DecodeLocale(argv[0], NULL);
cout << argv[0] << endl;
if (program == NULL) {
fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
exit(1);
}
Py_SetProgramName(program); /* 不见得是必须的 */
/* 非常重要,折腾的时间主要是因为这儿引起的【1】 */
Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(\"/home/user/project/run_retina/build\")");
import_array();
/* 非常重要 */
/* 读图 */
Mat sml_img = imread("lena.jpg");
/* 导入模块和函数,貌似两种方式都可以,不需要加.py,后面回再提到 */
// PyObject *pName = PyUnicode_DecodeFSDefault("simple_module");
PyObject *pName = PyUnicode_FromString("simple_module");
/*这些检查也非常有帮助*/
if (pName == NULL) {
PyErr_Print();
throw std::invalid_argument("Error: PyUnicode_FromString");
}
PyObject *pModule = PyImport_Import(pName);
if (pModule == NULL) {
PyErr_Print();
throw std::invalid_argument("fails to import the module");
}
PyObject *pFunc = PyObject_GetAttrString(pModule, "super_resolution");
if (pFunc == NULL) {
PyErr_Print();
throw std::invalid_argument("fails to PyObject_GetAttrString");
}
/* 准备输入参数 */
PyObject *pArgs = PyTuple_New(2);
if (!sml_img.isContinuous()) { sml_img = sml_img.clone(); }
npy_intp dims[] = {sml_img.rows, sml_img.cols, 3};
PyObject *pValue = PyArray_SimpleNewFromData(3, dims, NPY_UINT8, sml_img.data);
PyTuple_SetItem(pArgs, 0, pValue); /* pValue的引用计数被偷偷减一,无需手动再减 */
PyTuple_SetItem(pArgs, 1, Py_BuildValue("i", 2)); /* 图像放大2倍 */
/* 调用函数 */
PyObject *pRetValue = PyObject_CallObject(pFunc, pArgs);
/* 解析返回结果 */
PyArrayObject *ret_array;
PyArray_OutputConverter(pRetValue, &ret_array);
npy_intp *shape = PyArray_SHAPE(ret_array);
Mat big_img(shape[0], shape[1], CV_8UC3, PyArray_DATA(ret_array));
imwrite("aa.jpg", big_img);
/* 释放所有 */
//Py_DECREF(...);
return 0;
}
simple_module.py
# simple_module.py
import cv2 as cv
def simple_func(a,b):return a+b
def super_resolution(img, scale=4):
height, width = img.shape[:2]
dsize = (width*scale, height*scale)
big_img = cv.resize(img, dsize)
print(img.shape, big_img.shape)
cv.imwrite('aaa.jpg',big_img)
return big_img
多个numpy返回值
/* 解析返回结果 */
PyArrayObject *r1, *r2, *r3, *r4, *r5, *r6;
PyArg_UnpackTuple(pRetValue, "ref", 6, 6, &r1, &r2, &r3, &r4, &r5, &r6);
npy_intp *shape1 = PyArray_SHAPE(r1);
npy_intp *shape2 = PyArray_SHAPE(r2);
npy_intp *shape3 = PyArray_SHAPE(r3);
npy_intp *shape4 = PyArray_SHAPE(r4);
npy_intp *shape5 = PyArray_SHAPE(r5);
npy_intp *shape6 = PyArray_SHAPE(r6);
std::cout << "shape[1]:" << shape1[0] <<
" shape2:" << shape2[0] << "," << shape2[1] <<
" shape3:" << shape3[0] <<
" shape4:" << shape4[0] << "," << shape4[1] <<
" shape5:" << shape5[0] <<
" shape6:" << shape6[0] << "," << shape6[1] <<
std::endl;
# 返回值的打印结果
#-#-#-#-#-#-#-#-#-#-
list_id float32 (11,)
list_track float32 float32 (20, 2) (11,)
list_box float32 (11, 4)
entran;pass_by;ratio float32 (3,)
entrance_line;rec float32 (4, 2)
#-#-#-#-#-#-#-#-#-#-
shape[1]:11 shape2:20,2 shape3:11 shape4:11,4 shape5:3 shape6:4,2
代码c++ : cc.cpp ↩︎
代码python :simple_module.py ↩︎
更多推荐
c++调用python numpy编程
发布评论