# 加载分类字符串n********对应分类编号1-1000的文件 proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines() node_id_to_uid = {} for line in proto_as_ascii: if line.startswith(' target_class:'): #获取分类编号1-1000 target_class = int(line.split(': ')[1]) if line.startswith(' target_class_string:'): #获取编号字符串n******** target_class_string = line.split(': ')[1] #保存分类编号1-1000与编号字符串n********映射关系 node_id_to_uid[target_class] = target_class_string[1:-2]
#建立分类编号1-1000对应分类名称的映射关系 node_id_to_name = {} for key, val in node_id_to_uid.items(): #获取分类名称 name = uid_to_human[val] #建立分类编号1-1000到分类名称的映射关系 node_id_to_name[key] = name return node_id_to_name
#传入分类编号1-1000返回分类名称 defid_to_string(self, node_id): if node_id notinself.node_lookup: return'' returnself.node_lookup[node_id]
#创建一个图来存放google训练好的模型 with tf.gfile.FastGFile('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('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})#图片格式是jpg格式 #predictions = sess.run(softmax_tensor,{'DecodeGif/contents:0': image_data})#图片格式是jpg格式 predictions = np.squeeze(predictions)#把结果转为1维数据