flask_start.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. # pip install flask -i https://pypi.tuna.tsinghua.edu.cn/simple
  2. # 用flask将程序包装成一个服务,并在服务器上启动
  3. import cv2
  4. import json
  5. import flask
  6. import base64
  7. import argparse
  8. import numpy as np
  9. # -------------------------------------------------------------------------------------------------------------------- #
  10. # 设置
  11. parser = argparse.ArgumentParser('|在服务器上启动flask服务|')
  12. # ...
  13. args, _ = parser.parse_known_args() # 防止传入参数冲突,替代args = parser.parse_args()
  14. app = flask.Flask(__name__) # 创建一个服务框架
  15. # -------------------------------------------------------------------------------------------------------------------- #
  16. # 程序
  17. def image_decode(image):
  18. image_base64 = image.encode() # base64
  19. image_byte = base64.b64decode(image_base64) # base64->字节类型
  20. array = np.frombuffer(image_byte, dtype=np.uint8) # 字节类型->一行数组
  21. image = cv2.imdecode(array, cv2.IMREAD_COLOR) # 一行数组->BGR图片
  22. return image
  23. @app.route('/test/', methods=['POST']) # 每当调用服务时会执行一次flask_app函数
  24. def flask_app():
  25. request_json = flask.request.get_data()
  26. request_dict = json.loads(request_json)
  27. image = image_decode(request_dict['image'])
  28. # ...
  29. result = image.shape
  30. return result
  31. if __name__ == '__main__':
  32. print('| 使用flask启动服务 |')
  33. app.run(host='0.0.0.0', port=9999, debug=False) # 启动服务