开发环境:VS2015,python3.6 ,tensorflow-gpu=1.6
随便写了一个简单的测试代码,在此之前工程要加上包含路径和库目录,我的python路径为 F:/Anaconda/envs/python36:
#include
#include
#include
using namespace std;
void testImage(char * path)
{
try {
Py_SetPythonHome(L"F:/Anaconda/envs/python36");
Py_Initialize();
PyEval_InitThreads();
PyObject*pFunc_init = NULL;
PyObject*pArg = NULL;
PyObject*pArg_str = NULL;
PyObject*pArg_init = NULL;
PyObject* module = NULL;
module = PyImport_ImportModule("test1");//test1:Python文件名
if (!module) {
printf("cannot open module!");
Py_Finalize();
return;
}
pFunc_init = PyObject_GetAttrString(module, "init");//init:Python文件中的函数名
if (!pFunc_init) {
printf("cannot open FUNC_init!");
Py_Finalize();
return;
}
//开始调用model
pArg = Py_BuildValue("(s)", path);
pArg_str = PyTuple_New(1);
PyTuple_SetItem(pArg_str, 0, pArg);
if (module != NULL) {
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
PyEval_CallObject(pFunc_init, pArg);
}
}
catch (exception& e)
{
cout << "Standard exception: " << e.what() << endl;
}
}
int main()
{
char * path = "2.jpg";
testImage(path);
system("pause");
return 0;
}
其中要注意path最好不要包含中文,如果包含中文路径,记得加上:#pragma execution_character_set(“utf-8”)。
之前做的一个磁瓦正反面检测模型,就随便改了一下,反正用来测试,能用就行了。
import tensorflow as tf
import numpy as np
import os
import csv
import time
if 1:
CHECKPOINT_DIR = './all_model'
INCEPTION_MODEL_FILE = './inception_dec_2015/tensorflow_inception_graph.pb'
# inception-v3模型参数
BOTTLENECK_TENSOR_NAME = 'pool_3/_reshape:0' # inception-v3模型中代表瓶颈层结果的张量名称
JPEG_DATA_TENSOR_NAME = 'DecodeJpeg/contents:0' # 图像输入张量对应的名称
other_dict = {0: '不正常', 1: '正常'}
checkpoint_file = tf.train.latest_checkpoint(CHECKPOINT_DIR)
def init(path):
with tf.Graph().as_default() as graph:
with tf.Session().as_default() as sess:
# 读取训练好的inception-v3模型
with tf.gfile.FastGFile(INCEPTION_MODEL_FILE, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
print ("1")
# 加载inception-v3模型,并返回数据输入张量和瓶颈层输出张量
bottleneck_tensor, jpeg_data_tensor = tf.import_graph_def(
graph_def,
return_elements=[BOTTLENECK_TENSOR_NAME, JPEG_DATA_TENSOR_NAME])
saver = tf.train.import_meta_graph('{}.meta'.format(checkpoint_file))
saver.restore(sess, checkpoint_file)
image_data = tf.gfile.FastGFile(path, 'rb').read()
if len(image_data) > 100:
# 使用inception-v3处理图片获取特征向量
bottleneck_values = sess.run(bottleneck_tensor,
{jpeg_data_tensor: image_data})
# 将四维数组压缩成一维数组,由于全连接层输入时有batch的维度,所以用列表作为输入
bottleneck_values = [np.squeeze(bottleneck_values)]
# 加载元图和变量
# 通过名字从图中获取输入占位符
input_x = graph.get_operation_by_name(
'BottleneckInputPlaceholder').outputs[0]
# 我们想要评估的tensors
predictions = graph.get_operation_by_name('evaluation/ArgMax').outputs[0]
# 收集预测值
all_predictions = []
all_predictions = sess.run(predictions, {input_x: bottleneck_values})
print(other_dict[all_predictions[0]])