1

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.

Raksha
  • 1,572
  • 2
  • 28
  • 53

1 Answers1

1

I was stuck with the same problem. There was no issue with the target size as it will depend on the target size of images in dataset your deployed model was trained on.

Anyway, problem lies with the type of image (png/jpg) you are sending to the server from client's end. Make sure in the below code line (clientside.html)

base64Image = dataURL.replace("data:image/png;base64,","");

you specifically mentioned png and you are also sending the same type of image like imagename.png (png images).

I hope this might helpt

Adeel Afzal
  • 191
  • 1
  • 4