OSError:尝试使用Keras模型进行预测时,无法识别图像文件<_io.BytesIO对象在...>

时间:2018-11-03 22:43:45

标签: python tensorflow flask keras

我在YouTube上关注deeplizard撰写的“将Keras神经网络部署到Flask Web服务”教程,但遇到了麻烦。 我发现了一些类似问题的建议,这些问题已经帮助了其他人(例如this onethis one),但由于某些原因,它们对我没有用。也许我错误地应用了它们。

image = Image.open(io.BytesIO(decoded))行感到沮丧。

这是我的代码(对不起,这不是最少的,我不确定如何在不删除可能相关的细节的情况下简化它)。

如果您有任何建议,请告诉我。

非常感谢。

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)

我怀疑这可能是因为我的模型将输入作为:

model.predict_classes(i.reshape((-1, 50, 50, 3)), batch_size=32, verbose=0)[0]

但是用户通过html上传的图像没有得到重塑...我试图将其添加到代码中,但到目前为止还没有运气。

1 个答案:

答案 0 :(得分:1)

我也遇到了同样的问题。目标大小没有问题,因为它取决于训练了部署模型的数据集中图像的目标大小。

无论如何,问题出在从客户端发送到服务器的图像类型(png / jpg)。确保在下面的代码行(clientside.html)

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

您特别提到了 png ,并且还发送了与 imagename.png (png图像)相同类型的图像。

我希望这会有所帮助