pyton3+urllib.request+json.dumps

client.py
#! -*- coding: utf-8 -*-
from urllib import request
import base64
import json

IMAGE_PATH = "test.png"
HOST = "http://127.0.0.1:5000/"


def base64_encode_image(a):
    return base64.b64encode(a).decode("utf-8")


def main():
    image = open(IMAGE_PATH, "rb").read()
    image = base64_encode_image(image)
    data = {"image": image}
    data = json.dumps(data)
    req = request.Request(HOST + "server", headers={"Content-Type": "application/json"})
    # bytes(data, encoding="utf-8")
    res = request.urlopen(req, data=bytes(data, encoding="utf-8"))
    result = res.read()
    print(result)


if __name__ == '__main__':
    main()

Server.py
#! -*- coding: utf-8 -*-
from tensorflow import keras as k
from PIL import Image
import numpy as np
import base64
import flask
import json
import sys
import io

MODEL_PATH = "../../experiments/imagecontact/inception_resnet_v2/checkpoints/weights.03-0.33.hdf5"

# load model
print("* Loading model ...")
model = k.models.load_model(MODEL_PATH)
#         
# ValueError: Tensor Tensor("outputs/Softmax:0", shape=(?, 2), dtype=float32) is not an element of this graph.
#      
model._make_predict_function()
print("* Model loaded.")


def prepare_image(image, target):
    if image.mode != "RGB":
        image = image.convert("RGB")
    image = image.resize(target)
    image = np.asarray(image, "float32")
    image = np.expand_dims(image, axis=0)
    return image


def base64_decode_image(a):
    if sys.version_info.major == 3:
        a = bytes(a, encoding="utf-8")
    return base64.b64decode(a)


app = flask.Flask(__name__)


@app.route("/predict", methods=["POST"])
def predict():
    data = {"success": False}
    if flask.request.method == "POST":
        if flask.request.files.get("image"):
            image = flask.request.files["image"].read()
            image = Image.open(io.BytesIO(image))
            image = prepare_image(image, (224, 224))
            print("* inputs shape:", image.shape)
            outputs = model.predict(image)
            preds = np.argmax(outputs, axis=1)
            results = []
            for (pred, output) in zip(preds, outputs):
                r = {"pred": pred, "score": output[pred]}
                print(r)
                results.append(r)
            data["results"] = results
        else:
            data["err_msg"] = "Get none."
    else:
        data["err_msg"] = "Not support GET method."
    return flask.jsonify(data)


@app.route("/server", methods=["POST"])
def server():
    data = {"success": False}
    if flask.request.method == "POST":
        if flask.request.get_data():
            post_data = flask.request.get_data()
            post_data = json.loads(post_data)
            image = post_data["image"]
            image = base64_decode_image(image)
            image = Image.open(io.BytesIO(image))
            image = prepare_image(image, (224, 224))

            print("* inputs shape:", image.shape)
            outputs = model.predict(image)

            preds = np.argmax(outputs, axis=1)
            results = []
            for (pred, output) in zip(preds, outputs):
                r = {"pred": int(pred), "score": float(output[pred])}
                # json does not recognize NumPy data types. 
                # Convert the number to a Python int before serializing the object
                # r = {"pred": pred, "score": output[pred]}
                print(r)
                results.append(r)
            data["results"] = results
        else:
            data["err_msg"] = "Get none."
    else:
        data["err_msg"] = "Not support GET method."
    return json.dumps(data)


if __name__ == '__main__':
    app.run()


운행 하 다.
  • 이용 http://127.0.0.1:5000/server 서비스
  • python client.py
    
  • 이용 http://127.0.0.1:5000/predict 서비스
  • curl -X POST -F [email protected] 'http://localhost:5000/predict'
    

    교류 학습 을 환영 합 니 다.
    在这里插入图片描述 pyton3+urllib.request+json.dumps_第1张图片

    좋은 웹페이지 즐겨찾기