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

作者:denny402 时间:2023-02-20 20:40:37 

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

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

提取码: hu66

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

其中

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

imagenet_synset_to_human_label_map.txt是类别文件。

随机找一张图片

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

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

代码如下:先创建一个类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)

来源:https://www.cnblogs.com/denny402/p/6942580.html

标签:python,深度学习,tensorflow,训练模型,图像分类
0
投稿

猜你喜欢

  • 优雅地使用loading(推荐)

    2024-04-30 08:42:01
  • 小记一次mysql主从配置解决方案

    2024-01-12 18:28:42
  • sqlserver存储过程中SELECT 与 SET 对变量赋值的区别

    2024-01-14 09:50:26
  • 如何使用分区处理MySQL的亿级数据优化

    2024-01-21 04:49:01
  • 分享5个JS 高阶函数

    2024-04-18 09:29:29
  • golang 64位linux环境下编译出32位程序操作

    2024-05-02 16:26:09
  • Python subprocess模块功能与常见用法实例详解

    2021-08-30 02:46:43
  • SQL中varchar和nvarchar的基本介绍及其区别

    2024-01-16 22:16:53
  • Python实现统计文章阅读量的方法详解

    2023-11-02 23:28:46
  • python实现的登录与提交表单数据功能示例

    2021-04-28 21:16:38
  • php+ajax+h5实现图片上传功能

    2024-05-22 10:05:39
  • 如何通俗的解释TypeScript 泛型

    2024-04-10 16:18:31
  • 教你怎么用Python监控愉客行车程

    2021-10-22 17:59:37
  • 一文详解CNN 解决 Flowers 图像分类任务

    2023-02-28 22:23:39
  • Navicat连接MySQL时出现的连接失败问题及解决

    2024-01-16 00:22:13
  • Python必备技巧之字典(Dictionary)详解

    2022-02-12 23:01:13
  • 关于Vue3过渡动画的踩坑记录

    2024-06-07 16:03:35
  • Go gRPC服务客户端流式RPC教程

    2023-07-16 06:08:55
  • Python字典 dict几种遍历方式

    2023-01-14 19:48:28
  • Python3 max()函数基础用法

    2021-04-16 06:53:26
  • asp之家 网络编程 m.aspxhome.com