從客戶端推json到服務器端的工作可以用flask很容易做到,那么需要推送圖片的話可以先將圖片存到json中再進行操作。
服務器端
from flask import request, Flask
import json
import numpy as np
app = Flask(__name__)
@app.route("/frame", methods=['POST'])
def get_frame():
res = request.json # 獲取推過來的json,也可以用data然后轉換成json
# res = json.loads(request.data)
frame = eval(res["image"].decode("base64")) # dtype為int32
frame = np.array(frame, dtype=np.uint8)
cv2.imshow("frame", frame)
cv2.waitkey(0)
if __name__ == "__main__":
app.run("0.0.0.0", port=8081) #端口為8081
PS:關於request函數獲取的內容可以具體參考這里
客戶端
1. 將圖片存入json
import cv2
import json
img = cv2.imread("/your/image")
res = {"image": str(img.tolist()).encode('base64')} # img是ndarray,無法直接用base64編碼,否則會報錯
2. 推送json到服務器端
import requests
_ = requests.post("/your/server/url", json=res) # 比如這里/http://192.168.1.112:8081/frame
# _ = requests.post("/your/server/url", data=json.dumps(res)) # 如果服務器端獲取的方式為data
參考
- requests: http://docs.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests
- flask request: http://flask.pocoo.org/docs/0.12/quickstart/#the-request-object
- https://stackoverflow.com/questions/9746303/how-do-i-send-a-post-request-as-a-json
- https://stackoverflow.com/questions/27837346/how-to-include-pictures-bytes-to-a-json-with-python-encoding-issue
- https://stackoverflow.com/questions/20001229/how-to-get-posted-json-in-flask
- https://stackoverflow.com/questions/10434599/how-to-get-data-received-in-flask-request