keypoint_hrnet.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import paddle
  18. import numpy as np
  19. import math
  20. import cv2
  21. from ppdet.core.workspace import register, create
  22. from .meta_arch import BaseArch
  23. from ..keypoint_utils import transform_preds
  24. from .. import layers as L
  25. __all__ = ['TopDownHRNet']
  26. @register
  27. class TopDownHRNet(BaseArch):
  28. __category__ = 'architecture'
  29. __inject__ = ['loss']
  30. def __init__(self,
  31. width,
  32. num_joints,
  33. backbone='HRNet',
  34. loss='KeyPointMSELoss',
  35. post_process='HRNetPostProcess',
  36. flip_perm=None,
  37. flip=True,
  38. shift_heatmap=True,
  39. use_dark=True):
  40. """
  41. HRNet network, see https://arxiv.org/abs/1902.09212
  42. Args:
  43. backbone (nn.Layer): backbone instance
  44. post_process (object): `HRNetPostProcess` instance
  45. flip_perm (list): The left-right joints exchange order list
  46. use_dark(bool): Whether to use DARK in post processing
  47. """
  48. super(TopDownHRNet, self).__init__()
  49. self.backbone = backbone
  50. self.post_process = HRNetPostProcess(use_dark)
  51. self.loss = loss
  52. self.flip_perm = flip_perm
  53. self.flip = flip
  54. self.final_conv = L.Conv2d(width, num_joints, 1, 1, 0, bias=True)
  55. self.shift_heatmap = shift_heatmap
  56. self.deploy = False
  57. @classmethod
  58. def from_config(cls, cfg, *args, **kwargs):
  59. # backbone
  60. backbone = create(cfg['backbone'])
  61. return {'backbone': backbone, }
  62. def _forward(self):
  63. feats = self.backbone(self.inputs)
  64. hrnet_outputs = self.final_conv(feats[0])
  65. if self.training:
  66. return self.loss(hrnet_outputs, self.inputs)
  67. elif self.deploy:
  68. outshape = hrnet_outputs.shape
  69. max_idx = paddle.argmax(
  70. hrnet_outputs.reshape(
  71. (outshape[0], outshape[1], outshape[2] * outshape[3])),
  72. axis=-1)
  73. return hrnet_outputs, max_idx
  74. else:
  75. if self.flip:
  76. self.inputs['image'] = self.inputs['image'].flip([3])
  77. feats = self.backbone(self.inputs)
  78. output_flipped = self.final_conv(feats[0])
  79. output_flipped = self.flip_back(output_flipped.numpy(),
  80. self.flip_perm)
  81. output_flipped = paddle.to_tensor(output_flipped.copy())
  82. if self.shift_heatmap:
  83. output_flipped[:, :, :, 1:] = output_flipped.clone(
  84. )[:, :, :, 0:-1]
  85. hrnet_outputs = (hrnet_outputs + output_flipped) * 0.5
  86. imshape = (self.inputs['im_shape'].numpy()
  87. )[:, ::-1] if 'im_shape' in self.inputs else None
  88. center = self.inputs['center'].numpy(
  89. ) if 'center' in self.inputs else np.round(imshape / 2.)
  90. scale = self.inputs['scale'].numpy(
  91. ) if 'scale' in self.inputs else imshape / 200.
  92. outputs = self.post_process(hrnet_outputs, center, scale)
  93. return outputs
  94. def get_loss(self):
  95. return self._forward()
  96. def get_pred(self):
  97. res_lst = self._forward()
  98. outputs = {'keypoint': res_lst}
  99. return outputs
  100. def flip_back(self, output_flipped, matched_parts):
  101. assert output_flipped.ndim == 4,\
  102. 'output_flipped should be [batch_size, num_joints, height, width]'
  103. output_flipped = output_flipped[:, :, :, ::-1]
  104. for pair in matched_parts:
  105. tmp = output_flipped[:, pair[0], :, :].copy()
  106. output_flipped[:, pair[0], :, :] = output_flipped[:, pair[1], :, :]
  107. output_flipped[:, pair[1], :, :] = tmp
  108. return output_flipped
  109. class HRNetPostProcess(object):
  110. def __init__(self, use_dark=True):
  111. self.use_dark = use_dark
  112. def get_max_preds(self, heatmaps):
  113. '''get predictions from score maps
  114. Args:
  115. heatmaps: numpy.ndarray([batch_size, num_joints, height, width])
  116. Returns:
  117. preds: numpy.ndarray([batch_size, num_joints, 2]), keypoints coords
  118. maxvals: numpy.ndarray([batch_size, num_joints, 2]), the maximum confidence of the keypoints
  119. '''
  120. assert isinstance(heatmaps,
  121. np.ndarray), 'heatmaps should be numpy.ndarray'
  122. assert heatmaps.ndim == 4, 'batch_images should be 4-ndim'
  123. batch_size = heatmaps.shape[0]
  124. num_joints = heatmaps.shape[1]
  125. width = heatmaps.shape[3]
  126. heatmaps_reshaped = heatmaps.reshape((batch_size, num_joints, -1))
  127. idx = np.argmax(heatmaps_reshaped, 2)
  128. maxvals = np.amax(heatmaps_reshaped, 2)
  129. maxvals = maxvals.reshape((batch_size, num_joints, 1))
  130. idx = idx.reshape((batch_size, num_joints, 1))
  131. preds = np.tile(idx, (1, 1, 2)).astype(np.float32)
  132. preds[:, :, 0] = (preds[:, :, 0]) % width
  133. preds[:, :, 1] = np.floor((preds[:, :, 1]) / width)
  134. pred_mask = np.tile(np.greater(maxvals, 0.0), (1, 1, 2))
  135. pred_mask = pred_mask.astype(np.float32)
  136. preds *= pred_mask
  137. return preds, maxvals
  138. def gaussian_blur(self, heatmap, kernel):
  139. border = (kernel - 1) // 2
  140. batch_size = heatmap.shape[0]
  141. num_joints = heatmap.shape[1]
  142. height = heatmap.shape[2]
  143. width = heatmap.shape[3]
  144. for i in range(batch_size):
  145. for j in range(num_joints):
  146. origin_max = np.max(heatmap[i, j])
  147. dr = np.zeros((height + 2 * border, width + 2 * border))
  148. dr[border:-border, border:-border] = heatmap[i, j].copy()
  149. dr = cv2.GaussianBlur(dr, (kernel, kernel), 0)
  150. heatmap[i, j] = dr[border:-border, border:-border].copy()
  151. heatmap[i, j] *= origin_max / np.max(heatmap[i, j])
  152. return heatmap
  153. def dark_parse(self, hm, coord):
  154. heatmap_height = hm.shape[0]
  155. heatmap_width = hm.shape[1]
  156. px = int(coord[0])
  157. py = int(coord[1])
  158. if 1 < px < heatmap_width - 2 and 1 < py < heatmap_height - 2:
  159. dx = 0.5 * (hm[py][px + 1] - hm[py][px - 1])
  160. dy = 0.5 * (hm[py + 1][px] - hm[py - 1][px])
  161. dxx = 0.25 * (hm[py][px + 2] - 2 * hm[py][px] + hm[py][px - 2])
  162. dxy = 0.25 * (hm[py+1][px+1] - hm[py-1][px+1] - hm[py+1][px-1] \
  163. + hm[py-1][px-1])
  164. dyy = 0.25 * (
  165. hm[py + 2 * 1][px] - 2 * hm[py][px] + hm[py - 2 * 1][px])
  166. derivative = np.matrix([[dx], [dy]])
  167. hessian = np.matrix([[dxx, dxy], [dxy, dyy]])
  168. if dxx * dyy - dxy**2 != 0:
  169. hessianinv = hessian.I
  170. offset = -hessianinv * derivative
  171. offset = np.squeeze(np.array(offset.T), axis=0)
  172. coord += offset
  173. return coord
  174. def dark_postprocess(self, hm, coords, kernelsize):
  175. '''DARK postpocessing, Zhang et al. Distribution-Aware Coordinate
  176. Representation for Human Pose Estimation (CVPR 2020).
  177. '''
  178. hm = self.gaussian_blur(hm, kernelsize)
  179. hm = np.maximum(hm, 1e-10)
  180. hm = np.log(hm)
  181. for n in range(coords.shape[0]):
  182. for p in range(coords.shape[1]):
  183. coords[n, p] = self.dark_parse(hm[n][p], coords[n][p])
  184. return coords
  185. def get_final_preds(self, heatmaps, center, scale, kernelsize=3):
  186. """the highest heatvalue location with a quarter offset in the
  187. direction from the highest response to the second highest response.
  188. Args:
  189. heatmaps (numpy.ndarray): The predicted heatmaps
  190. center (numpy.ndarray): The boxes center
  191. scale (numpy.ndarray): The scale factor
  192. Returns:
  193. preds: numpy.ndarray([batch_size, num_joints, 2]), keypoints coords
  194. maxvals: numpy.ndarray([batch_size, num_joints, 1]), the maximum confidence of the keypoints
  195. """
  196. coords, maxvals = self.get_max_preds(heatmaps)
  197. heatmap_height = heatmaps.shape[2]
  198. heatmap_width = heatmaps.shape[3]
  199. if self.use_dark:
  200. coords = self.dark_postprocess(heatmaps, coords, kernelsize)
  201. else:
  202. for n in range(coords.shape[0]):
  203. for p in range(coords.shape[1]):
  204. hm = heatmaps[n][p]
  205. px = int(math.floor(coords[n][p][0] + 0.5))
  206. py = int(math.floor(coords[n][p][1] + 0.5))
  207. if 1 < px < heatmap_width - 1 and 1 < py < heatmap_height - 1:
  208. diff = np.array([
  209. hm[py][px + 1] - hm[py][px - 1],
  210. hm[py + 1][px] - hm[py - 1][px]
  211. ])
  212. coords[n][p] += np.sign(diff) * .25
  213. preds = coords.copy()
  214. # Transform back
  215. for i in range(coords.shape[0]):
  216. preds[i] = transform_preds(coords[i], center[i], scale[i],
  217. [heatmap_width, heatmap_height])
  218. return preds, maxvals
  219. def __call__(self, output, center, scale):
  220. preds, maxvals = self.get_final_preds(output.numpy(), center, scale)
  221. outputs = [[
  222. np.concatenate(
  223. (preds, maxvals), axis=-1), np.mean(
  224. maxvals, axis=1)
  225. ]]
  226. return outputs