Приложение Flask не возвращает jsonified результаты и выдает сообщение об ошибке - PullRequest
0 голосов
/ 16 октября 2019

Когда я запускаю «python app.py» в командной строке для выполнения следующих сценариев, терминал подсказывает мне, что tf.nn.max_pool устарел и обновляется до tf.nn.max_pool2;но я не могу найти статьи в Поиске Google о том, как это сделать. Тем не менее, Flask запускается и даже читает файл изображения, который должен быть обработан и идентифицирован. Тем не менее, jsonified результаты не отображаются, и вместо этого появляется следующее сообщение об ошибке, описывающее проблемы с локальным хостом и TensorFlow, но я не могу найти статьи об устранении неполадок об этом в поиске Google.


import os
import io
import numpy as np

import keras
from keras.preprocessing import image
from keras.preprocessing.image import img_to_array
from keras.applications.xception import (Xception, preprocess_input, decode_predictions)
from keras import backend as K

# I added the below
#import tensorflow as tf
#from tensorflow import keras
#from tensorflow.keras.callbacks import TensorBoard
#I added the above



from flask import Flask, request, redirect, url_for, jsonify


app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'Uploads'

model = None
graph = None


def load_model():

    global model
    global graph

    model = Xception(weights="imagenet")
    graph = K.get_session().graph


load_model()


def prepare_image(img):
    img = img_to_array(img)
    img = np.expand_dims(img, axis=0)
    img = preprocess_input(img)
    # return the processed image
    return img


@app.route('/', methods=['GET', 'POST'])
def upload_file():
    data = {"success": False}
    if request.method == 'POST':
        if request.files.get('file'):
            # read the file
            file = request.files['file']

            # read the filename
            filename = file.filename

            # create a path to the uploads folder
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)

            file.save(filepath)

            # Load the saved image using Keras and resize it to the Xception
            # format of 299x299 pixels
            image_size = (299, 299)
            im = keras.preprocessing.image.load_img(filepath,
                                                    target_size=image_size,
                                                    grayscale=False)

            # preprocess the image and prepare it for classification
            image = prepare_image(im)

            global graph
            with graph.as_default():
                preds = model.predict(image)
                results = decode_predictions(preds)
                # print the results
                print(results)

                data["predictions"] = []

                # loop over the results and add them to the list of
                # returned predictions
                for (imagenetID, label, prob) in results[0]:
                    r = {"label": label, "probability": float(prob)}
                    data["predictions"].append(r)

                # indicate that the request was a success
                data["success"] = True

        return jsonify(data)

    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''


if __name__ == "__main__":
    app.run(debug=True)   


введите описание изображения здесь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...