Tensorflow Inception-v3 图像识别

Inception-v3 图像识别

导入模块

import tensorflow as tf
import os
import numpy as np
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):     
        proto_as_ascill_lines = tf.gfile.GFile(uid_lookup_path).readlines()
        uid_to_human = {}
        #一行一行读取数据
        for line in proto_as_ascill_lines:
            line = line.strip('\n')
            parsed_items = line.split('\t')
            uid = parsed_items[0]  #分类编号
            human_string = parsed_items[1]  #分类名称
            #编号字符串与分类名称一一对应
            uid_to_human[uid] = human_string
                
        proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()
        node_id_to_uid = {}
        for line in proto_as_ascii:
            line = line.strip('\n')
            if line.startswith('  target_class:'):
                target_class = int(line.split(': ')[1])  #获取分类编号target_class_string
            if line.startswith('  target_class_string:'):
                target_class_string = line.split(': ')[1]
                node_id_to_uid[target_class] = target_class_string[1:-1]  #分类编号和target_class一一对应
        
        node_id_to_name = {}
        for key,val in node_id_to_uid.items():
            name = uid_to_human[val]
            node_id_to_name[key] = name   #建立分类编号到1-1000(target_class)的对应关系
        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]

#创建图来存放google训练好的模型
with tf.gfile.GFile('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')  #获取网络最后输出的tensor
    #遍历目录
    for root,dirs,files in os.walk('image/'):
        for file in files:
            #载入图片
            image_data = tf.gfile.GFile(os.path.join(root,file),'rb').read()
            predictions = sess.run(softmax_tensor,{'DecodeJpeg/contents:0':image_data})
            predictions = np.squeeze(predictions)  #把结果转为一维数据
            print(predictions.shape)
            
            #打印图片路径及名称
            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]  #获取概率最大的5个值
            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()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值