QT-C++调用Python文件,实现深度学习的交互调用

QT-C++调用Python文件,实现深度学习的交互调用

李伯爵的指间沙 2020-05-12 09:34:54 42 收藏
展开
0.本机环境:WIN10*64

1.下载安装python3.7.4

路径如下:C:\Python3.7.4

2.修改pro文件

INCLUDEPATH += C:\Python3.7.4\include
LIBS += -LC:\Python3.7.4\libs
-lpython37_d
3.python文件修改

4. C++调用

#pragma push_macro(“slots”)
#undef slots
#include
#pragma pop_macro(“slots”)
5.C++启动环境

std::tuple Py_Initialize_Start()
{
bool Py_IsInitialized_flag;
Py_Initialize();
if ( !Py_IsInitialized())
{
Py_IsInitialized_flag = false;
qDebug() <<“Py_IsInitialized failed”;
}
else
{
Py_IsInitialized_flag = true;
qDebug() <<“Py_IsInitialized successed”;
}
PyObject* pFunc;
PyObject* pModule;
bool ispModule;
if(Py_IsInitialized_flag == true)
{
//导入*.py模块
pModule = PyImport_ImportModule(“predict”);
//PyObject* pModule = PyImport_ImportModule(“hello”);
if (!pModule)
{
ispModule = false;
printf(“Cant open python file!\n”);
qDebug() <<“Cant open python file!”;
}
else
{
ispModule = true;
cout<<“Open python successed”< qDebug() <<“Open python successed”;
}
if(ispModule == true)
{
//获取test模块中的hello函数
PyObject* pDict = PyModule_GetDict(pModule);
if (!pDict)
{
printf(“Cant find dictionary.\n”);
qDebug() <<“Cant find dictionary.”;
}
else
{
cout<<“Get dictionary successed”< qDebug() <<“Get dictionary successed”;
}
pFunc = PyDict_GetItemString(pDict, “main_function”);
}
}
qDebug() <<“make_tuple ok”;
return std::make_tuple(pFunc,Py_IsInitialized_flag,ispModule);
}
6.C++停止环境

void Py_Initialize_End(PyObject* pFunc)
{
if(!pFunc || !PyCallable_Check(pFunc))
{
cout<<“Get function hello failed”< }
else
{
cout<<“Get function successed”< }

//结束,释放python
//Py_Finalize();
cout<<"Py_Finalize successed"<

}
7.C++调用Python深度学习的框架,并进行处理

QMap Character_Recognition(string ImagePath,PyObject* pFunc)
{
//===========================================================================
//开始识别
//===========================================================================
PyObject* pReturnValue;
PyObject* pKeyWord;
PyObject* pArgs;
char* result ;
string reStr;
QString result_qstring;
//以元组的形式打包参数
qDebug() < pKeyWord = StringToPyByQt1(ImagePath);
pArgs = PyTuple_New(1);
PyTuple_SetItem(pArgs, 0, pKeyWord);
pReturnValue = PyEval_CallObject(pFunc, pArgs);
qDebug() << “处理返回值”;
//处理返回值
result = new char[256];
PyArg_Parse(pReturnValue, “s”, &result);
reStr= gbk::FromUnicode(result);
result_qstring = QString(QString::fromLocal8Bit(reStr.c_str()));
//========================================================================================
//结束识别
//========================================================================================
QStringList result_List = result_qstring.split(";");
QMap result_map;
for(unsigned int i = 0; i < result_List.size(); i++)
{
if(result_List[i] != NULL)
{
//process code
}
}
return result_map;
}
 
————————————————
版权声明:本文为CSDN博主「李伯爵的指间沙」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/m0_37690102/article/details/106069057

你可能感兴趣的:(C++)