c++运行python脚本方案

#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);


}

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值