下载保存模型
import tensorflow as tf
import os
import tarfile
import requests
inception_pretrain_model_url = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'
inception_pretrain_model_dir = 'inception_model'
if not os.path.exists(inception_pretrain_model_dir):
os.makedirs(inception_pretrain_model_dir)
filename = inception_pretrain_model_url.split('/')[-1]
filepath = os.path.join(inception_pretrain_model_dir, filename)
if not os.path.exists(filepath):
print('download', filename)
r = requests.get(inception_pretrain_model_url, stream=True)
with open(filepath, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
print('finish: ', filename)
# 解压文件
tarfile.open(filepath, 'r:gz').extractall(inception_pretrain_model_dir)
# 模型结构存放文件
log_dir = 'inception_log'
if not os.path.exists(log_dir):
os.makedirs(log_dir)
# classify_image_graph_def.pb 为google已训练好的模型
inception_graph_def_file = os.path.join(inception_pretrain_model_dir, 'classify_image_graph_def.pb')
with tf.Session() as sess:
# 创建一个图来存放已经训练好的模型
with tf.gfile.FastGFile(inception_graph_def_file, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='')
# 保存图的结构
writer = tf.summary.FileWriter(log_dir, sess.graph)
writer.close()
查看网络结构:tensorboard --logdir=./
classify_image_graph_def.pd 为模型
imagenet_2012_challenge_label_map_proto.pbtxt 记录一个个图像实体
imagenet_synset_to_human_label_map.txt 记录类别
两个文件通过编号字符串 target_class_string 字段连接起来
在项目下创建images文件夹,放入图片
载入模型进行测试,代码参考tensorflow官方代码
import tensorflow as tf
import os
import numpy as np
import re
from PIL import Image
import matplotlib.pyplot as plt
class NodeLookup(object):
def __init__(self):
label_lookup_path = 'inception_model/imagenet_2012_challenge_label_map_proto.pbtxt'
uid_lookup_path = 'inception_model/imagenet_synset_to_human_label_map.txt'
self.node_lookup = self.load(label_lookup_path, uid_lookup_path)
def load(self, label_lookup_path, uid_lookup_path):
# 通过tensorflow读文件方法把文件读入,加载分类字符转 'n*******' 对应各分类名称的文件
proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()
uid_to_human={}
# 一行一行读取数据
for line in proto_as_ascii_lines:
# 去掉换行符
line = line.strip('\n')
# 按照 '\t' 分割
parsed_items = line.split('\t')
uid = parsed_items[0]
human_string = parsed_items[1]
# 保存编号字符串与分类名称的关系
uid_to_human[uid] = human_string
# 加载分类字符串n*******对应分类编号1-1000的文件
proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()
node_id_to_uid = {}
for line in proto_as_ascii:
if line.strip().startswith('target_class:'):
target_class = int(line.strip().split(':')[1])
elif line.strip().startswith('target_class_'):
target_class_string = line.strip().split(':')[1].strip()
node_id_to_uid[target_class] = target_class_string[1:-1]
# 建立分类编号 1-1000 与对应分类名称的映射关系
node_id_to_name = {}
for key,val in node_id_to_uid.items():
name = uid_to_human[val]
node_id_to_name[key] = name # 最后得到如 {449: 'tench, Tinca tinca', ...}
return node_id_to_name
# 传入分类编号1-1000 返回分类名称,因为 inception-v3 分类结果返回的是编号不是直接给名称
def id_to_string(self, node_id):
if node_id not in self.node_lookup:
return ''
return self.node_lookup[node_id]
# 创建一个图来存放google训练好的模型
with tf.gfile.FastGFile('inception_model/classify_image_graph_def.pb','rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='')
node_lookup = NodeLookup()
with tf.Session() as sess:
# 拿到softmax的op
# 'softmax:0'这个名字,可以在网络中找到这个节点,它的名字就'(softmax)',
softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')
for root,dirs,files in os.walk('images/'): ###把要测图片放入Images文件夹
for file in files:
image_data = tf.gfile.FastGFile(os.path.join(root,file),'rb').read()
# 运行softmax节点,向其中feed值
# 可以在网络中找到这个名字,DecodeJpeg/contents,
# 据此可以发现,根据名字取网络中op时,如果其名字带括号,就用括号内的名字,如果不带括号,就用右上角介绍的名字。
# 而带个0,是默认情况,如果网络中出现同名节点,这个编号会递增
predictions = sess.run(softmax_tensor,{'DecodeJpeg/contents:0':image_data})
predictions = np.squeeze(predictions)# 把结果转化为1维数据
image_path = os.path.join(root, file)
print(image_path)
img = Image.open(image_path)
plt.imshow(img)
plt.axis('off')
plt.show()
# 排序,拿概率最大的5个值,然后再对这5个值倒序
top_k = predictions.argsort()[-5:][::-1]
for node_id in top_k:
human_string = node_lookup.id_to_string(node_id)
# 获取置信度
score = predictions[node_id]
print('%s (score = %.5f)' % (human_string, score))
运行后结果如下