不明白为什么我不能旋转烧瓶中的图像并显示它,继续显示损坏的图片图标

问题描述 投票:1回答:1

我正在使用Flask尝试提供处理过的图像,如裁剪或在我的模型处理后将其转换为用户,但总是很短,因为它会产生一些错误。当我使用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.pydata.org/bokeh/release/bokeh-0.12.10.min.js"> 
</script>
<script src="http://cdn.pydata.org/bokeh/release/bokeh-widgets- 
0.12.10.min.js"></script>
{% endblock %}
python html flask rotation
1个回答
0
投票

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

以下是一个有效的实施。为了便于阅读,我删除了预测代码并能够在我的最后运行它。在你的情况下,你需要用uploads替换os.path.join中的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)

输出:

Code output in browser showing original image and rotated image

© www.soinside.com 2019 - 2024. All rights reserved.