Skip to content

chapter 9. infer.py does not work, but i fixed it. #176

@zoldaten

Description

@zoldaten

here`s working code:

import flask
import tensorflow as tf
from tensorflow import keras
from keras.utils import CustomObjectScope
from keras.models import load_model
from tensorflow.keras.utils import img_to_array
from PIL import Image
import numpy as np
import io
from tensorflow.keras.models import load_model

#curl -X POST -F image=@dog.jpg 'http://localhost:5000/infer' #to predict

app = flask.Flask(__name__)

#with CustomObjectScope({'relu6': keras.applications.mobilenet.relu6}):
with CustomObjectScope({'relu6': keras.layers.ReLU(6.),'DepthwiseConv2D': keras.layers.DepthwiseConv2D}):
    #model = load_model('ADD_H5_MODEL_PATH')
    model = load_model("model.h5")

def preprocess(image):
    image = image.resize((224, 224))
    image = img_to_array(image)
    image = np.expand_dims(image, axis=0)
    return image

@app.route('/infer', methods=['POST'])
def infer():
    file = flask.request.files['image'].read()
    image = Image.open(io.BytesIO(file))
    image = preprocess(image)

    predictions = model.predict(image)
    max_index = np.argmax(predictions)
    
    # We know the labels from the model we trained previously
    if max_index == 0:
        return "Cat"
    else:
        return "Dog"

if __name__ == "__main__":
    app.run()
    #app.run(host="0.0.0.0") # for access from lan

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions