keras Python皮+ flask :当我选择文件图像,它不工作,不显示在Web应用程序上

bzzcjhmw  于 2022-11-13  发布在  Python
关注(0)|答案(1)|浏览(128)

下面的代码给出错误UnboundLocalError:赋值前引用局部变量'predictions'

***编辑:*我添加预测=“”它不是错误!但当我选择文件图像时。它不工作,不显示在Web应用程序上。我该怎么办?

app.py

from flask import Flask, render_template, request, redirect
import tensorflow as tf
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
from tensorflow.keras.models import model_from_json
from tensorflow.keras.preprocessing.image import img_to_array
import numpy as np
from PIL import Image
from io import BytesIO
from keras.models import load_model

model = None
app = Flask(__name__)

model = load_model('model.h5')

def process_image(image):
    image = Image.open(BytesIO(image))
    if image.mode != "RGB":
        image = image.convert("RGB")
    image = image.resize((224, 224))
    image = img_to_array(image)
    image = preprocess_input(image)
    image = np.expand_dims(image, axis = 0)
    return image

@app.route("/submit", methods=['GET', 'POST'])
def get_output():
        if request.method == "POST":
            if request.files:
                try:
                    image = request.files["image"].read()
                    image = process_image(image)
                    out = model.predict(image)
                    if np.round(out[0][1], 2) > np.round(out[0][0], 2):
                        predictions = "Normal have an accuracy of " + str(np.round(out[0][1]*100, 2)) + "%"
                    else:
                        predictions = "Pneumonia have an accuracy of " + str(np.round(out[0][0]*100, 2)) + "%"
                except:
                    redirect('/submit')
        return render_template("Analysis.html", predictions = predictions)

if __name__ == "__main__":
    app.run(debug = True, threaded = False)

我在使用flask时遇到问题。我收到此错误
我能怎么办呢?

html文件

<section class="upload">
    <form id = "upload" action="/submit" method="POST" enctype="multipart/form-data">
    <center style="margin-top: 1rem;">
        <div class="form-group">
            <input type="file" id="image" name="image" onchange="loadFile(event)">
        </div>
        <div class="form-group">
            <button type="submit" id ="predict" class="btn btn-primary" style="display: none; margin-top: 1rem;">Predict Image</button>
        </div>
    </center>
    </form>
</section>

<center style="margin-top: 1rem;">
<section class="Predictions">
    <div>
    {% if predictions %}
        <div class="img-preview">
        <p><img id="output" style="width: 100%; height: 480px;" /></p>
        </div>
        <button type="button" class="btn btn-dark" style="font-size: 20px; margin-top: 1rem;">{{predictions}}</button>
    {% endif %}
    </div>
</section>

<script>
window.onload = function() {
    let profileImage = localStorage.getItem("profileImageData");
    if (profileImage !== null) {
                                           
        document.getElementById("output").src = profileImage
    }
}

const loadFile = function(event) {
    document.getElementById('predict').style.display = 'block'                              
    let image = document.getElementById('output');
    image.src = URL.createObjectURL(event.target.files[0]);
};
                         document.getElementById("image").addEventListener('change', function() {
    var file = this.files[0];
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {                                   
        localStorage.setItem("profileImageData", reader.result);
    };
} );
</script>
</center>

我该如何解决这个问题?

wwtsj6pe

wwtsj6pe1#

我的猜测是,因为你只在两个if命令中创建了变量predictions,python告诉你,你不能返回它,因为它不是100%确定变量被创建了。

def get_output():
    if request.method == "POST":
        predictions = ""
        if request.files:
            try:
                image = request.files["image"].read()
                image = process_image(image)
                out = model.predict(image)
                if np.round(out[0][1], 2) > np.round(out[0][0], 2):
                    predictions = "Normal have an accuracy of " + str(np.round(out[0][1]*100, 2)) + "%"
                else:
                    predictions = "Pneumonia have an accuracy of " + str(np.round(out[0][0]*100, 2)) + "%"
            except:
                redirect('/submit')
    return render_template("Analysis.html", predictions = predictions)

添加预测=“”确保变量存在!
我已经经历过很多次了...对我来说,它成功了!

相关问题