postprocess_ops.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. import cv2
  2. import math
  3. import numpy as np
  4. from preprocess_ops import get_affine_transform
  5. class HRNetPostProcess(object):
  6. def __init__(self, use_dark=True):
  7. self.use_dark = use_dark
  8. def flip_back(self, output_flipped, matched_parts):
  9. assert output_flipped.ndim == 4,\
  10. 'output_flipped should be [batch_size, num_joints, height, width]'
  11. output_flipped = output_flipped[:, :, :, ::-1]
  12. for pair in matched_parts:
  13. tmp = output_flipped[:, pair[0], :, :].copy()
  14. output_flipped[:, pair[0], :, :] = output_flipped[:, pair[1], :, :]
  15. output_flipped[:, pair[1], :, :] = tmp
  16. return output_flipped
  17. def get_max_preds(self, heatmaps):
  18. """get predictions from score maps
  19. Args:
  20. heatmaps: numpy.ndarray([batch_size, num_joints, height, width])
  21. Returns:
  22. preds: numpy.ndarray([batch_size, num_joints, 2]), keypoints coords
  23. maxvals: numpy.ndarray([batch_size, num_joints, 2]), the maximum confidence of the keypoints
  24. """
  25. assert isinstance(heatmaps,
  26. np.ndarray), 'heatmaps should be numpy.ndarray'
  27. assert heatmaps.ndim == 4, 'batch_images should be 4-ndim'
  28. batch_size = heatmaps.shape[0]
  29. num_joints = heatmaps.shape[1]
  30. width = heatmaps.shape[3]
  31. heatmaps_reshaped = heatmaps.reshape((batch_size, num_joints, -1))
  32. idx = np.argmax(heatmaps_reshaped, 2)
  33. maxvals = np.amax(heatmaps_reshaped, 2)
  34. maxvals = maxvals.reshape((batch_size, num_joints, 1))
  35. idx = idx.reshape((batch_size, num_joints, 1))
  36. preds = np.tile(idx, (1, 1, 2)).astype(np.float32)
  37. preds[:, :, 0] = (preds[:, :, 0]) % width
  38. preds[:, :, 1] = np.floor((preds[:, :, 1]) / width)
  39. pred_mask = np.tile(np.greater(maxvals, 0.0), (1, 1, 2))
  40. pred_mask = pred_mask.astype(np.float32)
  41. preds *= pred_mask
  42. return preds, maxvals
  43. def gaussian_blur(self, heatmap, kernel):
  44. border = (kernel - 1) // 2
  45. batch_size = heatmap.shape[0]
  46. num_joints = heatmap.shape[1]
  47. height = heatmap.shape[2]
  48. width = heatmap.shape[3]
  49. for i in range(batch_size):
  50. for j in range(num_joints):
  51. origin_max = np.max(heatmap[i, j])
  52. dr = np.zeros((height + 2 * border, width + 2 * border))
  53. dr[border:-border, border:-border] = heatmap[i, j].copy()
  54. dr = cv2.GaussianBlur(dr, (kernel, kernel), 0)
  55. heatmap[i, j] = dr[border:-border, border:-border].copy()
  56. heatmap[i, j] *= origin_max / np.max(heatmap[i, j])
  57. return heatmap
  58. def dark_parse(self, hm, coord):
  59. heatmap_height = hm.shape[0]
  60. heatmap_width = hm.shape[1]
  61. px = int(coord[0])
  62. py = int(coord[1])
  63. if 1 < px < heatmap_width - 2 and 1 < py < heatmap_height - 2:
  64. dx = 0.5 * (hm[py][px + 1] - hm[py][px - 1])
  65. dy = 0.5 * (hm[py + 1][px] - hm[py - 1][px])
  66. dxx = 0.25 * (hm[py][px + 2] - 2 * hm[py][px] + hm[py][px - 2])
  67. dxy = 0.25 * (hm[py+1][px+1] - hm[py-1][px+1] - hm[py+1][px-1] \
  68. + hm[py-1][px-1])
  69. dyy = 0.25 * (
  70. hm[py + 2 * 1][px] - 2 * hm[py][px] + hm[py - 2 * 1][px])
  71. derivative = np.matrix([[dx], [dy]])
  72. hessian = np.matrix([[dxx, dxy], [dxy, dyy]])
  73. if dxx * dyy - dxy**2 != 0:
  74. hessianinv = hessian.I
  75. offset = -hessianinv * derivative
  76. offset = np.squeeze(np.array(offset.T), axis=0)
  77. coord += offset
  78. return coord
  79. def dark_postprocess(self, hm, coords, kernelsize):
  80. """
  81. refer to https://github.com/ilovepose/DarkPose/lib/core/inference.py
  82. """
  83. hm = self.gaussian_blur(hm, kernelsize)
  84. hm = np.maximum(hm, 1e-10)
  85. hm = np.log(hm)
  86. for n in range(coords.shape[0]):
  87. for p in range(coords.shape[1]):
  88. coords[n, p] = self.dark_parse(hm[n][p], coords[n][p])
  89. return coords
  90. def get_final_preds(self, heatmaps, center, scale, kernelsize=3):
  91. """the highest heatvalue location with a quarter offset in the
  92. direction from the highest response to the second highest response.
  93. Args:
  94. heatmaps (numpy.ndarray): The predicted heatmaps
  95. center (numpy.ndarray): The boxes center
  96. scale (numpy.ndarray): The scale factor
  97. Returns:
  98. preds: numpy.ndarray([batch_size, num_joints, 2]), keypoints coords
  99. maxvals: numpy.ndarray([batch_size, num_joints, 1]), the maximum confidence of the keypoints
  100. """
  101. coords, maxvals = self.get_max_preds(heatmaps)
  102. heatmap_height = heatmaps.shape[2]
  103. heatmap_width = heatmaps.shape[3]
  104. if self.use_dark:
  105. coords = self.dark_postprocess(heatmaps, coords, kernelsize)
  106. else:
  107. for n in range(coords.shape[0]):
  108. for p in range(coords.shape[1]):
  109. hm = heatmaps[n][p]
  110. px = int(math.floor(coords[n][p][0] + 0.5))
  111. py = int(math.floor(coords[n][p][1] + 0.5))
  112. if 1 < px < heatmap_width - 1 and 1 < py < heatmap_height - 1:
  113. diff = np.array([
  114. hm[py][px + 1] - hm[py][px - 1],
  115. hm[py + 1][px] - hm[py - 1][px]
  116. ])
  117. coords[n][p] += np.sign(diff) * .25
  118. preds = coords.copy()
  119. # Transform back
  120. for i in range(coords.shape[0]):
  121. preds[i] = transform_preds(coords[i], center[i], scale[i],
  122. [heatmap_width, heatmap_height])
  123. return preds, maxvals
  124. def __call__(self, output, center, scale):
  125. preds, maxvals = self.get_final_preds(output, center, scale)
  126. return np.concatenate(
  127. (preds, maxvals), axis=-1), np.mean(
  128. maxvals, axis=1)
  129. def transform_preds(coords, center, scale, output_size):
  130. target_coords = np.zeros(coords.shape)
  131. trans = get_affine_transform(center, scale * 200, 0, output_size, inv=1)
  132. for p in range(coords.shape[0]):
  133. target_coords[p, 0:2] = affine_transform(coords[p, 0:2], trans)
  134. return target_coords
  135. def affine_transform(pt, t):
  136. new_pt = np.array([pt[0], pt[1], 1.]).T
  137. new_pt = np.dot(t, new_pt)
  138. return new_pt[:2]