基于Flask和VGG19的图像分类Web应用
import os
import sys
# Flask
from flask import Flask, redirect, url_for, request, render_template, Response, jsonify, redirect
from werkzeug.utils import secure_filename
from gevent.pywsgi import WSGIServer
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
from keras.applications.vgg19 import preprocess_input, decode_predictions
from keras.models import load_model
from keras.preprocessing import image
# Some utilites
import numpy as np
from util import base64_to_pil
# Declare a flask app
app = Flask(__name__)
# Load the VGG19 model
model = load_model('models/my_model.h5')
model.make_predict_function()
print('Model loaded. Start serving...')
def model_predict(img, model):
img = img.resize((224, 224))
# Preprocessing the image
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
return preds
@app.route('/', methods=['GET'])
def index():
# Main page
return render_template('index.html')
@app.route('/predict', methods=['GET', 'POST'])
def predict():
if request.method == 'POST':
# Get the image from post request
img = base64_to_pil(request.json)
# Make prediction
preds = model_predict(img, model)
# Process the result
pred_class = np.argmax(preds, axis=1)
class_names = ['class1', 'class2', 'class3', 'class4', 'class5', 'class6', 'class7', 'class8', 'class9', 'class10']
result = []
for i in range(5):
result.append(class_names[pred_class[0][i]])
# Serialize the result, you can add additional fields
return jsonify(result=result)
return None
if __name__ == '__main__':
# Serve the app with gevent
http_server = WSGIServer(('0.0.0.0', 5000), app)
http_server.serve_forever()
原文地址: https://www.cveoy.top/t/topic/H1t 著作权归作者所有。请勿转载和采集!