我正在使用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 %}
答案 0 :(得分:0)
您需要为旋转的图像生成一个有效的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)
输出: