I was following a "Deploy Keras neural network to Flask web service" tutorial by deeplizard on YouTube, but got stuck. I found several suggestions to similar problems which have helped others (like this one and this one), but for some reason they aren't working for me. Or maybe I'm applying them wrong.
It's upset with the line image = Image.open(io.BytesIO(decoded))
.
Here is the code I have (sorry it's not minimal, I'm not sure how to simplify it without dropping details that might be relevant).
If you have any suggestions, please let me know.
Much appreciated.
app = Flask(__name__)
def get_model():
global model, graph
model = load_model('model.h5')
print(' * Model loaded!')
graph = tf.Graph()
def preprocess_image(image, target_size):
if image.mode != 'RGB':
image = image.convert('RGB')
image = image.resize(target_size)
image = img_to_array(image)
image = np.expand_dims(image, axis=0)
return image
print(' * Loading model...')
get_model()
@app.route('/predict', methods=["POST"])
def predict():
message = request.get_json(force=True)
encoded = message['image']
decoded = base64.b64decode(encoded)
with graph.as_default():
image = Image.open(io.BytesIO(decoded))
preprocessed_image = preprocess_image(image, target_size(50, 50))
prediction = model.predict(preprocessed_image).tolist()
response = {
'prediction': {
'food': prediction[0][0],
'notfood': prediction[0][1]
}
}
return jsonify(response)
I suspect it might be because my model takes input as:
model.predict_classes(i.reshape((-1, 50, 50, 3)), batch_size=32, verbose=0)[0]
but the images uploaded through html by user aren't' getting reshaped ... I was trying to finagle that into the code, but no luck so far.