python使用post请求发送图片并接受图片

图像读取编码与反编码:

import requests
import json
import numpy as np
import cv2
import base64

# 首先将图片读入
# 由于要发送json,所以需要对byte进行str解码
def getByte(path):
    with open(path, 'rb') as f:
        img_byte = base64.b64encode(f.read())
    img_str = img_byte.decode('ascii')
    return img_str

img_str = getByte('../face_/sample/heyang.jpg')
# 此时可以测试解码得到图像并显示,服务器端也按照下面的方法还原图像继续进一步处理
img_decode_ = img_str.encode('ascii')  # ascii编码
img_decode = base64.b64decode(img_decode_)  # base64解码
img_np = np.frombuffer(img_decode, np.uint8)  # 从byte数据读取为np.array形式
img = cv2.imdecode(img_np, cv2.COLOR_RGB2BGR)  # 转为OpenCV形式

# 显示图像
cv2.imshow('img', img)
cv2.waitKey()
cv2.destroyAllWindows()

发送图片到服务器:

import requests
import json
import base64
import socket

# 首先将图片读入
# 由于要发送json,所以需要对byte进行str解码
def getByte(path):
    with open(path, 'rb') as f:
        img_byte = base64.b64encode(f.read())
    img_str = img_byte.decode('ascii')
    return img_str

img_str = getByte('../face_/sample/heyang.jpg')
# 此段为获得ip,本人使用本机服务器测试
def getIp():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip

url = 'http://' + str(getIp()) + ':9888/'
data = {'recognize_img':img_str, 'type':'0', 'useAntiSpoofing':'0'}
json_mod = json.dumps(data)
res = requests.post(url=url, data=json_mod)
print(res.text)
# 如果服务器没有报错,传回json格式数据
print(eval(res.text))

猜你喜欢

转载自blog.csdn.net/xiaotuzigaga/article/details/86622136
今日推荐