2017-09-28 2 views
0

나는 자체 데이터로 InceptionV3 모델을 재교육했으며 Tensorflow 이미지 분류 자습서 https://www.tensorflow.org/tutorials/image_recognition에서 코드를 수정하려고합니다.TensorFlow 튜토리얼에서 label_image.py를 수정하여 여러 이미지 분류

나는 목록으로 디렉토리에 읽고 그 위에 반복 시도했지만이 작동하지 않았다 :

load_graph(FLAGS.graph) 

filelist = os.listdir(FLAGS.image) 

for i in filelist: 
    # load image 
    image_data = load_image(i) 

난 그냥 오류가 플래그가 정의되지 않았 음을 말하는 얻을, 그래서 나는 플래그가 생각 load_image 함수와 함께 사용 하시겠습니까? 이 작업을해야

import os 
import tensorflow as tf 

# Define this after your imports. This is similar to python argparse except more verbose 
FLAGS = tf.app.flags.FLAGS 

tf.app.flags.DEFINE_string('image', '/Users/photos', 
          """ 
          Define your 'image' folder here 
          or as an argument to your script 
          for eg, test.py --image /Users/.. 
          """) 



# use listdir to list the images in the target folder 
filelist = os.listdir(FLAGS.image) 

# now iterate over the objects in the list 
for i in filelist: 
    # load image 
    image_data = load_image(i) 

,

from __future__ import absolute_import 
from __future__ import division 
from __future__ import print_function 

import argparse 
import sys 
import os 
import tensorflow as tf 

parser = argparse.ArgumentParser() 
parser.add_argument(
    '--image', required=True, type=str, help='Absolute path to image file.') 
parser.add_argument(
    '--num_top_predictions', 
    type=int, 
    default=5, 
    help='Display this many predictions.') 
parser.add_argument(
    '--graph', 
    required=True, 
    type=str, 
    help='Absolute path to graph file (.pb)') 
parser.add_argument(
    '--labels', 
    required=True, 
    type=str, 
    help='Absolute path to labels file (.txt)') 
parser.add_argument(
    '--output_layer', 
    type=str, 
    default='final_result:0', 
    help='Name of the result operation') 
parser.add_argument(
    '--input_layer', 
    type=str, 
    default='DecodeJpeg/contents:0', 
    help='Name of the input operation') 


def load_image(filename): 
    """Read in the image_data to be classified.""" 
    return tf.gfile.FastGFile(filename, 'rb').read() 


def load_labels(filename): 
    """Read in labels, one label per line.""" 
    return [line.rstrip() for line in tf.gfile.GFile(filename)] 


def load_graph(filename): 
    """Unpersists graph from file as default graph.""" 
    with tf.gfile.FastGFile(filename, 'rb') as f: 
    graph_def = tf.GraphDef() 
    graph_def.ParseFromString(f.read()) 
    tf.import_graph_def(graph_def, name='') 


def run_graph(image_data, labels, input_layer_name, output_layer_name, 
       num_top_predictions): 
    with tf.Session() as sess: 
    # Feed the image_data as input to the graph. 
    # predictions will contain a two-dimensional array, where one 
    # dimension represents the input image count, and the other has 
    # predictions per class 
    softmax_tensor = sess.graph.get_tensor_by_name(output_layer_name) 
    predictions, = sess.run(softmax_tensor, {input_layer_name: image_data}) 

    # Sort to show labels in order of confidence 
    top_k = predictions.argsort()[-num_top_predictions:][::-1] 
    for node_id in top_k: 
     human_string = labels[node_id] 
     score = predictions[node_id] 
     print('%s (score = %.5f)' % (human_string, score)) 

    return 0 


def main(argv): 
    """Runs inference on an image.""" 
    if argv[1:]: 
    raise ValueError('Unused Command Line Args: %s' % argv[1:]) 

    if not tf.gfile.Exists(FLAGS.image): 
    tf.logging.fatal('image file does not exist %s', FLAGS.image) 

    if not tf.gfile.Exists(FLAGS.labels): 
    tf.logging.fatal('labels file does not exist %s', FLAGS.labels) 

    if not tf.gfile.Exists(FLAGS.graph): 
    tf.logging.fatal('graph file does not exist %s', FLAGS.graph) 


    # load image 
    image_data = load_image(FLAGS.image) 

    # load labels 
    labels = load_labels(FLAGS.labels) 

    # load graph, which is stored in the default session 
    load_graph(FLAGS.graph) 

    run_graph(image_data, labels, FLAGS.input_layer, FLAGS.output_layer, 
      FLAGS.num_top_predictions) 


if __name__ == '__main__': 
    FLAGS, unparsed = parser.parse_known_args() 
    tf.app.run(main=main, argv=sys.argv[:1]+unparsed) 

답변

0

주어진 도움을 주셔서 감사합니다. 플래그는 TensorFlow 플래그 모듈이 아닌 argparser 모듈에서 가져오고 함수 내에서 FLAGS를 호출해야 할 수 있습니다.

def get_image_list(path): 
    return glob.glob(path + '*.jpg') 

을 그리고 더 루프 호출 아래 :

filelist = get_image_list(FLAGS.image) 

    for i in filelist: 
     image_data = load_image(i) 

     run_graph(image_data, labels, FLAGS.input_layer, FLAGS.output_layer, 
      FLAGS.num_top_predictions) 
을 내가 그 무슨 일이 일어나고 있는지 생각 때문에 나는 결국 별도의 기능을함으로써이 문제를 해결
0

는 다음을 시도 tf.flags.FLAGS, 또는 상단에, from tf.flags import FLAGS

0

을 시도해보십시오이 원래 프로그램입니다. 희망이 도움이됩니다.

관련 문제