诗人的Tensorflow

时间:2017-06-12 14:49:53

标签: python tensorflow

在诗人的张量流中,有一个名为label_image.py的脚本,它采用单个图像并根据概率吐出5个预测。有没有办法给它一个完整的图像文件夹,并要求它可以在文本文件中逐个存储预测?

指向文件的链接 - https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/#5

1 个答案:

答案 0 :(得分:2)

我试过这个并且对我很好。以下是您可能想要尝试的代码。如果您需要非常具体的内容,可以进行更改。

import os, sys
import glob
import tensorflow as tf

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

# change this as you see fit
image_path = sys.argv[1]

extension = ['*.jpeg', '*.jpg']
files=[]

for e in extension:
directory = os.path.join(image_path, e)
fileList = glob.glob(directory)
for f in fileList:
    files.append(f)

# Loads label file, strips off carriage return
label_lines = [line.rstrip() for line
           in tf.gfile.GFile("/path_to_file/retrained_labels.txt")]

# Unpersists graph from file
with tf.gfile.FastGFile("/path_to_file/retrained_graph.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:
    # Feed the image_data as input to the graph and get first prediction
    softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')

    # Read in the image_data
    for file in files:
        image_data = tf.gfile.FastGFile(file, 'rb').read()

        predictions = sess.run(softmax_tensor, \
                       {'DecodeJpeg/contents:0': image_data})

    # Sort to show labels of first prediction in order of confidence
        top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]
        print("Image Name: " + file)
        for node_id in top_k:
            human_string = label_lines[node_id]
            score = predictions[0][node_id]
            print('%s (score = %.5f)' % (human_string, score))