Practical-Deep-Learning-Book icon indicating copy to clipboard operation
Practical-Deep-Learning-Book copied to clipboard

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

Open zoldaten opened this issue 1 year ago • 1 comments

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 [email protected] '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

zoldaten avatar Apr 11 '23 10:04 zoldaten

Appreciate sharing this @zoldaten , we'll start to incorporate this soon.

koul avatar Apr 15 '23 18:04 koul