result.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import cv2
  15. import copy
  16. import math
  17. from PIL import Image
  18. import matplotlib.pyplot as plt
  19. import numpy as np
  20. from ...common.result import BaseCVResult, JsonMixin
  21. def get_color(idx):
  22. idx = idx * 3
  23. color = ((37 * idx) % 255, (17 * idx) % 255, (29 * idx) % 255)
  24. return color
  25. def draw_keypoints(img, results, visual_thresh=0.1, ids=None):
  26. plt.switch_backend("agg")
  27. skeletons = results["keypoints"]
  28. skeletons = np.array(skeletons)
  29. if len(skeletons) > 0:
  30. kpt_nums = skeletons.shape[1]
  31. if kpt_nums == 17: # plot coco keypoint
  32. EDGES = [
  33. (0, 1),
  34. (0, 2),
  35. (1, 3),
  36. (2, 4),
  37. (3, 5),
  38. (4, 6),
  39. (5, 7),
  40. (6, 8),
  41. (7, 9),
  42. (8, 10),
  43. (5, 11),
  44. (6, 12),
  45. (11, 13),
  46. (12, 14),
  47. (13, 15),
  48. (14, 16),
  49. (11, 12),
  50. ]
  51. else: # plot mpii keypoint
  52. EDGES = [
  53. (0, 1),
  54. (1, 2),
  55. (3, 4),
  56. (4, 5),
  57. (2, 6),
  58. (3, 6),
  59. (6, 7),
  60. (7, 8),
  61. (8, 9),
  62. (10, 11),
  63. (11, 12),
  64. (13, 14),
  65. (14, 15),
  66. (8, 12),
  67. (8, 13),
  68. ]
  69. NUM_EDGES = len(EDGES)
  70. colors = [
  71. [255, 0, 0],
  72. [255, 85, 0],
  73. [255, 170, 0],
  74. [255, 255, 0],
  75. [170, 255, 0],
  76. [85, 255, 0],
  77. [0, 255, 0],
  78. [0, 255, 85],
  79. [0, 255, 170],
  80. [0, 255, 255],
  81. [0, 170, 255],
  82. [0, 85, 255],
  83. [0, 0, 255],
  84. [85, 0, 255],
  85. [170, 0, 255],
  86. [255, 0, 255],
  87. [255, 0, 170],
  88. [255, 0, 85],
  89. ]
  90. plt.figure()
  91. color_set = results["colors"] if "colors" in results else None
  92. if "bbox" in results and ids is None:
  93. bboxs = results["bbox"]
  94. for j, rect in enumerate(bboxs):
  95. xmin, ymin, xmax, ymax = rect
  96. color = (
  97. colors[0] if color_set is None else colors[color_set[j] % len(colors)]
  98. )
  99. cv2.rectangle(img, (xmin, ymin), (xmax, ymax), color, 1)
  100. canvas = img.copy()
  101. for i in range(kpt_nums):
  102. for j in range(len(skeletons)):
  103. if skeletons[j][i, 2] < visual_thresh:
  104. continue
  105. if ids is None:
  106. color = (
  107. colors[i]
  108. if color_set is None
  109. else colors[color_set[j] % len(colors)]
  110. )
  111. else:
  112. color = get_color(ids[j])
  113. cv2.circle(
  114. canvas,
  115. tuple(skeletons[j][i, 0:2].astype("int32")),
  116. 2,
  117. color,
  118. thickness=-1,
  119. )
  120. stickwidth = 1
  121. for i in range(NUM_EDGES):
  122. for j in range(len(skeletons)):
  123. edge = EDGES[i]
  124. if (
  125. skeletons[j][edge[0], 2] < visual_thresh
  126. or skeletons[j][edge[1], 2] < visual_thresh
  127. ):
  128. continue
  129. cur_canvas = canvas.copy()
  130. X = [skeletons[j][edge[0], 1], skeletons[j][edge[1], 1]]
  131. Y = [skeletons[j][edge[0], 0], skeletons[j][edge[1], 0]]
  132. mX = np.mean(X)
  133. mY = np.mean(Y)
  134. length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
  135. angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
  136. polygon = cv2.ellipse2Poly(
  137. (int(mY), int(mX)), (int(length / 2), stickwidth), int(angle), 0, 360, 1
  138. )
  139. if ids is None:
  140. color = (
  141. colors[i]
  142. if color_set is None
  143. else colors[color_set[j] % len(colors)]
  144. )
  145. else:
  146. color = get_color(ids[j])
  147. cv2.fillConvexPoly(cur_canvas, polygon, color)
  148. canvas = cv2.addWeighted(canvas, 0.4, cur_canvas, 0.6, 0)
  149. plt.close()
  150. return canvas
  151. class KptResult(BaseCVResult):
  152. """Save Result Transform"""
  153. def _to_img(self):
  154. """apply"""
  155. if "kpts" in self: # for single module result
  156. keypoints = [kpt["keypoints"] for kpt in self["kpts"]]
  157. else:
  158. keypoints = [
  159. obj["keypoints"] for obj in self["boxes"]
  160. ] # for top-down pipeline result
  161. image = self["input_img"]
  162. if keypoints:
  163. image = draw_keypoints(image, dict(keypoints=np.stack(keypoints)))
  164. image = Image.fromarray(image[..., ::-1])
  165. return {"res": image}
  166. def _to_str(self, *args, **kwargs):
  167. data = copy.deepcopy(self)
  168. data.pop("input_img")
  169. return JsonMixin._to_str(data, *args, **kwargs)
  170. def _to_json(self, *args, **kwargs):
  171. data = copy.deepcopy(self)
  172. data.pop("input_img")
  173. return JsonMixin._to_json(data, *args, **kwargs)