Распознавание изображений с помощью Tensorflow + Keras + Flask - PullRequest
0 голосов
/ 28 мая 2019

Я пытался создать веб-приложение (REST API) для распознавания изображений с помощью Tensorflow + keras во Flask.Я попытался проследить какой-то ресурс, доступный в интернете, и придумал скрипт, как показано ниже:

from imageai.Prediction import ImagePrediction
import os
execution_path = os.getcwd()
prediction = ImagePrediction()
prediction.setModelTypeAsResNet()
prediction.setModelPath( execution_path + "\\resnet50_weights_tf_dim_ordering_tf_kernels.h5")
prediction.loadModel()

for i in range(3):
    predictions, percentage_probabilities = prediction.predictImage("C:\\Users\\Administrator\\Downloads\\pics\\banana"+str(i)+".jpg", result_count=5)
    for index in range(len(predictions)):
        print(predictions[index] , " : " , percentage_probabilities[index])

Это прекрасно работало как автономный скрипт.Затем я попытался преобразовать то же самое в Flask Application, и он начинает терпеть неудачу.

import flask
from imageai.Prediction import ImagePrediction
import os
import json
import keras

# initialize our Flask application and the Keras model
app = flask.Flask(__name__)
def init():
    global model
    execution_path = os.getcwd()
    model = ImagePrediction()
    model.setModelTypeAsResNet() 
    model.setModelPath( os.path.join(os.getcwd(),"models","resnet50_weights_tf_dim_ordering_tf_kernels.h5"))
    model.loadModel()


# API for prediction
@app.route("/predict", methods=["GET"])
def predict():
    predictions, percentage_probabilities =     model.predictImage( os.path.join(os.getcwd(),"pics","banana.jpg"), result_count=5)
    mylist = []
    for index in range(len(predictions)):
        mydict = {}
        mydict[predictions[index]]=percentage_probabilities[index]
        mylist.append(mydict)
    keras.backend.clear_session()

return sendResponse(json.dumps(mylist))

# Cross origin support
def sendResponse(responseObj):
    response = flask.jsonify(responseObj)
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Methods', 'GET')
    response.headers.add('Access-Control-Allow-Headers', 'accept,content-type,Origin,X-Requested-With,Content-Type,access_token,Accept,Authorization,source')
    response.headers.add('Access-Control-Allow-Credentials', True)
    return response

# if this is the main thread of execution first load the model and then start the server
if __name__ == "__main__":
    print(("* Loading Keras model and Flask starting server..."
    "please wait until server has fully started"))
    init()
    app.run(threaded=True)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...