result.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. import matplotlib.pyplot as plt
  18. import numpy as np
  19. from ...common.result import BaseCVResult, StrMixin, JsonMixin
  20. def get_color(idx):
  21. idx = idx * 3
  22. color = ((37 * idx) % 255, (17 * idx) % 255, (29 * idx) % 255)
  23. return color
  24. def draw_keypoints(img, results, visual_thresh=0.1, ids=None):
  25. plt.switch_backend("agg")
  26. skeletons = results["keypoints"]
  27. skeletons = np.array(skeletons)
  28. if len(skeletons) > 0:
  29. kpt_nums = skeletons.shape[1]
  30. if kpt_nums == 17: # plot coco keypoint
  31. EDGES = [
  32. (0, 1),
  33. (0, 2),
  34. (1, 3),
  35. (2, 4),
  36. (3, 5),
  37. (4, 6),
  38. (5, 7),
  39. (6, 8),
  40. (7, 9),
  41. (8, 10),
  42. (5, 11),
  43. (6, 12),
  44. (11, 13),
  45. (12, 14),
  46. (13, 15),
  47. (14, 16),
  48. (11, 12),
  49. ]
  50. else: # plot mpii keypoint
  51. EDGES = [
  52. (0, 1),
  53. (1, 2),
  54. (3, 4),
  55. (4, 5),
  56. (2, 6),
  57. (3, 6),
  58. (6, 7),
  59. (7, 8),
  60. (8, 9),
  61. (10, 11),
  62. (11, 12),
  63. (13, 14),
  64. (14, 15),
  65. (8, 12),
  66. (8, 13),
  67. ]
  68. NUM_EDGES = len(EDGES)
  69. colors = [
  70. [255, 0, 0],
  71. [255, 85, 0],
  72. [255, 170, 0],
  73. [255, 255, 0],
  74. [170, 255, 0],
  75. [85, 255, 0],
  76. [0, 255, 0],
  77. [0, 255, 85],
  78. [0, 255, 170],
  79. [0, 255, 255],
  80. [0, 170, 255],
  81. [0, 85, 255],
  82. [0, 0, 255],
  83. [85, 0, 255],
  84. [170, 0, 255],
  85. [255, 0, 255],
  86. [255, 0, 170],
  87. [255, 0, 85],
  88. ]
  89. plt.figure()
  90. color_set = results["colors"] if "colors" in results else None
  91. if "bbox" in results and ids is None:
  92. bboxs = results["bbox"]
  93. for j, rect in enumerate(bboxs):
  94. xmin, ymin, xmax, ymax = rect
  95. color = (
  96. colors[0] if color_set is None else colors[color_set[j] % len(colors)]
  97. )
  98. cv2.rectangle(img, (xmin, ymin), (xmax, ymax), color, 1)
  99. canvas = img.copy()
  100. for i in range(kpt_nums):
  101. for j in range(len(skeletons)):
  102. if skeletons[j][i, 2] < visual_thresh:
  103. continue
  104. if ids is None:
  105. color = (
  106. colors[i]
  107. if color_set is None
  108. else colors[color_set[j] % len(colors)]
  109. )
  110. else:
  111. color = get_color(ids[j])
  112. cv2.circle(
  113. canvas,
  114. tuple(skeletons[j][i, 0:2].astype("int32")),
  115. 2,
  116. color,
  117. thickness=-1,
  118. )
  119. stickwidth = 1
  120. for i in range(NUM_EDGES):
  121. for j in range(len(skeletons)):
  122. edge = EDGES[i]
  123. if (
  124. skeletons[j][edge[0], 2] < visual_thresh
  125. or skeletons[j][edge[1], 2] < visual_thresh
  126. ):
  127. continue
  128. cur_canvas = canvas.copy()
  129. X = [skeletons[j][edge[0], 1], skeletons[j][edge[1], 1]]
  130. Y = [skeletons[j][edge[0], 0], skeletons[j][edge[1], 0]]
  131. mX = np.mean(X)
  132. mY = np.mean(Y)
  133. length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
  134. angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
  135. polygon = cv2.ellipse2Poly(
  136. (int(mY), int(mX)), (int(length / 2), stickwidth), int(angle), 0, 360, 1
  137. )
  138. if ids is None:
  139. color = (
  140. colors[i]
  141. if color_set is None
  142. else colors[color_set[j] % len(colors)]
  143. )
  144. else:
  145. color = get_color(ids[j])
  146. cv2.fillConvexPoly(cur_canvas, polygon, color)
  147. canvas = cv2.addWeighted(canvas, 0.4, cur_canvas, 0.6, 0)
  148. plt.close()
  149. return canvas
  150. class KptResult(BaseCVResult):
  151. """Save Result Transform"""
  152. def _to_img(self):
  153. """apply"""
  154. if "kpts" in self: # for single module result
  155. keypoints = [kpt["keypoints"] for kpt in self["kpts"]]
  156. else:
  157. keypoints = [
  158. obj["keypoints"] for obj in self["boxes"]
  159. ] # for top-down pipeline result
  160. image = draw_keypoints(self["input_img"], dict(keypoints=np.stack(keypoints)))
  161. return {"res": image}
  162. def _to_str(self, *args, **kwargs):
  163. data = copy.deepcopy(self)
  164. return StrMixin._to_str(data, *args, **kwargs)
  165. def _to_json(self, *args, **kwargs):
  166. data = copy.deepcopy(self)
  167. data.pop("input_img")
  168. return JsonMixin._to_json(data, *args, **kwargs)