第十期 使用 Keras 和 Flask 构建一个在线 API 《显卡就是开发板》

版权声明:本文为aggresss原创文章,未经博主允许不得转载。 作者:[email protected] https://blog.csdn.net/aggresss/article/details/78599829

  用Jupyter notebook 来进行演示在生产环境中并不是很实用,在应用环境中如果想要预测一个场景通常需要返回指定格式的文本形式的信息,我写了一个小例子,使用flask架构创建了一个简陋的API,客户端通过curl工具上传图片,并返回指定格式的json流。
  首先需要安装flask

pip install flask

  将下面的代码保存为 keras_api.py 然后在实验环境下输入 python keras_api.py 就可以运行这个API,默认监听6006端口.
  对应github地址: https://github.com/aggresss/GPUDemo/blob/master/keras_api.py

from flask import Flask,request,redirect,url_for
from werkzeug.utils import secure_filename
from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input, decode_predictions
import numpy as np
import os, json


app = Flask(__name__)
@app.route('/upload', methods=['POST', 'GET'])
def upload():
    if request.method == 'POST':
        f = request.files['file']
        basepath = os.path.dirname(__file__)
        upload_path = os.path.join(basepath, 'demo.jpg')
        f.save(upload_path)

        img = image.load_img(upload_path, target_size=(224, 224))
        x = image.img_to_array(img)
        x = np.expand_dims(x, axis=0)
        x = preprocess_input(x)

        model = VGG16(weights='imagenet')
        features = model.predict(x)
        result_list = list(decode_predictions(features, top=1)[0][0])
        result_trans = [ str(x) for x in result_list ]
        result_json = json.dumps(result_trans)
        return result_json + '\n'
    return 'Error Format'

if __name__ == '__main__':
    app.run(debug=False, host='0.0.0.0', port=6006)

  当API服务运行后,使用下面的命令可以验证API的输出

curl -m 300 -F "[email protected];type=image/jpeg" http://127.0.0.1:6006/upload

其中 -m 300 表示超时时间为300秒,如果运算速度慢可以延长超时时间,demo.jpg 为上传图片的路径和文件名.
  正常情况下可以返回类似 [“n02114367”, “timber_wolf”, “0.737966”] 格式的 json 数据流.

猜你喜欢

转载自blog.csdn.net/aggresss/article/details/78599829