搭建环境:
windows7 x64位系统
python3.5
tf_nightly-1.6.0.dev20180117-cp35-cp35m-win_amd64.whl
搭建步骤:
一.安装python
傻瓜式安装。在windows下安装python3.5,双击安装。注意安装时勾选自动配置环境变量,如果计算机中有其它python版本,建议卸载掉再安装。自行到python官网下载,注意python版本需要匹配64位。
二.安装Tensorflow模块到python中
在命令行中,运行#pip install wheel来安装wheel模块。安装成功后运行#pip install tf_nightly-1.6.0.dev20180117-cp35-cp35m-win_amd64.whl来安装Tensorflow模块,此过程需要保证网络畅通,需要另外自动下载一些Tensorflow依赖模块。
此whl files只支持windows-cpu only,读者若需要其它版本可以自行到github下载。
注意:笔者安装为Tensorflow-1.6.0,经测试Tensorflow-1.4.0中Qt调用嵌入Tensorflow模块的python脚本会失败,具体原因不明。
三.Qt调用嵌入Tensorflow的python
假定测试工程名为test,则工程属性如下:
QT -= gui
QT += core
CONFIG += c++11 console
CONFIG -= app_bundle
# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += main.cpp
INCLUDEPATH += -I D:\python35\include
LIBS += -LD:\python35\libs -lpython35
最后两行是配置链接python库路径和引用文件路径,读者根据自己python路径配置。
main.cpp如下:
#include <QCoreApplication>
#include <Python.h>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//初始化python模块
Py_Initialize();
if ( !Py_IsInitialized() )
{
return -1;
}
//导入test.py模块
PyObject* pModule = PyImport_ImportModule("test1");
if (!pModule) {
printf("Cant open python file!\n");
return -1;
}
//获取test模块中的hello函数
//PyObject* pFunhello= PyObject_GetAttrString(pModule,"hello");
PyObject* pDict = PyModule_GetDict(pModule);
if (!pDict) {
printf("Cant find dictionary.\n");
return -1;
}
PyObject* pFunhello = PyDict_GetItemString(pDict, "hello");
if(!pFunhello || !PyCallable_Check(pFunhello)){
cout<<"Get function hello failed"<<endl;
return -1;
}
PyObject * pArgs = NULL;
pArgs = PyTuple_New(1);
PyTuple_SetItem(pArgs, 0, Py_BuildValue("s", "Hello, TensorFlow!"));
//调用hello函数
PyObject_CallFunction(pFunhello, "s", "Hello, TensorFlow!");
//结束,释放python
Py_Finalize();
return a.exec();
}
不要将测试脚本命名为test.py,python安装源码中有同名文件,会引起冲突,这个坑找了好久。我们命名为test1.py,
内容如下:
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
def hello(a):
print("hello begin =====")
hello = tf.constant(a)
sess = tf.Session()
print(sess.run(hello))
print("hello end =====")
由于笔者没有python35debug库,所以该工程在release模式下运行。
在调试的过程中,遇到Qt关键字slots与python库文件object.h第445行冲突,笔者使用的是Qt5.6.0 MSVC2013 64bit。这里是将object.h中slots修改为slots1,如果用到这个模块可能会出问题,请笔者知悉。
运行结果图如下: