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_classes = np.argsort(preds[0])[::-1][:5]
    class_names = ['class1', 'class2', 'class3', 'class4', 'class5', 'class6', 'class7', 'class8', 'class9', 'class10']
    result = []

    for i in range(5):
        result.append({
            'class': class_names[pred_classes[i]],
            'probability': float(preds[0][pred_classes[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()

基于 Flask 和 TensorFlow 的图像分类 API

原文地址: https://www.cveoy.top/t/topic/H3r 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录