2015-12-27 11 views
15

転送学習にテンソルフローを使用しようとしています。私はチュートリアルから事前に訓練されたモデルのインセプション3をダウンロードしました。コードでは、予測のために:転送学習のテンソルフローで画像データを入力する

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

png画像を送る方法はありますか? DecodeJpegDecodePngに変更しようとしましたが、動作しませんでした。また、numpy配列や配列のバッチのようなデコードされたイメージファイルをフィードしたいのであれば、私は何を変更すればよいでしょうか?

ありがとうございます!

答えて

27

classify_image.pyで使用されている出荷時のInceptionV3グラフは、すぐに使用できるJPEG画像のみをサポートしています。

  1. height X width×3(チャネル)numpyのアレイは、PILを使用して、例えば、次にフィード'DecodeJpeg:0'テンソルにPNG画像を変換する:あなたは、PNG画像と、このグラフを使用することができる二つの方法があり

    このテンソルを供給することによって、あなたは生の画像データを供給することができますので、
    import numpy as np 
    from PIL import Image 
    # ... 
    
    image = Image.open("example.png") 
    image_array = np.array(image)[:, :, 0:3] # Select RGB channels only. 
    
    prediction = sess.run(softmax_tensor, {'DecodeJpeg:0': image_array}) 
    

    はおそらく紛らわしい、'DecodeJpeg:0'は、DecodeJpegオペアンプの出力です。

  2. インポートしたグラフにtf.image.decode_png() opを追加します。単に供給されたテンソルの名前を'DecodeJpeg/contents:0'から'DecodePng/contents:0'に変更するだけでは、出荷されたグラフに'DecodePng' opが存在しないため、機能しません。あなたはtf.import_graph_def()input_map引数を使用して、グラフに、このようなノードを追加することができます。

    png_data = tf.placeholder(tf.string, shape=[]) 
    decoded_png = tf.image.decode_png(png_data, channels=3) 
    # ... 
    
    graph_def = ... 
    softmax_tensor = tf.import_graph_def(
        graph_def, 
        input_map={'DecodeJpeg:0': decoded_png}, 
        return_elements=['softmax:0']) 
    
    sess.run(softmax_tensor, {png_data: ...}) 
    
+0

私はあなたの最初の方法で試してみました。 「フィードから要素を取得できません」と出力されます。なぜ私は分からない。しかし、あなたの第二の仕事。ありがとう!! –

+0

"フィードから要素を取得できません"というエラーは異常です。つまり、 'image_array'が文字列の配列として扱われていることを意味しています。したがって、画像のTensorFlowテンソルへの型変換に欠けている可能性があります。 – mrry

+2

2番目の答えから、私は 'DecodeJpeg:0'が 'jpg_data = tf.placeholder(tf.string、shape = []);で構築されていると仮定します。 decoded_jpg = tf.image.decode_jpeg(jpg_data、channels = 3) 'numpy配列ではなく文字列を待ちます。 –

1

次のコードは、両方のケースを処理する必要があります。直接文字列を含む

import numpy as np 
from PIL import Image 

image_file = 'test.jpeg' 
with tf.Session() as sess: 

    #  softmax_tensor = sess.graph.get_tensor_by_name('final_result:0') 
    if image_file.lower().endswith('.jpeg'): 
     image_data = tf.gfile.FastGFile(image_file, 'rb').read() 
     prediction = sess.run('final_result:0', {'DecodeJpeg/contents:0': image_data}) 
    elif image_file.lower().endswith('.png'): 
     image = Image.open(image_file) 
     image_array = np.array(image)[:, :, 0:3] 
     prediction = sess.run('final_result:0', {'DecodeJpeg:0': image_array}) 

    prediction = prediction[0]  
    print(prediction) 

または短いバージョン:

image_file = 'test.png' # or 'test.jpeg' 
image_data = tf.gfile.FastGFile(image_file, 'rb').read() 
ph = tf.placeholder(tf.string, shape=[]) 

with tf.Session() as sess:   
    predictions = sess.run(output_layer_name, {ph: image_data}) 
関連する問題