我正在使用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.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 %}
最佳答案
您需要为旋转后的图像生成有效的URL,该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)
输出:
关于python - 不明白为什么继续显示残缺的图片图标,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55456317/