JSONDecodeError: Ожидаемое значение: строка 1, столбец 1 (символ 0) для приложения Keras + Rest API - PullRequest
1 голос
/ 19 февраля 2020

Я пытаюсь вернуть HTTP-ответ от моей модели keras.

@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”)

Первая часть запускается:

  • Загрузка модели Keras и Flask запуск сервера .. Пожалуйста, подождите, пока сервер полностью не запустится
    • Обслуживание Flask Приложение " main " (отложенная загрузка)
    • Среда: производство ПРЕДУПРЕЖДЕНИЕ: Это сервер разработки. Не используйте его в производственном развертывании. Вместо этого используйте рабочий сервер WSGI.
    • Режим отладки: выключен
    • Работает на http://127.0.0.1: 5000 /

Но следующая часть дает мне: JSONDecodeError: Ожидаемое значение: строка 1, столбец 1 (символ 0)

1 Ответ

0 голосов
/ 19 февраля 2020

Вы можете взглянуть на this , пример того, как отправить изображение по запросу, вам не нужно отправлять json, только изображение: 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))

для декодирования изображения на сервере flask просто:

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....
...