#include <Python.h>
#include <opencv.hpp>
#include <iostream>
#include <numpy/arrayobject.h>
using namespace std;
using namespace cv;
int main()
{
wchar_t* pythonHome = Py_DecodeLocale("D:/Anaconda3/envs/SL", NULL);
Py_SetPythonHome(pythonHome);
Py_Initialize(); // 初始化
if (!Py_IsInitialized()) {
cout << "initial failed" << endl;
}
if (_import_array() < 0) {
PyErr_Print();
PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import");
/*return NUMPY_IMPORT_ARRAY_RETVAL;*/
return 0;
}
_object* pyModel, *pDict, *pClass,* pArgs, *_pyTranslator;
pyModel = PyImport_ImportModule("image_translator");
if (!pyModel)
{
cout << "py文件初始化失败" << endl;
return 0 ;
}
// 获取公共属性
pDict = PyModule_GetDict(pyModel);
if (!pDict)
{
cout << "py属性获取失败" << endl;
return 0;
}
pClass = PyDict_GetItemString(pDict, "ImageTranslator");
if (!pClass || !PyCallable_Check(pClass))
{
cout << "ImageTranslate类获取失败" << endl;
return 0;
}
pArgs = PyTuple_New(3);
string modelPath = "E:/FeedBack/ZaXiang/20240415/DB.pb";
int netWidth = 256, netHeight = 256;
PyTuple_SetItem(pArgs, 0, Py_BuildValue("s", (const char*)modelPath.c_str()));
PyTuple_SetItem(pArgs, 1, Py_BuildValue("i", netWidth));
PyTuple_SetItem(pArgs, 2, Py_BuildValue("i", netHeight));
_pyTranslator = PyObject_CallObject(pClass, pArgs);
if (!_pyTranslator)
{
cout << "初始化类失败" << endl;
return 0 ;
}
string img_path = "D:/20240416/20240416.jpg";
Mat img = cv::imread(img_path, 0);
int input_channel = 1;
int output_channel = 2;
// 申请空间
int width = img.cols;
int height = img.rows;
int channel = img.channels();
npy_intp Dims[3] = { height, width, channel };
PyObject*PyArray = PyArray_SimpleNewFromData(2, Dims, NPY_UBYTE, img.data);
// 传入参数
PyObject*ArgArray = PyTuple_New(3);
PyObject *pValue1 = PyLong_FromLong(input_channel); // 第一个整数参数
PyObject *pValue2 = PyLong_FromLong(output_channel); // 第二个整数参数
PyTuple_SetItem(ArgArray, 0, PyArray);
PyTuple_SetItem(ArgArray, 1, pValue1);
PyTuple_SetItem(ArgArray, 2, pValue2);
PyObject *pReturn = nullptr;
if ((1 == input_channel) or (3 == input_channel))
{
pReturn = PyObject_CallMethod(_pyTranslator, "translate", "O", ArgArray);
}
PyArrayObject *pArray;
PyArray_OutputConverter(pReturn, &pArray); // 获取数据[c * h * w]
uchar *array_3 = (uchar*)PyArray_DATA(pArray); // 拿数据
cv::Mat channel1 = cv::Mat(height,width , CV_8UC1, array_3);
cv::Mat channel2 = cv::Mat(height,width, CV_8UC1, array_3 + height * width * channel);
cout << channel1.rows << " " << channel1.cols << endl;
Py_DECREF(pReturn);
}
c++运行python脚本方案
于 2024-04-16 19:11:20 首次发布