zoukankan      html  css  js  c++  java
  • 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))

    --

  • 相关阅读:
    多浏览器CSS样式解决方法
    CSS基础
    HTML页面——常用模块
    CSS选择器
    li水平与div水平
    天梯题目解答——1012、1430
    天梯题目解答——1205、1075、1083、1160
    HTML5 元素拖动
    div简单水平移动效果
    Matlab代码优化--向量化
  • 原文地址:https://www.cnblogs.com/Ph-one/p/11847588.html
Copyright © 2011-2022 走看看