如何让python逐个读取目录中的所有图像

时间:2017-08-21 10:58:54

标签: python-2.7 tensorflow io

我对python的体验非常有限,所以我不完全理解代码在这个例子中的作用。这是来自tensorflow框架的诗人实验室代码的一部分。

import os, sys

import tensorflow as tf
import sys
import numpy as np
from PIL import Image

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

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

# Read in the image_data
image_data = tf.gfile.FastGFile(image_path, 'rb').read()

image = Image.open(image_path)      
image_array = image.convert('RGB')

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

# Unpersists graph from file
with tf.gfile.FastGFile("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')

predictions = sess.run(softmax_tensor,{'DecodeJpeg:0': image_array})

# Sort to show labels of first prediction in order of confidence
top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]

for node_id in top_k:
    human_string = label_lines[node_id]
    score = predictions[0][node_id]
    print('%s (score = %.5f)' % (human_string, score))


filename = "results.txt"    
with open(filename, 'a+') as f:
    f.write('\n**%s**\n' % (image_path))
    for node_id in top_k:
        human_string = label_lines[node_id]
        score = predictions[0][node_id]
    f.write('%s (score = %.5f)\n' % (human_string, score))

我希望上面的代码读入目录而不是单个图像然后处理它们并将分数输出到results.txt文件。 目前我可以这样称呼:

python this_file.py /root/images/1.jpg

我如何获取此代码以获取以下输入并对其进行处理

python this_file.py /root/images/

1 个答案:

答案 0 :(得分:0)

使用os.listdir列出目录中的所有文件。使用过滤器对其进行鉴定。将生成的文件加入其目录。使用for循环从列表中读取它们。

  
    
      

python this_file.py / root / images /

    
  
image_path = sys.argv[1]
image_paths = [os.path.join(image_path,img) for img in  os.listdir(image_path) if '.jpg' in img]

我还建议您重新检查您的培训功能和策略。使用tf变量占位符尽可能抽象整个网络也是一种好习惯。此外,实现批处理以及可能将数据集转换为tf记录会更有效。