赞
踩
原文:VS2019 C++ 调用python函数/类对象的方法_ 蜗牛在听雨的博客-CSDN博客_c++调用python函数
因为需要转换图像格式,从opencv的Mat格式转为python的PIL格式,需要用到numpy的C++接口。但是编译出错,目前看到这篇文章写的最精准,也解决了我的问题。编译错误内容:
无法解析的外部符号 __imp___Py_RefTotal
无法解析的外部符号 __imp___Py_NegativeRefcount,该符号在函数 __import_array 中被引用
1、引入头文件#include"arrayobject.h" (文件在C:\Program Files\Python36\Lib\site-packages\numpy\core\include\numpy目录下)
2、添加import_array()函数。
3、修改两个头文件object.h和pyconfig.h (文件在C:\Program Files\Python36\include目录下)
在object中,修改54行的
- /* Py_DEBUG implies Py_TRACE_REFS. */
- #if defined(Py_DEBUG) && !defined(Py_TRACE_REFS)
- #define Py_TRACE_REFS
- #endif
修改为
- /* Py_DEBUG implies Py_TRACE_REFS. */
- #if defined(Py_DEBUG) && !defined(Py_TRACE_REFS)
- //#define Py_TRACE_REFS
- #endif
在pyconfig中,修改358行的
- /* Py_DEBUG implies Py_TRACE_REFS. */
- #if defined(Py_DEBUG) && !defined(Py_TRACE_REFS)
- //#define Py_TRACE_REFS
- #endif
修改为:
- #ifdef _DEBUG
- //# define Py_DEBUG
- #endif
代码如图所示:
- //读图像,以array形式传递参数
- Mat sml_img = imread("1.png",0);
- if (!sml_img.isContinuous())
- {
- sml_img = sml_img.clone();
- }
- npy_intp dims[] = { sml_img.rows, sml_img.cols};
-
- PyObject *pValue = PyArray_SimpleNewFromData(2, dims, NPY_UINT8, sml_img.data);
-
-
- //用tuple封装参数传入python
- PyObject* args = PyTuple_New(1);
- PyTuple_SetItem(args, 0, pValue);
-
- //返回值
- PyObject *pReturn = PyObject_CallObject(pFunc, args);
- PyArrayObject* ret_array = (PyArrayObject*)PyList_GetItem(pReturn, 0);
- PyArrayObject* ret_params = (PyArrayObject*) PyList_GetItem(pReturn, 1);
-
-
-
- //返回的numpy矩阵的row和col
- int Rows = ret_params->dimensions[0], columns = ret_params->dimensions[1];
- std::cout << Rows << " " << columns << std::endl;
-
-
- //获取py返回值,很多种方式,我只是为了解析返回的两个数组
-
- //#define out_Value(i,j) (*(npy_float64*)((PyArray_DATA(ret_params) + \
- //(i) * PyArray_STRIDES(ret_params)[0] + \
- // (j) * PyArray_STRIDES(ret_params)[1])))
- int a = *((int *)PyArray_GETPTR2(ret_params, 2, 1));
-
-
- //转换成Mat,图像显示
- npy_intp *shape = PyArray_SHAPE(ret_array);
- Mat big_img(shape[0], shape[1], CV_8UC1, PyArray_DATA(ret_array));
- imshow("t",big_img);
- waitKey(0);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。