Request发送图片到flask客户端
request客户端
def getByte(path):
with open(path, 'rb') as f:
img_byte = base64.b64encode(f.read()) # 二进制读取后变base64编码
img_str = img_byte.decode('ascii') # 转成python的unicode
return img_str
#img转换
def http2Server():
img_str = getByte('screenshot.jpg')
requestsss = {'image': img_str}
req = json.dumps(requestsss) # 字典数据结构变json(所有程序语言都认识的字符串)
res = requests.post('http://172.0.0.1/POST', data=req)
requests.adapters.DEFAULT_RETRIES = 5
return res.text
flask服务端
@app.route("/POST", methods=['POST'])
def predict():
upload_file = request.get_data()#接收数据
req = json.loads(upload_file)
if upload_file:
img_str = req['image']
img_decode_ = img_str.encode('ascii')
img_decode = base64.b64decode(img_decode_)
img_np_ = np.frombuffer(img_decode, np.uint8)
img = cv2.imdecode(img_np_, cv2.COLOR_RGB2BGR)
cv2.imwrite('img.jpg',img) #cv保存到本地
python2json = test.run()#执行你想要对图片进行的操作
jsondata = json.dumps(python2json,ensure_ascii=False,indent=4)
return jsondata