首页 > 解决方案 > JSONDecodeError:期望值:Keras+Rest API 应用程序的第 1 行第 1 列(字符 0)

问题描述

我正在尝试从我的 keras 模型返回 HTTP 响应。

@app.route("/predict", methods=["POST"])
def predict():
    # initialize the data dictionary that will be returned from the
    # view
    data = {"success": False}

    # ensure an image was properly uploaded to our endpoint
    if flask.request.method == "POST":
        if flask.request.files.get("image"):
            # read the image in PIL format
            image = flask.request.files["image"].read()
            image = Image.open(io.BytesIO(image))

            # preprocess the image and prepare it for classification
            image = prepare_image(image, target=(224, 224))

            proba = model.predict(image)[0]
            idx = np.argmax(proba)
            label = lb.classes_[idx]
            r = {"label": label, "probability": float(proba[idx] * 100)}
            y = json.dumps(r)

    # return the data dictionary as a JSON response
    return y


if __name__ == "__main__":
    print(("* Loading Keras model and Flask starting server..."
        "please wait until server has fully started"))
    load_my_model()
    app.run()


import requests

# initialize the Keras REST API endpoint URL along with the input
# image path
KERAS_REST_API_URL = "http://localhost:5000/my_predict"
IMAGE_PATH = "dog.jpg"

# load the input image and construct the payload for the request
image = open(IMAGE_PATH, "rb").read()
payload = {"image": image}

# submit the request
r = requests.post(KERAS_REST_API_URL, files=payload).json()

# ensure the request was successful
if r["success"]:
    # loop over the predictions and display them
    for (i, result) in enumerate(r["predictions"]):
        print("{}. {}: {:.4f}".format(i + 1, result["label"],
            result["probability"]))

# otherwise, the request failed
else:
    print("Request failed”)

第一部分运行:

但下一部分给了我: JSONDecodeError: Expecting value: line 1 column 1 (char 0)

标签: jsonpython-3.xkerasjsondecoder

解决方案


You can take a look at this, an example on how to send an image over a post request, You don't need to send a json, just the image: import cv2

# prepare headers for http request
content_type = 'image/jpeg'
headers = {'content-type': content_type}

img = cv2.imread('lena.jpg')
# encode image as jpeg
_, img_encoded = cv2.imencode('.jpg', img)
# send http request with image and receive response
response = requests.post(url, data=img_encoded.tostring(), headers=headers)
# decode response
print(json.loads(response.text))

to decode the image on the flask server just:

import cv2

# convert string of image data to uint8
nparr = np.fromstring(flask.request.data, np.uint8)
# decode image
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

# do some fancy processing here....

推荐阅读