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))

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值