keypoint_hrnet.py 9.5 KB

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