环境:ubuntu16.04+tensorflow+cpu
文件路径:/home/qf/tensorflow/tf/tf6
用别人训练好的模型来进行图像分类
首先下载预训练的模型,放到model中,
model中如图所示
其中tensorflow_inception_graph.pb为预训练模型,tf-master/imagenet/文件夹下的
imagenet_2012_challenge_label_map_proto.pbtxt和 imagenet_synset_to_human_label_map.txt分别为电脑和人看的标签文件
# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
import re
import os
import Image
from matplotlib import pyplot as plt
model_dir='/home/qf/tensorflow/tf/tf6/model/'
image='/home/qf/tensorflow/tf/tf6/cat.jpg'
#transform label txt to txt which human can recongize
##将类别ID转换为人类易读的标签
class NodeLookup(object):
def __init__(self,
label_lookup_path=None,
uid_lookup_path=None):
if not label_lookup_path:
label_lookup_path = os.path.join(
model_dir, 'tf-master/imagenet/imagenet_2012_challenge_label_map_proto.pbtxt')
if not uid_lookup_path:
uid_lookup_path = os.path.join(
model_dir, 'tf-master/imagenet/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):
if not tf.gfile.Exists(uid_lookup_path):
tf.logging.fatal('File does not exist %s', uid_lookup_path)
if not tf.gfile.Exists(label_lookup_path):
tf.logging.fatal('File does not exist %s', label_lookup_path)
# Loads mapping from string UID to human-readable string
proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()
uid_to_human = {}
p = re.compile(r'[n\d]*[ \S,]*')
for line in proto_as_ascii_lines:
parsed_items = p.findall(line)
uid = parsed_items[0]
human_string = parsed_items[2]
uid_to_human[uid] = human_string
# Loads mapping from string UID to integer node ID.
node_id_to_uid = {}
proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()
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]
node_id_to_uid[target_class] = target_class_string[1:-2]
# Loads the final mapping of integer node ID to human-readable string
node_id_to_name = {}
for key, val in node_id_to_uid.items():
if val not in uid_to_human:
tf.logging.fatal('Failed to locate: %s', val)
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]
#read pre-trained Inception-v3 model to construct graph
def create_graph():
##读取训练好的Inception-v3模型来创建graph
with tf.gfile.FastGFile(os.path.join(
model_dir, 'tensorflow_inception_graph.pb'), 'rb') as f: #load model
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='')
#construct graph
create_graph()
'''
#read image
#image_data = tf.gfile.FastGFile(image, 'rb').read()
sess=tf.Session()
# the Inception-v3 model's last layer --softmax
##Inception-v3模型的最后一层softmax的输出
softmax_tensor= sess.graph.get_tensor_by_name('softmax:0')
#input image and get softmax value(shape=(1,1008))
predictions = sess.run(softmax_tensor,{'DecodeJpeg/contents:0': image_data})
#(1,1008)->(1008,)
predictions = np.squeeze(predictions)
# ID --> English string label.
node_lookup = NodeLookup()
#take out the top 5 highest probability values (top-5)
top_5 = predictions.argsort()[-5:][::-1]
for node_id in top_5:
human_string = node_lookup.id_to_string(node_id)
score = predictions[node_id]
print('%s (score = %.5f)' % (human_string, score))
sess.close()
'''
##################################################
#上面为对单幅图测试,若对多幅图测试代码如下
with tf.Session() as sess:
softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')
#遍历目录
for root,dirs,files in os.walk('images/'):
for file in files:
#载入图片
image_data = tf.gfile.FastGFile(os.path.join(root,file), 'rb').read()
predictions = sess.run(softmax_tensor,{'DecodeJpeg/contents:0': image_data})#图片格式是jpg格式
#predictions = sess.run(softmax_tensor,{'DecodeGif/contents:0': image_data})#图片格式是jpg格式
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()
#排序
top_k = predictions.argsort()[-5:][::-1]
node_lookup = NodeLookup()
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))
print()