image.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. import os
  2. from flask import request, logging, send_file, jsonify
  3. from app import app
  4. from .resp import success_resp, error_resp
  5. import numpy as np
  6. from .req import ReplaceForm, is_empty
  7. import tools
  8. import cv2
  9. from .file import get_upload_file_path, get_output_dir, file_url, get_output_file_path, get_file_id
  10. log = logging.create_logger(app)
  11. @app.route("/image/seg", methods=['POST'])
  12. def seg():
  13. if 'fileId' not in request.values:
  14. return "请先上传图片!", 500
  15. file_id = request.values.get('fileId')
  16. file_path = get_upload_file_path(file_id)
  17. _, fg, _, path = tools.seg(file_path, get_output_dir())
  18. # filename = os.path.relpath(path, OUTPUT_DIR)
  19. return jsonify(success_resp({
  20. "fileId": file_id,
  21. "url": file_url(path, True)
  22. }))
  23. @app.route("/image/replace", methods=["POST"])
  24. def replace():
  25. form_data = request.form
  26. form = ReplaceForm(form_data)
  27. if form.validate() is False:
  28. return jsonify(error_resp("参数错误!"))
  29. if is_empty(form.bg_file_id.data) and is_empty(form.background.data):
  30. return jsonify(error_resp("请选择需要替换的背景!"))
  31. img_path = get_upload_file_path(form.file_id.data)
  32. bg_path = form.background.data
  33. if is_empty(form.bg_file_id.data) is False:
  34. bg_path = get_upload_file_path(form.bg_file_id.data)
  35. if os.path.exists(bg_path):
  36. bg_path = form.background.data
  37. result = tools.replace(img_path=img_path, background=bg_path, save_dir=get_output_dir())
  38. return jsonify({
  39. "fileId": get_file_id(result, True),
  40. "url": file_url(result, True)
  41. })
  42. @app.route("/image/resize", methods=["POST", 'GET'])
  43. def resize():
  44. # flip: 翻转, 0 为沿X轴翻转,正数为沿Y轴翻转,负数为同时沿X轴和Y轴翻转
  45. # reset: 是否重头开始,否则从上一次的处理开始,默认为重头开始
  46. # resize: 重新设定尺寸
  47. # rect: 裁剪,left,top,right,bottom 四个参数
  48. reset = request.values.get("reset")
  49. file_id = request.values.get("fileId")
  50. width = request.values.get("width")
  51. height = request.values.get("height")
  52. rotate = request.values.get("rotate")
  53. flip = request.values.get("flip")
  54. rect = request.values.get('rect')
  55. if is_empty(reset):
  56. reset = True
  57. else:
  58. reset = False
  59. file_path = get_upload_file_path(file_id)
  60. is_get = request.method.upper() == "GET"
  61. if os.path.exists(file_path) is not True:
  62. return "文件上传失败,请重新上传!" if is_get else jsonify(error_resp("文件上传失败,请重新上传")), 400
  63. out_file = get_output_file_path(file_id, "resize")
  64. if reset is False and os.path.exists(out_file):
  65. img = cv2.imread(out_file)
  66. else:
  67. img = cv2.imread(file_path)
  68. origin_h = img.shape[0]
  69. origin_w = img.shape[1]
  70. img = crop(img, rect, origin_w, origin_h)
  71. change_size = True
  72. if is_empty(width) and is_empty(height):
  73. change_size = False
  74. w = origin_w
  75. h = origin_h
  76. elif is_empty(width):
  77. h = int(height)
  78. w = round(h * origin_w / origin_h)
  79. elif is_empty(height):
  80. w = int(width)
  81. h = round(w * origin_h / origin_w)
  82. else:
  83. w = int(width)
  84. h = int(height)
  85. dst = img
  86. if change_size:
  87. dst = cv2.resize(img, (w, h))
  88. if is_empty(flip) is not True:
  89. flip = int(flip)
  90. dst = cv2.flip(dst, flip)
  91. if is_empty(rotate) is False:
  92. dst = rot_degree(dst, float(rotate), w=w, h=h)
  93. if dst is not None:
  94. cv2.imwrite(out_file, dst)
  95. if is_get:
  96. return send_file(out_file, mimetype="image/png")
  97. else:
  98. return jsonify(success_resp({
  99. "fileId": get_file_id(out_file),
  100. "url": file_url(out_file)
  101. }))
  102. if is_get:
  103. return send_file(file_path, mimetype="image/png")
  104. return jsonify(success_resp({
  105. "fileId": get_file_id(file_path),
  106. "url": file_url(file_path)
  107. }))
  108. def crop(img, rect: str, w, h):
  109. # 裁剪
  110. if is_empty(rect):
  111. return img
  112. r = rect.split(',')
  113. if len(r) != 4:
  114. return img
  115. left = int(r[0])
  116. top = int(r[1])
  117. right = int(r[2])
  118. bottom = int(r[3])
  119. if left < 0:
  120. left = 0
  121. if right > w:
  122. right = w
  123. if top < 0:
  124. top = 0
  125. if bottom > h:
  126. bottom = h
  127. if left == 0 and top == 0 and right == w and bottom == h:
  128. return img
  129. return img[top:bottom, left:right]
  130. def rot_degree(img, degree, w, h):
  131. center = (w / 2, h / 2)
  132. M = cv2.getRotationMatrix2D(center, degree, 1)
  133. top_right = np.array((w - 1, 0)) - np.array(center)
  134. bottom_right = np.array((w - 1, h - 1)) - np.array(center)
  135. top_right_after_rot = M[0:2, 0:2].dot(top_right)
  136. bottom_right_after_rot = M[0:2, 0:2].dot(bottom_right)
  137. new_width = max(int(abs(bottom_right_after_rot[0] * 2) + 0.5), int(abs(top_right_after_rot[0] * 2) + 0.5))
  138. new_height = max(int(abs(top_right_after_rot[1] * 2) + 0.5), int(abs(bottom_right_after_rot[1] * 2) + 0.5))
  139. offset_x = (new_width - w) / 2
  140. offset_y = (new_height - h) / 2
  141. M[0, 2] += offset_x
  142. M[1, 2] += offset_y
  143. dst = cv2.warpAffine(img, M, (new_width, new_height))
  144. return dst