【问题标题】:OSError: cannot identify image file <_io.BytesIO object at ... > when trying to predict with Keras modelOSError: cannot identify image file <_io.BytesIO object at ...> 尝试使用 Keras 模型进行预测时
【发布时间】:2018-11-03 22:43:45
【问题描述】:

我在 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 上传的图像并没有被重新塑造......我试图将其添加到代码中,但到目前为止还没有运气。

【问题讨论】:

  • 您尝试加载的图片格式是什么?
  • @MatiasValdenegro,jpg。我想弄清楚如何允许多种格式,但首先我只想让它工作
  • 您使用的Image 类是什么?请提供完整的错误堆栈跟踪。

标签: python tensorflow flask keras


【解决方案1】:

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

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

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

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

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2021-05-23
    • 2014-07-24
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 2018-05-30
    相关资源
    最近更新 更多