import os
import tensorflow as tf
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import numpy as np
import re
from PIL import Image
import matplotlib.pyplot as plt
filePath = r'E:\src\inception_model'
class NodeLookup(object):
def __init__(self):
'''
entry #imagenet_2012_challenge_label_map_proto.pbtxt
{
target_class: 391
target_class_string: "n01558993"
}
'''
label_lookup_path = filePath + '\\' + 'imagenet_2012_challenge_label_map_proto.pbtxt'
# n01482071 elasmobranch, selachian
uid_lookup_path = filePath + '\\' + '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):
#加载分类字符串
# n01482071 elasmobranch, selachian
proto_as_ascii_line = tf.gfile.GFile(uid_lookup_path).readlines() #读文件,啥方法都可以
uid_to_human = {}
for line in proto_as_ascii_line:
#去掉换行符
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
#加载分类字符串 , 对应分类编号1-1000的文件
# entry #imagenet_2012_challenge_label_map_proto.pbtxt
# {
# target_class: 391
# target_class_string: "n01558993"
# }
proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()
target_class = 0
target_class_string = 0
node_id_to_uid = {}
for line in proto_as_ascii:
if line.startswith(' target_class:'):
#获取分类编号
target_class = int(line.split(': ')[1])
if line.startswith(' target_class_string:'):
#获取编号字符串
target_class_string = line.split(': ')[1]
#保存分类编号,第一行是target_class, 第二行是target_class_string,
node_id_to_uid[target_class] = target_class_string[1:-2] # 不要引号,只要中间部分
#建立分类编号
node_id_to_name = {}
for key, val in node_id_to_uid.items():
# 获取分类名称
name = uid_to_human[val]
# 建立分类编号
node_id_to_name[key] = name
return node_id_to_name
# 传入分类器编号返回分类名称
def id_to_string(self, node_id):
if node_id not in self.node_lookup:
return ''
return self.node_lookup[node_id]
#创建一个图用来存储训练好的模型
with tf.gfile.FastGFile(filePath+'\\'+'classify_image_graph_def.pb', 'rb') as f:
grapg_def = tf.GraphDef() #声明一个默认的
grapg_def.ParseFromString(f.read())
tf.import_graph_def(grapg_def, name='')
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)#0.9表示可以使用GPU 90%的资源进行训练,可以任意修改
#sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess: #这里用的图就是 上面设置好的
softmax_tensor = sess.graph.get_tensor_by_name(("softmax:0")) #获取图中softmax函数
# 可以从http://zmjames:6006 的图的结构中看到。 所以这些东西在保存和恢复,运用的时候很关键
for root,dirs,files,in os.walk(r'images/'):
for file in files:
# Tensorflow载入图片
image_data = tf.gfile.FastGFile(os.path.join(root,file),'rb').read()
# 执行函数,传入jpg格式图片计算并得到结果
predictions = sess.run(softmax_tensor,{'DecodeJpeg/contents:0':image_data}) #这个结果是二维的
# 把得到的结果转成一维
predictions = np.squeeze(predictions)
# 打印图片路径及名称
image_path = os.path.join(root,file)
print(image_path)
# 显示图片
img = Image.open(image_path)
plt.imshow(img)
plt.axis('off')
plt.show()
# 排序
top_k = predictions.argsort()[-5:][::-1] #有1000个结果,从小到大的排序,
# [-5:] 表示从后向前取5个,也就是最后5个,[::-1] 在进行一次排序,从大到小排序
node_lookup = NodeLookup()
for node_id in top_k: #
# 获取分类名称
human_string = node_lookup.id_to_string(node_id)
# 获取分类的置信度,相当于就是分类的百分比,80%是狗,10%是猫
score = predictions[node_id]
print("%s (score = %.5f)" % (human_string, score))
print()
14.使用inception-v3进行图像识别
最新推荐文章于 2020-07-08 22:11:55 发布