2017-04-08 6 views
-1

私は、特定の順序でpythonスクリプトを実行する必要がある約13000個の画像を持っています。私はforループを使ってみましたが、正しい順序で画像を通過しません。これらの画像が格納されているフォルダは、必ずしも名前順ではありません。私は、順番にファイル名を含むcsvファイルを持っています。おそらく、それはcsvファイルを読み込んで、どのファイルを反復するのかを見つけることができますか?forループで画像を順番に調べる方法

複数の画像を分類し、tensorflow、python、retrainedグラフ、およびそれ以前に生成されたそれぞれのラベルを使用してcsvに印刷しようとしています。

import tensorflow as tf, sys 
import csv 
import numpy 
import os 

files_dir = os.getcwd() + '/Desktop/model/test_stg1/' 
files = os.listdir(files_dir) 

for f in files: 
    if f.lower().endswith(('.png', '.jpg', '.jpeg')): 
     image_path = files_dir + '/' + f 


     image_data = tf.gfile.FastGFile(image_path, 'rb').read() 


     label_lines = [line.rstrip() for line 
         in tf.gfile.GFile("/home/fly/Desktop/model/retrained_labels.txt")] 


     with tf.gfile.FastGFile("/home/fly/Desktop/model/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: 

      softmax_tensor = sess.graph.get_tensor_by_name('final_result:0') 

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


      top_k = predictions[0].argsort()[-len(predictions[0]):][::-1] 


      text_file = open("Outputtest2.csv", "a") 
      for node_id in top_k: 
       human_string = label_lines[node_id] 
       score = predictions[0][node_id] 
       print('%s (score = %.5f)' % (human_string, score)) 
       text_file.write('%s (%.5f),' % (human_string, score)) 
+0

あなたは 'ファイル=ソート(ファイル)'を行うことができますか? –

+0

あなたの質問は何ですか?あなたの質問を改善するために、[最小限の、完全で検証可能なサンプルを作成する方法](https://stackoverflow.com/help/mcve)を参照してください。 – Craig

+0

こんにちは@Craigあなたが見ることができるように、パブロはすでにこれに答えました:) – xion

答えて

0

あなたが望むようにソートされたCSV内のファイルのリストを持っている場合は、[1] CSVを開いて、あなたのファイルを反復処理するためにそれを使用することができます。たとえば、次のように

with open('files_data_sorted.csv', 'r') as csvfile: 
    filedatareader = csv.reader(csvfile, delimiter=' ', quotechar='|') 
    for row in filedatareader: 
     # let's suppose the filename is in column 0 
     fname = row[0] 
     image_path = files_dir + '/' + fname 
     image_data = tf.gfile.FastGFile(image_path, 'rb').read() 

それとも、あなたはアルファベット順にソートしてファイルを持っている場合、あなたは、単にfiles.sort()

を実行することができます[1] https://docs.python.org/2/library/csv.html

関連する問題