谷歌在大型图像数据库ImageNet上训练好了一个Inception-v3模型,这个模型我们可以直接用来进来图像分类。

下载地址:https://storage.googleapis.com/download.tensorflow.org/models/inception_dec_2015.zip

下载完解压后,得到几个文件:

其中的classify_image_graph_def.pb 文件就是训练好的Inception-v3模型。

imagenet_synset_to_human_label_map.txt是类别文件。

随机找一张图片:如

对这张图片进行识别,看它属于什么类?

代码如下:先创建一个类NodeLookup来将softmax概率值映射到标签上。

然后创建一个函数create_graph()来读取模型。

最后读取图片进行分类识别:

  1. # -*- coding: utf-8 -*-
  2.  
  3. import tensorflow as tf
  4. import numpy as np
  5. import re
  6. import os
  7.  
  8. model_dir='D:/tf/model/'
  9. image='d:/cat.jpg'
  10.  
  11. #将类别ID转换为人类易读的标签
  12. class NodeLookup(object):
  13. def __init__(self,
  14. label_lookup_path=None,
  15. uid_lookup_path=None):
  16. if not label_lookup_path:
  17. label_lookup_path = os.path.join(
  18. model_dir, 'imagenet_2012_challenge_label_map_proto.pbtxt')
  19. if not uid_lookup_path:
  20. uid_lookup_path = os.path.join(
  21. model_dir, 'imagenet_synset_to_human_label_map.txt')
  22. self.node_lookup = self.load(label_lookup_path, uid_lookup_path)
  23.  
  24. def load(self, label_lookup_path, uid_lookup_path):
  25. if not tf.gfile.Exists(uid_lookup_path):
  26. tf.logging.fatal('File does not exist %s', uid_lookup_path)
  27. if not tf.gfile.Exists(label_lookup_path):
  28. tf.logging.fatal('File does not exist %s', label_lookup_path)
  29.  
  30. # Loads mapping from string UID to human-readable string
  31. proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()
  32. uid_to_human = {}
  33. p = re.compile(r'[n\d]*[ \S,]*')
  34. for line in proto_as_ascii_lines:
  35. parsed_items = p.findall(line)
  36. uid = parsed_items[0]
  37. human_string = parsed_items[2]
  38. uid_to_human[uid] = human_string
  39.  
  40. # Loads mapping from string UID to integer node ID.
  41. node_id_to_uid = {}
  42. proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()
  43. for line in proto_as_ascii:
  44. if line.startswith(' target_class:'):
  45. target_class = int(line.split(': ')[1])
  46. if line.startswith(' target_class_string:'):
  47. target_class_string = line.split(': ')[1]
  48. node_id_to_uid[target_class] = target_class_string[1:-2]
  49.  
  50. # Loads the final mapping of integer node ID to human-readable string
  51. node_id_to_name = {}
  52. for key, val in node_id_to_uid.items():
  53. if val not in uid_to_human:
  54. tf.logging.fatal('Failed to locate: %s', val)
  55. name = uid_to_human[val]
  56. node_id_to_name[key] = name
  57.  
  58. return node_id_to_name
  59.  
  60. def id_to_string(self, node_id):
  61. if node_id not in self.node_lookup:
  62. return ''
  63. return self.node_lookup[node_id]
  64.  
  65. #读取训练好的Inception-v3模型来创建graph
  66. def create_graph():
  67. with tf.gfile.FastGFile(os.path.join(
  68. model_dir, 'classify_image_graph_def.pb'), 'rb') as f:
  69. graph_def = tf.GraphDef()
  70. graph_def.ParseFromString(f.read())
  71. tf.import_graph_def(graph_def, name='')
  72.  
  73. #读取图片
  74. image_data = tf.gfile.FastGFile(image, 'rb').read()
  75.  
  76. #创建graph
  77. create_graph()
  78.  
  79. sess=tf.Session()
  80. #Inception-v3模型的最后一层softmax的输出
  81. softmax_tensor= sess.graph.get_tensor_by_name('softmax:0')
  82. #输入图像数据,得到softmax概率值(一个shape=(1,1008)的向量)
  83. predictions = sess.run(softmax_tensor,{'DecodeJpeg/contents:0': image_data})
  84. #(1,1008)->(1008,)
  85. predictions = np.squeeze(predictions)
  86.  
  87. # ID --> English string label.
  88. node_lookup = NodeLookup()
  89. #取出前5个概率最大的值(top-5)
  90. top_5 = predictions.argsort()[-5:][::-1]
  91. for node_id in top_5:
  92. human_string = node_lookup.id_to_string(node_id)
  93. score = predictions[node_id]
  94. print('%s (score = %.5f)' % (human_string, score))
  95.  
  96. sess.close()

最后输出:

tiger cat (score = 0.40316)
Egyptian cat (score = 0.21686)
tabby, tabby cat (score = 0.21348)
lynx, catamount (score = 0.01403)
Persian cat (score = 0.00394)

tensorflow 1.0 学习:用别人训练好的模型来进行图像分类的更多相关文章

  1. 三分钟快速上手TensorFlow 2.0 (中)——常用模块和模型的部署

    本文学习笔记参照来源:https://tf.wiki/zh/basic/basic.html 前文:三分钟快速上手TensorFlow 2.0 (上)——前置基础.模型建立与可视化 tf.train. ...

  2. 三分钟快速上手TensorFlow 2.0 (上)——前置基础、模型建立与可视化

    本文学习笔记参照来源:https://tf.wiki/zh/basic/basic.html 学习笔记类似提纲,具体细节参照上文链接 一些前置的基础 随机数 tf.random uniform(sha ...

  3. tensorflow 1.0 学习:模型的保存与恢复(Saver)

    将训练好的模型参数保存起来,以便以后进行验证或测试,这是我们经常要做的事情.tf里面提供模型保存的是tf.train.Saver()模块. 模型保存,先要创建一个Saver对象:如 saver=tf. ...

  4. tensorflow 1.0 学习:用CNN进行图像分类

    tensorflow升级到1.0之后,增加了一些高级模块: 如tf.layers, tf.metrics, 和tf.losses,使得代码稍微有些简化. 任务:花卉分类 版本:tensorflow 1 ...

  5. tensorflow 1.0 学习:模型的保存与恢复

    将训练好的模型参数保存起来,以便以后进行验证或测试,这是我们经常要做的事情.tf里面提供模型保存的是tf.train.Saver()模块. 模型保存,先要创建一个Saver对象:如 saver=tf. ...

  6. TensorFlow 同时调用多个预训练好的模型

    在某些任务中,我们需要针对不同的情况训练多个不同的神经网络模型,这时候,在测试阶段,我们就需要调用多个预训练好的模型分别来进行预测. 调用单个预训练好的模型请点击此处 弄明白了如何调用单个模型,其实调 ...

  7. tensorflow 2.0 学习(四)

    这次的mnist学习加入了测试集,看看学习的准确率,代码如下 # encoding: utf-8 import tensorflow as tf import matplotlib.pyplot as ...

  8. Tensorflow 2.0 学习资源

    我从换了新工作才开始学习使用Tensorflow,感觉实在太难用了,sess和graph对 新手很不友好,各种API混乱不堪,这些在tf2.0都有了重大改变,2.0大量使用keras的 api,初步使 ...

  9. tensorflow 1.0 学习:十图详解tensorflow数据读取机制

    本文转自:https://zhuanlan.zhihu.com/p/27238630 在学习tensorflow的过程中,有很多小伙伴反映读取数据这一块很难理解.确实这一块官方的教程比较简略,网上也找 ...

随机推荐

  1. oracle中nvarchar2查询结果显示总是少一位

    问题: 有个表的字段是nvarchar2(32),但是在plsql中查询显示结果发现一直少一位. 修改方法: 在plsql里的首选项-连接里有个选项: 在oci8上强制使用oci7, 把这个勾上就ok ...

  2. Linux中伪分布的搭建

    一伪分布模式             特点:在单机上,模拟一个分布式的环境,具备Hadoop的所有功能                     HDFS:NameNode + DataNode + S ...

  3. Java排序 - 不实用的几个排序算法 -- 睡眠排序、猴子排序、面条排序、珠排序

    介绍几个不实用的排序算法,一来可以在学习时增加一些乐趣,放松一下自己,二来可以学习一下.思考一下这些算法失败在哪里,又是否存在一些好的地方? 睡眠排序 这是一个思想比较简单,脑洞巨大的算法 -- 我们 ...

  4. 2018-2019-2 20165235《网络对抗技术》Exp2 后门原理与实践

    2018-2019-2 20165235<网络对抗技术>Exp2 后门原理与实践 实验内容 1.使用netcat获取主机操作Shell,cron启动 2.使用socat获取主机操作Shel ...

  5. WPF RadioButton的绑定

    1. 枚举类 public enum EnumDataTypes { Simulation, Test } 2. 枚举型与布尔型的转换 public class EnumToBooleanConver ...

  6. [转]webpack中require和import的区别

    webpack中可以写commonjs格式的require同步语法,可以写AMD格式的require回调语法,还有一个require.ensure,以及webpack自己定义的require.incl ...

  7. markdown 书写文档的框架

    请使用 [MkDocs](http://www.mkdocs.org/)

  8. TypeScript专题-Static和使用技巧

    class People { static _name: string; print() { //alert(this.name);// 编译不通过,doex not exist on type Pe ...

  9. Go语言基础(二)

    Go语言基础(二) 跟着上篇,继续看Go基础 一.变量作用域 与C类似,有全局变量.局部变量.形参之分 package main import "fmt" // 全局变量 var ...

  10. centos7安装kubeadm

    安装配置docker v1.9.0版本推荐使用docker v1.12, v1.11, v1.13, 17.03也可以使用,再高版本的docker可能无法正常使用. 测试发现17.09无法正常使用,不 ...