代码拉取完成,页面将自动刷新
同步操作将从 姬缈/keras-flask-deploy-webapp 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
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 tensorflow.keras.applications.imagenet_utils import preprocess_input, decode_predictions
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
# Some utilites
import numpy as np
from util import base64_to_pil
# Declare a flask app
app = Flask(__name__)
# You can use pretrained model from Keras
# Check https://keras.io/applications/
# or https://www.tensorflow.org/api_docs/python/tf/keras/applications
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2
model = MobileNetV2(weights='imagenet')
print('Model loaded. Check http://127.0.0.1:5000/')
# Model saved with Keras model.save()
MODEL_PATH = 'models/your_model.h5'
# Load your own trained model
# model = load_model(MODEL_PATH)
# model._make_predict_function() # Necessary
# 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.true_divide(x, 255)
x = np.expand_dims(x, axis=0)
# Be careful how your trained model deals with the input
# otherwise, it won't make correct prediction!
x = preprocess_input(x, mode='tf')
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)
# Save the image to ./uploads
# img.save("./uploads/image.png")
# Make prediction
preds = model_predict(img, model)
# Process your result for human
pred_proba = "{:.3f}".format(np.amax(preds)) # Max probability
pred_class = decode_predictions(preds, top=1) # ImageNet Decode
result = str(pred_class[0][0][1]) # Convert to string
result = result.replace('_', ' ').capitalize()
# Serialize the result, you can add additional fields
return jsonify(result=result, probability=pred_proba)
return None
if __name__ == '__main__':
# app.run(port=5002, threaded=False)
# Serve the app with gevent
http_server = WSGIServer(('0.0.0.0', 5000), app)
http_server.serve_forever()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。