2017-04-08 116 views
-1

我有大約13000個圖像需要通過特定順序的python腳本運行。我嘗試使用for循環,但是,它不按照正確的順序通過圖像。包含這些圖像的文件夾按順序排列,但不一定按名稱排列。我有一個順序包含文件名稱的csv文件。也許它可以讀取csv文件來查找要迭代哪一個?如何按照順序遍歷for循環中的圖像

我試圖對多個圖像進行分類,然後使用tensorflow,python,再培訓的圖形以及它們在此之前生成的各自標籤將它們打印到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

嗨@克雷格沒有必要,你可以看到,巴勃羅已經回答了這個:) – xion

回答

0

如果你有一個CSV文件的排序,你所希望的方式列表中,您可以打開CSV [1],並使用通過您的文件進行迭代。例如:

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