简体   繁体   中英

Tensorflow Inception with image upload

I'm trying to upload an image to TF-Inception model using a Flask wrapper, but here is the error that I'm facing while testing it out via postman. I've tried a lot of google search/SO but not finding a way to figure out how to address the image_data part which originally was

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

but I've changed it to accept the image data using request module of flask, and this is coming to be empty all the time

image_data = request.data

but I want to pass along the image file's data that I'm uploading.

Error:

InvalidArgumentError (see above for traceback): Invalid JPEG data, size 0
     [[Node: DecodeJpeg = DecodeJpeg[acceptable_fraction=1, channels=3, dct_method="", fancy_upscaling=true, ratio=1, try_recover_truncated=false, _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_DecodeJpeg/contents_0)]]

Code:

from flask import Flask, request
import tensorflow as tf
import sys

app = Flask(__name__)

@app.route("/classify", methods=["POST"])
def classify():
    image_data = request.data
    #loads label file, strips off carriage return
    label_lines = [line.strip() for line in tf.gfile.GFile("/tmp/output_labels.txt")]

    # Unpersists graph from file
    with tf.gfile.FastGFile("/tmp/output_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 an get first prediction
        softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
        predictions = sess.run(softmax_tensor, \
             {'DecodeJpeg/contents:0':image_data})
        # 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 = %.2f)' % (human_string, score))

if __name__ == '__main__':
    app.run()

(complete rewrite of answer, thanks for the clarification)

So, what I understand is that your code works well when using a file name directly but is failing once you try reading the file from the POST .

In your code you retrieve the file like so:

image_data = request.data

Looking around the web I've found that you should probably get the data instead like so:

# check if the post request has the file part
if 'file' not in request.files:
    flash('No file part')
    return redirect(request.url)
file = request.files['file']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM