【发布时间】:2021-11-18 04:46:20
【问题描述】:
我创建了一个 html 模板来预测值,但无法做到这一点。我对flask 了解不多,但尝试开始。你能帮我解决这个问题吗?
我的代码相关部分如下:
我无法预测价值
from __future__ import division, print_function
import sys
import os
import glob
import re
import numpy as np
from tensorflow.keras.applications.imagenet_utils import preprocess_input, decode_predictions
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
from flask import Flask, redirect, url_for, request, render_template
from werkzeug.utils import secure_filename
app = Flask(__name__)
MODEL_PATH ='model_resnet50.h5'
model = load_model(MODEL_PATH)
def model_predict(img_path, model):
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x=x/255
x = np.expand_dims(x, axis=0)
preds = model.predict(x)
preds=np.argmax(preds, axis=1)
if preds==0:
preds="Dhoni"
elif preds==1:
preds="Kohli"
else:
preds="Rohith"
return preds
@app.route('/', methods=['GET'])
def index():
# Main page
return render_template('index.html')
@app.route('/predict', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
f = request.files['file']
basepath = os.path.dirname(__file__)
file_path = os.path.join(
basepath, 'uploads', secure_filename(f.filename))
f.save(file_path)
preds = model_predict(file_path, model)
result=preds
return result
if __name__ == '__main__':
app.run(debug=True)
我的index.html
这是我的index.html。请帮我解决问题
<h2>Predict Image</h2>
<div>
<form id="upload-file" method="post" enctype="multipart/form-data">
<label for="imageUpload" class="upload-label">
Choose...
</label>
<input type="file" name="file" id="imageUpload" accept=".png, .jpg, .jpeg">
</form>
<div>
<button type="button" class="btn btn-primary btn-lg " id="btn-predict">Predict!</button>
</div>
<h3 id="result">
<span> </span>
</h3>
</div>
【问题讨论】:
-
你在
<form>中没有action="/predict",所以它发送到/,因为它是从/加载的 -
发送
<form>你把<button>放在<form>里面 -
upload()应该生成文本或 HTML,即使request.method是GET- 或从methods=[...]中删除GET
标签: python tensorflow flask keras