我需要将上传的图像传递给flask。 html页面上载图像,但我无法将该图像作为请求传输到烧瓶。 我将其用于图像预测,但是无法获取图像。
这是我的烧瓶代码
import numpy as np
from flask import Flask, request, jsonify, render_template
import numpy
from PIL import Image
from keras.models import load_model
app = Flask(__name__)
model = load_model('traffic_classifier.h5')
classes = { 1:'Speed limit (20km/h)',
2:'Speed limit (30km/h)',
3:'Speed limit (50km/h)',
4:'Speed limit (60km/h)',
5:'Speed limit (70km/h)',
6:'Speed limit (80km/h)',
7:'End of speed limit (80km/h)',
8:'Speed limit (100km/h)',
9:'Speed limit (120km/h)',
10:'No passing',
11:'No passing veh over 3.5 tons',
12:'Right-of-way at intersection',
13:'Priority road',
14:'Yield',
15:'Stop',
16:'No vehicles',
17:'Veh > 3.5 tons prohibited',
18:'No entry',
19:'General caution',
20:'Dangerous curve left',
21:'Dangerous curve right',
22:'Double curve',
23:'Bumpy road',
24:'Slippery road',
25:'Road narrows on the right',
26:'Road work',
27:'Traffic signals',
28:'Pedestrians',
29:'Children crossing',
30:'Bicycles crossing',
31:'Beware of ice/snow',
32:'Wild animals crossing',
33:'End speed + passing limits',
34:'Turn right ahead',
35:'Turn left ahead',
36:'Ahead only',
37:'Go straight or right',
38:'Go straight or left',
39:'Keep right',
40:'Keep left',
41:'Roundabout mandatory',
42:'End of no passing',
43:'End no passing veh > 3.5 tons' }
@app.route('/')
def index():
# Main page
return render_template('index.html')
@app.route('/traffic')
def traffic():
# Main page
return render_template('traffic.html')
@app.route('/sleep')
def sleep():
# Main page
return render_template('sleep.html')
@app.route('/predict',methods=['POST'])
def predict():
'''
For rendering results on HTML GUI
'''
if request. method == "POST":
image=request. form["fileupload"]
image = Image.open('D:/main_project/Traffic/Test/00006.png')
image = image.resize((30,30))
image = numpy.expand_dims(image, axis=0)
image = numpy.array(image)
pred = model.predict_classes([image])[0]
sign = classes[pred+1]
return render_template('traffic.html', prediction_text='This sign represents {}'.format(sign))
@app.route('/predict_api',methods=['POST'])
def predict_api():
'''
For direct API calls trought request
'''
data = request.get_json(force=True)
prediction = model.predict([np.array(list(data.values()))])
output = prediction[0]
return jsonify(output)
if __name__ == "__main__":
app.run(debug=True)
这是我的html代码
<!DOCTYPE html>
<html lang="en-US" class="no-js no-svg">
<br />
<h2>Upload Traffic Signs</h2>
<br />
<br />
<br />
<form action="{{ url_for('predict')}}"method="post">
<input id="fileupload" name="fileupload" type="file" />
<b></b>
<br />
<br />
<div width="250px" height="300px" id="dvPreview">
</div>
<br />
<br />
<div id="txt" >
</div>
<button type="submit" class="button button4">Classify Sign</button>
</form>
<br />
{{ prediction_text }}
<br />
<br />
<br />
<!-- images uploader ends-->
</html>
我需要ID来预测该图像,但不能根据请求传输该图像。请为此提供帮助。
答案 0 :(得分:1)
<form method="post" action="{{ url_for('') }}" enctype="multipart/form-data">
def upload_image():
try:
if request.method == 'POST':
ALLOWED_EXTENSIONS = [".png", ".jpg", ".jpeg", ".gif"]
file = request.files['image']
if file and any(split_filename(file.filename)[1] == s for s in ALLOWED_EXTENSIONS):
folder = app.config['UPLOAD_FOLDER']
pathName = app.config['IMAGE_PATH'] + datetime.utcnow().strftime(
'%Y\\%m\\')
if not os.path.exists(os.path.join(folder + pathName)):
os.makedirs(folder + pathName)
filename = str(uuid.uuid4()) + split_filename(file.filename)[1]
file.save(os.path.join(folder + pathName, filename))
path = pathlib.PureWindowsPath(pathName + filename).as_posix()
return url_for('main.get_file', path=path, _external=True)
else:
return 'Please Choose PNG, JPG, JPEG, GIF Image, Not ' + split_filename(file.filename)[1], 404
except Exception as error:
return error.__str__()
@mn.route('/file/<path:path>', methods=['GET'])
def get_file(path):
try:
return send_file(os.path.join(app.config['UPLOAD_FOLDER'], path))
except :
return send_file(os.path.join(app.config['UPLOAD_FOLDER'], '404.png'))
这是我的代码