flask+keras实现简单api接口

目的:图片有两种类型分别是zhong和jing,实现预测。

           利用Keras训练好分类模型,创建一个flask api调用,实现图片预测分类。

目录:

flask_api下的代码结构:

app.py:  flask程序

jing.jpg: 测试图片

simple_request.py: 请求程序

vgg_model.h5 : keras已经训练好的模型

cmd.txt: 命令行参数提示信息(无关信息)

1.flask实现api接口

app.py

import os
import io
import flask
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.models import load_model
import numpy as np
from PIL import Image
import tensorflow as tf


# FG class dictory
FG_dict = {0:'jing', 1:'zhong'}
# initialize our Flask application and the Keras model
app = flask.Flask(__name__)

# Global variables
global graph
graph = tf.get_default_graph()
global model
model = load_model('vgg_model.h5')


def prepare_image(image, target):
    # if the image mode is not RGB, convert it
    if image.mode != "RGB":
         image = image.convert("RGB")
    # resize the input image and preprocess it
    image = image.resize(target)
    image = img_to_array(image)/255.
    image = np.expand_dims(image, axis=0)

    return image


@app.route('/')
def hello():
    return "Hello World!"


@app.route("/predict", methods=["POST"])
def predict():
    # initialize the data dictionary that will be returned from the view
    data = {"success": False}
    # ensure an image was properly uploaded to our endpoint
    if flask.request.method == "POST":
        if flask.request.files.get("image"):
            # read the image in PIL format
            image = flask.request.files["image"].read()
            image = Image.open(io.BytesIO(image))
            # preprocess the image and prepare it for classification
            image = prepare_image(image, target=(224, 224))
            # Use default graph very import 
            with graph.as_default():
                preds = model.predict(image)

            probability = np.max(preds)
            label = FG_dict[int(np.argmax(preds))]
        
            data["probability"] = '{:.2f}%'.format(probability*100)
            data["label"] = str(label)
            # indicate that the request was a success
            data["success"] = True

    # return the data dictionary as a JSON response
    return flask.jsonify(data)

代码中有2处坑:

1.定义全局的图和

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值