json - 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”)
第一部分运行:
- 加载 Keras 模型和 Flask 启动服务器...请等待服务器完全启动
- 服务 Flask 应用程序“ main ”(延迟加载)
- 环境:生产警告:这是一个开发服务器。不要在生产部署中使用它。请改用生产 WSGI 服务器。
- 调试模式:关闭
- 在http://127.0.0.1:5000/上运行
但下一部分给了我: JSONDecodeError: Expecting value: line 1 column 1 (char 0)
解决方案
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....
推荐阅读
- jquery - onClick hide/show after page refreshed
- c++ - Detailed explanation of transfer count members in IO_COUNTERS filled by GetProcessIoCounters
- express - Express + Axios - Pipe request to another server
- linux - Can you tell me what "crus" means in "LDFLAGS = crus $@"?
- python - My tkinter window isn't showing everything it should
- python - Discord.py 添加命令
- angular - Angular components not binding attributes after update from Angular 7 to Angular 10
- jupyter - Remove source code from notebook cell with Nbconvert 6.x
- c# - Change Navigation Bar Color for Single Page in Xamarin
- google-apps-script - 如何更改导入函数源电子表格