util2.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. import math
  2. import cv2
  3. import matplotlib
  4. import matplotlib.pyplot as plt
  5. import numpy as np
  6. from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
  7. from matplotlib.figure import Figure
  8. def padRightDownCorner(img, stride, padValue):
  9. h = img.shape[0]
  10. w = img.shape[1]
  11. pad = 4 * [None]
  12. pad[0] = 0 # up
  13. pad[1] = 0 # left
  14. pad[2] = 0 if (h % stride == 0) else stride - (h % stride) # down
  15. pad[3] = 0 if (w % stride == 0) else stride - (w % stride) # right
  16. img_padded = img
  17. pad_up = np.tile(img_padded[0:1, :, :] * 0 + padValue, (pad[0], 1, 1))
  18. img_padded = np.concatenate((pad_up, img_padded), axis=0)
  19. pad_left = np.tile(img_padded[:, 0:1, :] * 0 + padValue, (1, pad[1], 1))
  20. img_padded = np.concatenate((pad_left, img_padded), axis=1)
  21. pad_down = np.tile(img_padded[-2:-1, :, :] * 0 + padValue, (pad[2], 1, 1))
  22. img_padded = np.concatenate((img_padded, pad_down), axis=0)
  23. pad_right = np.tile(img_padded[:, -2:-1, :] * 0 + padValue, (1, pad[3], 1))
  24. img_padded = np.concatenate((img_padded, pad_right), axis=1)
  25. return img_padded, pad
  26. # transfer caffe model to pytorch which will match the layer name
  27. def transfer(model, model_weights):
  28. transfered_model_weights = {}
  29. for weights_name in model.state_dict().keys():
  30. transfered_model_weights[weights_name] = model_weights['.'.join(weights_name.split('.')[1:])]
  31. return transfered_model_weights
  32. # draw the body keypoint and lims
  33. def draw_bodypose(canvas, candidate, subset):
  34. stickwidth = 4
  35. limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10], \
  36. [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17], \
  37. [1, 16], [16, 18], [3, 17], [6, 18]]
  38. colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0], \
  39. [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255], \
  40. [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]
  41. for i in range(18):
  42. for n in range(len(subset)):
  43. index = int(subset[n][i])
  44. if index == -1:
  45. continue
  46. x, y = candidate[index][0:2]
  47. cv2.circle(canvas, (int(x), int(y)), 4, colors[i], thickness=-1)
  48. for i in range(17):
  49. for n in range(len(subset)):
  50. index = subset[n][np.array(limbSeq[i]) - 1]
  51. if -1 in index:
  52. continue
  53. cur_canvas = canvas.copy()
  54. Y = candidate[index.astype(int), 0]
  55. X = candidate[index.astype(int), 1]
  56. mX = np.mean(X)
  57. mY = np.mean(Y)
  58. length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
  59. angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
  60. polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), stickwidth), int(angle), 0, 360, 1)
  61. cv2.fillConvexPoly(cur_canvas, polygon, colors[i])
  62. canvas = cv2.addWeighted(canvas, 0.4, cur_canvas, 0.6, 0)
  63. # plt.imsave("preview.jpg", canvas[:, :, [2, 1, 0]])
  64. # plt.imshow(canvas[:, :, [2, 1, 0]])
  65. return canvas
  66. def draw_handpose(canvas, all_hand_peaks, show_number=False):
  67. edges = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], \
  68. [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]]
  69. fig = Figure(figsize=plt.figaspect(canvas))
  70. fig.subplots_adjust(0, 0, 1, 1)
  71. fig.subplots_adjust(bottom=0, top=1, left=0, right=1)
  72. bg = FigureCanvas(fig)
  73. ax = fig.subplots()
  74. ax.axis('off')
  75. ax.imshow(canvas)
  76. width, height = ax.figure.get_size_inches() * ax.figure.get_dpi()
  77. for peaks in all_hand_peaks:
  78. for ie, e in enumerate(edges):
  79. if np.sum(np.all(peaks[e], axis=1) == 0) == 0:
  80. x1, y1 = peaks[e[0]]
  81. x2, y2 = peaks[e[1]]
  82. ax.plot([x1, x2], [y1, y2], color=matplotlib.colors.hsv_to_rgb([ie / float(len(edges)), 1.0, 1.0]))
  83. for i, keyponit in enumerate(peaks):
  84. x, y = keyponit
  85. ax.plot(x, y, 'r.')
  86. if show_number:
  87. ax.text(x, y, str(i))
  88. bg.draw()
  89. canvas = np.fromstring(bg.tostring_rgb(), dtype='uint8').reshape(int(height), int(width), 3)
  90. return canvas
  91. # image drawed by opencv is not good.
  92. def draw_handpose_by_opencv(canvas, peaks, show_number=False):
  93. edges = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], \
  94. [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]]
  95. # cv2.rectangle(canvas, (x, y), (x+w, y+w), (0, 255, 0), 2, lineType=cv2.LINE_AA)
  96. # cv2.putText(canvas, 'left' if is_left else 'right', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
  97. for ie, e in enumerate(edges):
  98. if np.sum(np.all(peaks[e], axis=1) == 0) == 0:
  99. x1, y1 = peaks[e[0]]
  100. x2, y2 = peaks[e[1]]
  101. cv2.line(canvas, (x1, y1), (x2, y2), matplotlib.colors.hsv_to_rgb([ie / float(len(edges)), 1.0, 1.0]) * 255,
  102. thickness=2)
  103. for i, keyponit in enumerate(peaks):
  104. x, y = keyponit
  105. cv2.circle(canvas, (x, y), 4, (0, 0, 255), thickness=-1)
  106. if show_number:
  107. cv2.putText(canvas, str(i), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.3, (0, 0, 0), lineType=cv2.LINE_AA)
  108. return canvas
  109. # detect hand according to body pose keypoints
  110. # please refer to https://github.com/CMU-Perceptual-Computing-Lab/openpose/blob/master/src/openpose/hand/handDetector.cpp
  111. def handDetect(candidate, subset, oriImg):
  112. # right hand: wrist 4, elbow 3, shoulder 2
  113. # left hand: wrist 7, elbow 6, shoulder 5
  114. ratioWristElbow = 0.33
  115. detect_result = []
  116. image_height, image_width = oriImg.shape[0:2]
  117. for person in subset.astype(int):
  118. # if any of three not detected
  119. has_left = np.sum(person[[5, 6, 7]] == -1) == 0
  120. has_right = np.sum(person[[2, 3, 4]] == -1) == 0
  121. if not (has_left or has_right):
  122. continue
  123. hands = []
  124. # left hand
  125. if has_left:
  126. left_shoulder_index, left_elbow_index, left_wrist_index = person[[5, 6, 7]]
  127. x1, y1 = candidate[left_shoulder_index][:2]
  128. x2, y2 = candidate[left_elbow_index][:2]
  129. x3, y3 = candidate[left_wrist_index][:2]
  130. hands.append([x1, y1, x2, y2, x3, y3, True])
  131. # right hand
  132. if has_right:
  133. right_shoulder_index, right_elbow_index, right_wrist_index = person[[2, 3, 4]]
  134. x1, y1 = candidate[right_shoulder_index][:2]
  135. x2, y2 = candidate[right_elbow_index][:2]
  136. x3, y3 = candidate[right_wrist_index][:2]
  137. hands.append([x1, y1, x2, y2, x3, y3, False])
  138. for x1, y1, x2, y2, x3, y3, is_left in hands:
  139. # pos_hand = pos_wrist + ratio * (pos_wrist - pos_elbox) = (1 + ratio) * pos_wrist - ratio * pos_elbox
  140. # handRectangle.x = posePtr[wrist*3] + ratioWristElbow * (posePtr[wrist*3] - posePtr[elbow*3]);
  141. # handRectangle.y = posePtr[wrist*3+1] + ratioWristElbow * (posePtr[wrist*3+1] - posePtr[elbow*3+1]);
  142. # const auto distanceWristElbow = getDistance(poseKeypoints, person, wrist, elbow);
  143. # const auto distanceElbowShoulder = getDistance(poseKeypoints, person, elbow, shoulder);
  144. # handRectangle.width = 1.5f * fastMax(distanceWristElbow, 0.9f * distanceElbowShoulder);
  145. x = x3 + ratioWristElbow * (x3 - x2)
  146. y = y3 + ratioWristElbow * (y3 - y2)
  147. distanceWristElbow = math.sqrt((x3 - x2) ** 2 + (y3 - y2) ** 2)
  148. distanceElbowShoulder = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
  149. width = 1.5 * max(distanceWristElbow, 0.9 * distanceElbowShoulder)
  150. # x-y refers to the center --> offset to topLeft point
  151. # handRectangle.x -= handRectangle.width / 2.f;
  152. # handRectangle.y -= handRectangle.height / 2.f;
  153. x -= width / 2
  154. y -= width / 2 # width = height
  155. # overflow the image
  156. if x < 0: x = 0
  157. if y < 0: y = 0
  158. width1 = width
  159. width2 = width
  160. if x + width > image_width: width1 = image_width - x
  161. if y + width > image_height: width2 = image_height - y
  162. width = min(width1, width2)
  163. # the max hand box value is 20 pixels
  164. if width >= 20:
  165. detect_result.append([int(x), int(y), int(width), is_left])
  166. '''
  167. return value: [[x, y, w, True if left hand else False]].
  168. width=height since the network require squared input.
  169. x, y is the coordinate of top left
  170. '''
  171. return detect_result
  172. # get max index of 2d array
  173. def npmax(array):
  174. arrayindex = array.argmax(1)
  175. arrayvalue = array.max(1)
  176. i = arrayvalue.argmax()
  177. j = arrayindex[i]
  178. return i, j