当前位置:   article > 正文

VS2017 QT/C++ 调用python函数传图像_vs2017 qt python

vs2017 qt python

原文:VS2019 C++ 调用python函数/类对象的方法_ 蜗牛在听雨的博客-CSDN博客_c++调用python函数

1、c++调用python类(传图像参数) ,编译出错,解决方法:

因为需要转换图像格式,从opencv的Mat格式转为python的PIL格式,需要用到numpy的C++接口。但是编译出错,目前看到这篇文章写的最精准,也解决了我的问题。编译错误内容:

无法解析的外部符号 __imp___Py_RefTotal
无法解析的外部符号 __imp___Py_NegativeRefcount,该符号在函数 __import_array 中被引用

2、总结如下:

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行的

  1. /* Py_DEBUG implies Py_TRACE_REFS. */
  2. #if defined(Py_DEBUG) && !defined(Py_TRACE_REFS)
  3. #define Py_TRACE_REFS
  4. #endif

修改为

  1. /* Py_DEBUG implies Py_TRACE_REFS. */
  2. #if defined(Py_DEBUG) && !defined(Py_TRACE_REFS)
  3. //#define Py_TRACE_REFS
  4. #endif

在pyconfig中,修改358行的

  1. /* Py_DEBUG implies Py_TRACE_REFS. */
  2. #if defined(Py_DEBUG) && !defined(Py_TRACE_REFS)
  3. //#define Py_TRACE_REFS
  4. #endif

修改为:

  1. #ifdef _DEBUG
  2. //# define Py_DEBUG
  3. #endif

代码如图所示:

 

3、 传图像的源代码如下:

  1. //读图像,以array形式传递参数
  2. Mat sml_img = imread("1.png",0);
  3. if (!sml_img.isContinuous())
  4. {
  5. sml_img = sml_img.clone();
  6. }
  7. npy_intp dims[] = { sml_img.rows, sml_img.cols};
  8. PyObject *pValue = PyArray_SimpleNewFromData(2, dims, NPY_UINT8, sml_img.data);
  9. //用tuple封装参数传入python
  10. PyObject* args = PyTuple_New(1);
  11. PyTuple_SetItem(args, 0, pValue);
  12. //返回值
  13. PyObject *pReturn = PyObject_CallObject(pFunc, args);
  14. PyArrayObject* ret_array = (PyArrayObject*)PyList_GetItem(pReturn, 0);
  15. PyArrayObject* ret_params = (PyArrayObject*) PyList_GetItem(pReturn, 1);
  16. //返回的numpy矩阵的row和col
  17. int Rows = ret_params->dimensions[0], columns = ret_params->dimensions[1];
  18. std::cout << Rows << " " << columns << std::endl;
  19. //获取py返回值,很多种方式,我只是为了解析返回的两个数组
  20. //#define out_Value(i,j) (*(npy_float64*)((PyArray_DATA(ret_params) + \
  21. //(i) * PyArray_STRIDES(ret_params)[0] + \
  22. // (j) * PyArray_STRIDES(ret_params)[1])))
  23. int a = *((int *)PyArray_GETPTR2(ret_params, 2, 1));
  24. //转换成Mat,图像显示
  25. npy_intp *shape = PyArray_SHAPE(ret_array);
  26. Mat big_img(shape[0], shape[1], CV_8UC1, PyArray_DATA(ret_array));
  27. imshow("t",big_img);
  28. waitKey(0);

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/730687
推荐阅读
相关标签
  

闽ICP备14008679号