目的:图片有两种类型分别是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.定义全局的图和