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 <Python.h>
#pragma pop_macro("slots")
5.C++启动环境
std::tuple<PyObject*,bool,bool> 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"<<endl;
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"<<endl;
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"<<endl;
}
else
{
cout<<"Get function successed"<<endl;
}
//结束,释放python
//Py_Finalize();
cout<<"Py_Finalize successed"<<endl;
}
7.C++调用Python深度学习的框架,并进行处理
QMap<QString, QString> Character_Recognition(string ImagePath,PyObject* pFunc)
{
//===========================================================================
//开始识别
//===========================================================================
PyObject* pReturnValue;
PyObject* pKeyWord;
PyObject* pArgs;
char* result ;
string reStr;
QString result_qstring;
//以元组的形式打包参数
qDebug() <<QString::fromStdString(ImagePath);
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<QString, QString> result_map;
for(unsigned int i = 0; i < result_List.size(); i++)
{
if(result_List[i] != NULL)
{
//process code
}
}
return result_map;
}