tensorflow8-使用inception-v3做各种图像的识别

主要实现功能:使用下载好的 inception 模型对图像进行识别

imagenet_2012_challenge_label_map_proto.pbtxt 文件:主要是id 和 uid 之间的对应关系

imagenet_synset_to_human_label_map.txt 主要是 uid 和 类别名称之间的对应关系

 

代码如下所示:

# -*- coding: utf-8 -*-
"""
Created on Wed Jun 12 17:40:30 2019

@author: 666
"""
import tensorflow as tf
import os
import numpy as np
from PIL import Image
import matplotlib.pylab as plt

class NodeLookup(object):
    def __init__(self):
        label_lookup_path = 'F:\\AI\\AItest\\inception_model\\imagenet_2012_challenge_label_map_proto.pbtxt'
        uid_lookup_path = 'F:\\AI\\AItest\\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_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()
        uid_to_human = {}
        for line in proto_as_ascii_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_to_ascii = tf.gfile.GFile(label_lookup_path).readlines()
        node_id_to_uid = {}
        for line in proto_to_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]

        #建立id 和 name 之间的关系
        node_id_to_name = {}
        for key,val in node_id_to_uid.items():
            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]

with tf.gfile.FastGFile('F:\\AI\\AItest\\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')
    for root,dirs,files in os.walk('F:\\AI\\AItest\\images\\'):
        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) #把结果转化为一维数据
            
            image_path = os.path.join(root,file)
            print(image_path)
            
            #显示图片
            img = Image.open(image_path)
            plt.imshow(img)
            plt.axis('off')
            plt.show()
            
            top_5 = predictions.argsort()[-5:][::-1]
            node_lookup = NodeLookup()
            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))
            print()

注意: 测试的时候,需要在和存放本代码相同的路径之间新建一个 images 文件,里面存放的是需要测试的图片。

测试结果如下:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值