TensorFlow学习笔记(七) 使用训练好的inception_v3模型预测分类图片
2018-04-01 10:06
861 查看
下载需要练习的inception模型并看起流程
import tensorflow as tf import os import tarfile import requests #inception_v3模型下载 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("finishn: ", 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: #创建一个图来存放google训练好的模型,load graph 具体实现方法看下面的链接 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()点击打开链接
其结构图孺如下
使用inception模型检测图片
里面主要写了labels排序等 的实现,以及利用训练好的模型识别图片的实现。import tensorflow as tfimport 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):
#加载分类字符串n ------ 对应分类名称的文件
proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_pa
4000
th).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_lines = tf.gfile.GFile(label_lookup_path).readlines()
node_id_to_uid = {}
for line in proto_as_ascii_lines :
if line.startswith(' target_class:'):
#获取分类编号1-1000
target_class = int(line.split(': ')[1])
if line.startswith(' target_class_string:'):
#获取编号字符串n****
target_class_string = line.split(': ')[1]
#保存分类编号1-1000与编号字符串n****的映射关系
node_id_to_uid[target_class] = target_class_string[1:-2]
#建立分类编号1-1000对应分类名称的映射关系
node_id_to_name = {}
for key, val in node_id_to_uid.items():
#获取分类名称
name = uid_to_human[val]
#建立分类编号1-1000到分类名称的映射关系
node_id_to_name[key] = name
return node_id_to_name
#传入分类编号1-1000返回分类名称
def id_to_string(self, node_id):
if node_id not in self.node_lookup:
return ''
return self.node_lookup[node_id]
#创建一个图来存放google训练好的模型 #2 load graph
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='')
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 = 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()
相关文章推荐
- TensorFlow学习笔记(八) 如何训练自己的图片模型-基于inception模型(未完成)使用迁移学习和从头学习
- Tensorflow读取并使用预训练模型:以inception_v3为例
- caffe+python 使用训练好的VGG16模型 对 单张图片进行分类,输出置信度
- Tensorflow 的安装和用InceptionV3训练新的图像分类模型
- caffe 09 win10 使用训练好模型为给定图片分类
- TensorFlow迁移学习-使用谷歌训练好的Inception-v3网络进行分类
- 爬取百度图片各种狗狗的图片,使用caffe训练模型分类
- 使用lenet模型训练及预测自己的图片数据
- 使用tf-slim的inception_resnet_v2预训练模型进行图像分类
- caffe+python 使用训练好的VGG16模型 对 单张图片进行分类,输出置信度
- caffe的python接口学习:用训练好的模型(caffemodel或者h5)来分类新的图片
- DL学习笔记【15】使用训练好的模型得到分类结果
- 使用caffe中的imagenet对自己的图片进行分类训练(超级详细版)
- caffe的python接口学习(6):用训练好的模型(caffemodel)来分类新的图片
- 使用caffe训练一个多标签分类/回归模型
- Caffe初试(三)使用caffe的cifar10网络模型训练自己的图片数据
- 使用Caffe对图片进行训练并分类的简单流程
- Caffe 之 使用非图片的鸢尾花(IRIS)数据集(hdf5格式) 训练网络模型
- 深度学习Caffe平台实例——CIFAR-10数据集在caffe平台上模型训练及实例使用模型进行预测
- 【深度学习】笔记6:使用caffe中的CIFAR10网络模型和自己的图片数据训练自己的模型(步骤详解)