不明白为什么一直显示损坏的图片图标

Don't understand why keeps on showing a broken picture icon

我正在使用 Flask 尝试提供经过处理的图像,例如在我的模型处理后将其裁剪或转换给用户,但总是不够用,因为它会产生一些 error.When 我使用了 numpy.rot90 (),它没有按计划旋转我的图像,而是我得到了这个。

GET/predict/%3CPIL.JpegImagePlugin.JpegImageFile%20image%20mode=RGB%20size=64x64%20at%200xCE11748%3E HTTP/1.1" 500 -

这是我的代码:

@app.route('/predict/<filename>')
def predict(filename):
image_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
img = Image.open(image_path)
image_url = url_for('images', filename=filename)
image_mtx = imread(image_path)
image_mtx = image_mtx / 255.
image_mtx = image_mtx.reshape(-1, 64, 64, 3)
predictions = model.predict(image_mtx)

angles = ['0', '180', '270', '90']
angle = [0, 90, 180, 270]

confidence = str(round(max(predictions[0]), 4))
predictions = angles[np.argmax(predictions)]
print(predictions)

#img = img.rotate(1*int(angle)) #Clockwise (positive), to change to anti-clockwise put -1 
#img = numpy.rot90(img)
if confidence >= '0.8':
    if predictions == '270': angle = 90 
    elif predictions == '180': angle = 180 
    elif predictions == '90': angle = 270
    elif predictions == '0' : angle = 0

numpy.rot90(img)

return render_template(
    'predict.html',
    image_url=image_url,
    img=img,
    predictions=predictions,
    confidence=confidence
)

html 文件:

{% extends 'layout.html' %}
{% block body %}
<div class="centered">

<p>Image Given</p>
<img src="{{image_url}}" name="image_url" id="image_url">
<p>Looks like it's {{confidence|safe }}</p>
<p>The picture is rotated at {{ predictions|safe }} degrees</p>
<p>Fixed Image</p>
<img src="{{img}}" name="img" id="img">
</div>
<script src="http://cdn.bokeh.org/bokeh/release/bokeh-0.12.10.min.js"> 
</script>
<script src="http://cdn.bokeh.org/bokeh/release/bokeh-widgets- 
0.12.10.min.js"></script>
{% endblock %}

您需要为 returns 图像文件的旋转图像生成有效 URL。为此,首先保存旋转后的图像。然后你可以使用 url_for 为它生成一个 URL,就像原始图像一样。

下面是一个有效的实现。我删除了预测代码以提高可读性并能够 运行 它在我这边。在您的情况下,您需要将 os.path.join 中的 uploads 替换为 app.config['UPLOAD_FOLDER']

import os
from flask import Flask, render_template, url_for, send_file
from PIL import Image
app = Flask(__name__)

@app.route('/images/<filename>')
def images(filename):
    image_path = os.path.join('uploads', filename)
    return send_file(image_path)

@app.route('/predict/<filename>')
def predict(filename):
    image_path = os.path.join('uploads', filename)
    img = Image.open(image_path)
    image_url = url_for('images', filename=filename)

    # rotate image 90 degrees and save rotated image
    fixed_img = img.rotate(90)
    fixed_img.save(os.path.join('uploads', 'fixed_' + filename))
    fixed_image_url = url_for('images', filename='fixed_' + filename)

    img.close()

    return render_template(
        'predict.html',
        image_url=image_url,
        img=fixed_image_url
    )

if (__name__ == "__main__"):
    app.run(port = 8000)

输出: