Flask JSONDecodeError:期望值:第 1 行第 1 列(字符 0)

时间:2021-03-16 15:56:40

标签: python flask

嗨,我正在尝试使用flask进行图像预测,当我上传图像进行预测时,一旦我上传图像以预测结果,它就会抛出此错误JSONDecodeError: Expecting value: line 1 column 1 (char 0).

Traceback (most recent call last):
  File "app.py", line 54, in <module>
    predict()
  File "app.py", line 46, in predict
    image = load_request_image(image)
  File "app.py", line 16, in load_request_image
    image = Image.fromarray(np.array(json.loads(file), dtype='uint8'))
  File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

这是我的 app.py load_model() 函数中存在一些问题

from flask import Flask, render_template, request, jsonify
from flask_compress import Compress
import tensorflow as tf
from keras.models import model_from_json
from keras.applications.mobilenet_v2 import preprocess_input

from PIL import Image
from io import BytesIO
from keras.preprocessing.image import img_to_array
import numpy as np
import json

app = Flask(__name__)
model = None
graph = tf.get_default_graph()

def load_request_image(file):

    image = Image.fromarray(np.array(json.loads(file), dtype='uint8'))
    if image.mode != "RGB":
        image = image.convert("RGB")
    image = image.resize((48, 48))
    image = img_to_array(image)
    image = preprocess_input(image)
    image = np.expand_dims(image, axis=0)

    return image

def load_model():
    json_file = open('./model/model.json', 'r')
    model_json = json_file.read()
    json_file.close()
    global model
    model = model_from_json(model_json)
    model.load_weights("./model/weights.h5")

def predict_class(image_array):
    classes = ["Benign", "Malignant"]

    with graph.as_default():
        y_pred = model.predict(image_array, batch_size=None, verbose=0, steps=None)[0]
        class_index = np.argmax(y_pred, axis=0)
        confidence = y_pred[class_index]
        class_predicted = classes[class_index]
        return class_predicted, confidence

@app.route("/predict", methods=["POST"])
def predict():
    image = request.form["file"]
    image = load_request_image(image)
    class_predicted, confidence = predict_class(image)
    image_class = { "class": class_predicted, "confidence": str(confidence) } 

    return jsonify(image_class)

if __name__ == "__main__":
    load_model()
    app.run(host="0.0.0.0" ,port=7000, debug = True, threaded = True)

if __name__ == "app":
    load_model()

这是我提交图像后预测结果的函数

def breast_check(file):
    i = Image.open(file)
    json_data = json.dumps(np.array(i).tolist())
    resp = requests.post("http://0.0.0.0:7000/predict", data={'file':json_data})
    data = json.loads(resp.text)
    return [data['class'], data['confidence']]

这是我的route

@app.route("/breast", methods=["GET", "POST"])
@login_required
def breast():
  image_class = {}
    patient = None

    form = BreastForm()
    searchForm = PatientSearchForm()

    if searchForm.submit.data and searchForm.validate():
        patient = Patient.query.filter_by(mrn=searchForm.mrn.data).first()
        if patient:
            if patient.has_disease in [True, False]:
                return redirect(url_for("invoice", id=patient.mrn))
            else:
                print("=" * 20, patient.mrn)
                print(patient.name)
                session["patient_id"] = searchForm.mrn.data
                filledForm = BreastForm(obj=patient)
                return render_template(
                    "breast.html", form=filledForm, searchForm=searchForm
                )
        else:
            flash("Patient does not exists", "danger")
            return redirect(url_for("breast"))

    if form.submit2.data and form.validate():

        patient = Patient.query.filter_by(mrn=session["patient_id"]).first()

        patient.breastImage = save_picture(form.picture.data)

        class_, confidence = breast_check(form.picture.data)
        image_class["class"] = class_
        image_class["confidence"] = confidence

        patient.breast_class = class_
        #patient.breast_confidence = round(int(confidence,2))
        patient.breast_confidence = confidence
        patient.has_disease = True
        patient.disease = "Breast"

        db.session.commit()
        return render_template(
            "breast.html", form=form, searchForm=searchForm, image_class=image_class
        )

    return render_template(
        "breast.html", searchForm=searchForm, title="", image_class=image_class
    )

这是我的 html 代码:

<div class="row">
        <div class="col-lg-12 pt">
            {% if form %}
            <form method="POST" action="" enctype="multipart/form-data">
                {{ form.hidden_tag() }}
                <div class="form-group">
                    {{ form.picture.label(class="custom-file-label", for="files", id="files", label="files") }}
                    {{ form.picture(class="file custom-file-input", type="file") }}
                    {% if form.picture.errors %}
                    {% for error in form.picture.errors %}
                    <span class="text-danger">{{ error }}</span></br>
                    {% endfor %}
                    {% endif %}
                </div>
                <div class="mt-4 text-center">
                    {{ form.submit2(class="btn btn-outline-info") }}
                </div>
            </form>
            {% endif %}
        </div>
    </div>

0 个答案:

没有答案