广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python深度学习tensorflow训练好的模型进行图像分类
  • 651
分享到

python深度学习tensorflow训练好的模型进行图像分类

2024-04-02 19:04:59 651人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录正文随机找一张图片读取图片进行分类识别最后输出正文 谷歌在大型图像数据库ImageNet上训练好了一个Inception-v3模型,这个模型我们可以直接用来进来图像分类。 下载链

正文

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

下载链接: https://pan.baidu.com/s/1XGfwYer5pIEDkpM3nM6o2A

提取码: hu66

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

其中

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

imagenet_synset_to_human_label_map.txt是类别文件。

随机找一张图片

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

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

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

读取图片进行分类识别

# -*- coding: utf-8 -*-
import Tensorflow as tf
import numpy as np
import re
import os
model_dir='D:/tf/model/'
image='d:/cat.jpg'
#将类别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, 'imagenet_2012_challenge_label_map_proto.pbtxt')
    if not uid_lookup_path:
      uid_lookup_path = os.path.join(
          model_dir, '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]
#读取训练好的Inception-v3模型来创建graph
def create_graph():
  with tf.gfile.FastGFile(os.path.join(
      model_dir, 'classify_image_graph_def.pb'), 'rb') as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())
    tf.import_graph_def(graph_def, name='')
#读取图片
image_data = tf.gfile.FastGFile(image, 'rb').read()
#创建graph
create_graph()
sess=tf.Session()
#Inception-v3模型的最后一层softmax的输出
softmax_tensor= sess.graph.get_tensor_by_name('softmax:0')
#输入图像数据,得到softmax概率值(一个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()
#取出前5个概率最大的值(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()

最后输出

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)

以上就是python深度学习tensorflow训练好的模型进行图像分类的详细内容,更多关于tensorflow训练模型图像分类的资料请关注编程网其它相关文章!

--结束END--

本文标题: python深度学习tensorflow训练好的模型进行图像分类

本文链接: https://www.lsjlt.com/news/119024.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作