[深度学习]inception_v3识别任何图片(代码)

运用已经在imagenet上训练的inception_v3网络,识别各种图片:

1. 在网上下载Inception_v3的训练模型,解压后会得到如下文件(需要的可以私信我):
在这里插入图片描述
其中第一个第二个是imagenet中数字标号和英文label的文件:
在这里插入图片描述
在这里插入图片描述
第三个是该模型结构的带权重的Graph.
2.运用下面的代码可以生成一个tfevents文件,然后用tensorboard查看他的网络结构.

import tensorflow as tf
import os
inception_pretrain_model_dir = './inception_v3'
log_dir = 'inception_v3_log'
if not os.path.exists(log_dir):
    os.makedirs(log_dir)
   
inception_graph_def_file = os.path.join(inception_pretrain_model_dir, 'classify_image_graph_def.ckpt')

with tf.Session() as sess:
    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()
    


在这里插入图片描述
在这里插入图片描述3.然后加载模型到图中,把label写入新的字典,方便后期数字和英文转换.然后进行检测.

import tensorflow as tf 
import os
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
label_lookup_path = './imagenet_2012_challenge_label_map_proto.pbtxt'
id_lookup_path ='./imagenet_synset_to_human_label_map.txt'

class Nodelookup(object):
    def __init__(self,label_lookup_path, id_lookup_path):
        self.label_lookup_path = label_lookup_path
        self.id_lookup_path =id_lookup_path
        self.node_lookup = self.load(self.label_lookup_path, self.id_lookup_path)
        
    def load(self, label_lookup_path, id_lookup_path):
        #分类字符串对应的类别名称  (n00004475	organism, being)
        human_label = tf.gfile.GFile(id_lookup_path).readlines()
        id_to_human = {}
        for line in human_label:
            line = line.strip('\n')
            parsed_item = line.split('\t')
            uid = parsed_item[0]
            human_string = parsed_item[1]
            id_to_human[uid] = human_string
         
        
        #分类字符串与对应的编号
        '''entry {
                  target_class: 449
                  target_class_string: "n01440764"
                }'''
        
        label_to_id = tf.gfile.GFile(label_lookup_path).readlines()
        id_to_label = {}
        for line in label_to_id:
            if line.startswith('  target_class:'):
                target_class = int(line.split(': ')[1])
                
            if line.startswith('  target_class_string:'):
                target_class_string  = line.split(': ')[1]
                #不要左右的引号所以是从1:-2
                id_to_label[target_class] = target_class_string[1:-2]
         
        #建立一个新的字典,第二个字典的val作为第一个字典的key,得到的数值(也就是英文类别名称)作为新字典的val.
        #再把第二个字典的key作为新字典的key,建立新的对应(44----dog)
        id_to_name = {}
        for key, val in id_to_label.items():
            number = id_to_human[val]
            id_to_name[key] = number
        return 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训练好的模型
with tf.gfile.FastGFile('./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('image/'):
        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})
            predictions = np.squeeze(predictions)
            img_path = os.path.join(root, file)
            
            print(img_path)
            img = Image.open(img_path)
            plt.imshow(img)
            plt.axis('off')
            plt.show()
            
            node_lookup =Nodelookup(label_lookup_path, id_lookup_path)
            top_k = predictions.argsort()[-1:]
            for node_id in top_k:
                result = node_lookup.id_to_string(node_id)
                score = predictions[node_id]
                print('识别为: %s | 概率为: %.4f'% (result, score))
            print('\n')

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值