环境
tensorflow-gpu = 1.3.1
keras = 2.0.5
python = 3.6
Qt = 5.14
VS = 2015
预测函数编写
将预测函数编写好,包括加载权重,我这里将加载权重和预测写在一起了。
import os
import sys
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
from PIL import Image
from classification import Classification
classfication = Classification() #这里面有权重加载
def predect(imgpath):
image = Image.open(imgpath)
class_name = classfication.detect_image(image)
if(class_name == 'cat'):
return 1
else:
return 2
Qt调用网络
下面是pro文件需要添加的内容,我用的是ancconda 的环境
INCLUDEPATH +=-I D:\anaconda\envs\tensorflow1.3\include
LIBS += -LD:\anaconda\envs\tensorflow1.3\libs
LIBS += -LD:\anaconda\envs\tensorflow1.3\libs -lpython36
下面是我main.cpp内的内容
#include <QCoreApplication>
#include <Python.h>
#include <string>
#include<QDebug>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Py_Initialize(); // 初始化
if ( !Py_IsInitialized() )
{
return -1;
}
// char* path="D:\\PyCharmProject\\classification-keras-main\\img\\cat.jpg";
PyRun_SimpleString("import sys");
//这个地方就是为了找到你写的那个预测文件放的地方,你预测文件包含的其他所有的文件都要添加到Qt工程里
PyRun_SimpleString("sys.path.append('D:/QTproject/UsePredition/')");
//还可以使用以下路径,这个路径是pycharm工程路径,里面包含了所有需要的文件
// PyRun_SimpleString("sys.path.append('D:/PyCharmProject/classification-keras-main/')");
PyObject *pModule = NULL;
pModule =PyImport_ImportModule("prediction");
qDebug()<<"111111111111";
PyObject *pFunc2= PyObject_GetAttrString(pModule, "predect");
if(!pFunc2)
{
return -2;
}
PyObject *pArgs2 = PyTuple_New(1);
PyTuple_SetItem(pArgs2, 0, Py_BuildValue("s", "D:\\PyCharmProject\\classification-keras- main\\img\\cat.jpg"));
PyObject *pReturn2 = PyEval_CallObject(pFunc2, pArgs2);
qDebug()<<PyLong_AsLong(pReturn2)<<endl;
Py_Finalize();
return a.exec();
}
出现的问题
PyObject *pModule = NULL;
pModule =PyImport_ImportModule("prediction");
pModule 结果一直为NULL,Module import失败
代码加入以下内容
if (!pModule) {
if (pModule == NULL)
{
PyErr_Print();
exit(1);
}
printf("Import Module failed!\n");
}
运行显示没有keras,numpy等库
解决办法
网上查了很多资料,主要参考以下链接
https://blog.csdn.net/LTyyCFY/article/details/103185794
主要原因就是使用的python并不是anaconda的环境,也就找不到这些库,在用户变量里按上诉链接添加好后,在Qt内调用python函数
def printinfo():
print(sys.path)
发现调用的pyhon路径依然不是anaconda创建的环境,而是我安装的python环境,最直接的解决办法就是卸载python,反正也用不着。
最后注意函数返回类型,可能导致运行出错。