• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

python Http服务,传输base64图片

武飞扬头像
qq_21331593
帮助1

使用flask可以制作自己的http服务,前端post发送request访问请求,同过base64编码图片传输至服务器端进行处理:图像检测识别等。

图像base64编码解码代码:

  1.  
    import base64
  2.  
    ###np 图片编码成base64形式
  3.  
    def image_to_base64(image_mat):
  4.  
    image = cv2.imencode('.jpg', image_mat)[1]
  5.  
    image_code = str(base64.b64encode(image), 'utf-8')
  6.  
    return image_code
  7.  
    ###base64图片解码成numpy图
  8.  
    def base64_to_image(imgBase64):
  9.  
    img_data = base64.b64decode(imgBase64)
  10.  
    bs = np.asarray(bytearray(img_data), dtype='uint8')
  11.  
    img = cv2.imdecode(bs, cv2.IMREAD_COLOR)
  12.  
    return img

Http服务端代码:

  1.  
    from tqdm import tqdm
  2.  
    import requests
  3.  
    import sys
  4.  
    import base64
  5.  
    import numpy as np
  6.  
    import cv2,os
  7.  
    from flask import Flask, request
  8.  
    import argparse
  9.  
    import json
  10.  
     
  11.  
    app = Flask(__name__)
  12.  
     
  13.  
     
  14.  
    class RestHelper(object):
  15.  
    def __init__(self, data, id):
  16.  
    self.data = data
  17.  
    self.id = id
  18.  
    def toJson(self):
  19.  
    return {'status': '1', 'data': self.data, 'taskId':self.id}
  20.  
    def failure(self):
  21.  
    return {'status': '0','data': self.data, 'taskId':self.id}
  22.  
    def error(self):
  23.  
    return {'status': '0','data': self.data, 'taskId':self.id}
  24.  
     
  25.  
    class dataEnconding(json.JSONEncoder):
  26.  
    def default(self, o):
  27.  
    #if isnumber(o):
  28.  
    # return str(o)
  29.  
    if isinstance(o, float):
  30.  
    return str(float(o))
  31.  
    if isinstance(o, int):
  32.  
    return str(o)
  33.  
     
  34.  
    def proc(img):
  35.  
    pass
  36.  
     
  37.  
    @app.route('/my_service', methods=["POST"])
  38.  
    def my_service():
  39.  
    print("------------my_service start----------------")
  40.  
    data = request.json
  41.  
    ####接收到的信息
  42.  
    print("Request dict data key is: \n", data.keys(), type(data))
  43.  
    img = data["base64Img"]
  44.  
    ##process img now-----
  45.  
    proc(img)
  46.  
    ###process down
  47.  
    taskId=data["taskId"]
  48.  
    ##服务返回结果信息------
  49.  
    q = RestHelper({"respose": "hello world!"}, id=taskId).toJson()
  50.  
    return json.dumps(q, cls=dataEnconding)
  51.  
     
  52.  
    def parse_args():
  53.  
    parser = argparse.ArgumentParser(description='start service')
  54.  
    parser.add_argument('--port', '-p', default='4444', help='port')
  55.  
    parser.add_argument('--config', '-c', default='./iniFile/ini.cfg', help='rabbitMQ info')
  56.  
    args = parser.parse_args()
  57.  
    return args
  58.  
     
  59.  
    if __name__ == '__main__':
  60.  
    args = parse_args()
  61.  
    port = args.port
  62.  
    print(port)
  63.  
    app.run(debug=False, host='0.0.0.0', port=port, threaded=False, processes=8)
学新通

发送访问请求:

  1.  
    from urllib import request, parse
  2.  
    import requests
  3.  
    import base64
  4.  
    import json
  5.  
    from urllib.request import urlretrieve
  6.  
    import os
  7.  
    import cv2
  8.  
    import base64
  9.  
    import numpy as np
  10.  
    import time
  11.  
     
  12.  
     
  13.  
    def image_to_base64(image_mat):
  14.  
    image = cv2.imencode('.jpg', image_mat)[1]
  15.  
    image_code = str(base64.b64encode(image), 'utf-8')
  16.  
    return image_code
  17.  
     
  18.  
    if __name__ == '__main__':
  19.  
    url = "http://127.0.0.1:4444/my_service"
  20.  
     
  21.  
    testImgp = "imgs/1.jpg"
  22.  
    img = cv2,imread(testImgp)
  23.  
    headers = {'content-type': "application/json"}
  24.  
     
  25.  
    data = {
  26.  
    "taskId": 10086,
  27.  
    "base64Img":image_to_base64(img )
  28.  
    }
  29.  
     
  30.  
    response = requests.post(url, json=json.loads(json.dumps(data)), headers=headers)
  31.  
    if response:
  32.  
    result = json.loads(str(response.content, 'utf-8'))
  33.  
    print(result)
学新通

也可以从headers中传入某些key value,在服务端使用request.headers.get(yourKEY)获取到

比如发送头

headers = {'content-type': "application/json", "taskId": taskId}

接受时候采用下面get key形式获取到值:

ID = str(request.headers.get('taskId'))

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgfhjbf
系列文章
更多 icon
同类精品
更多 icon
继续加载