util.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import numpy as np
  2. import math
  3. import cv2
  4. # draw the body keypoint and lims
  5. def draw_bodypose(img, poses,model_type = 'coco'):
  6. stickwidth = 4
  7. limbSeq = [[1, 2], [1, 5], [2, 3], [3, 4], [5, 6], [6, 7], [1, 8], [8, 9], \
  8. [9, 10], [1, 11], [11, 12], [12, 13], [1, 0], [0, 14], [14, 16], \
  9. [0, 15], [15, 17]]
  10. njoint = 18
  11. if model_type == 'body_25':
  12. limbSeq = [[1,0],[1,2],[2,3],[3,4],[1,5],[5,6],[6,7],[1,8],[8,9],[9,10],\
  13. [10,11],[8,12],[12,13],[13,14],[0,15],[0,16],[15,17],[16,18],\
  14. [11,24],[11,22],[14,21],[14,19],[22,23],[19,20]]
  15. njoint = 25
  16. colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0], \
  17. [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255], \
  18. [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85], [255,255,0], [255,255,85], [255,255,170],\
  19. [255,255,255],[170,255,255],[85,255,255],[0,255,255]]
  20. for i in range(njoint):
  21. for n in range(len(poses)):
  22. pose = poses[n][i]
  23. if pose[2] <= 0:
  24. continue
  25. x, y = pose[:2]
  26. cv2.circle(img, (int(x), int(y)), 4, colors[i], thickness=-1)
  27. for pose in poses:
  28. for limb,color in zip(limbSeq,colors):
  29. p1 = pose[limb[0]]
  30. p2 = pose[limb[1]]
  31. if p1[2] <=0 or p2[2] <= 0:
  32. continue
  33. cur_canvas = img.copy()
  34. X = [p1[1],p2[1]]
  35. Y = [p1[0],p2[0]]
  36. mX = np.mean(X)
  37. mY = np.mean(Y)
  38. length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
  39. angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
  40. polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), stickwidth), int(angle), 0, 360, 1)
  41. cv2.fillConvexPoly(cur_canvas, polygon, color)
  42. img = cv2.addWeighted(img, 0.4, cur_canvas, 0.6, 0)
  43. return img
  44. def padRightDownCorner(img, stride, padValue):
  45. h = img.shape[0]
  46. w = img.shape[1]
  47. pad = 4 * [None]
  48. pad[0] = 0 # up
  49. pad[1] = 0 # left
  50. pad[2] = 0 if (h % stride == 0) else stride - (h % stride) # down
  51. pad[3] = 0 if (w % stride == 0) else stride - (w % stride) # right
  52. img_padded = img
  53. pad_up = np.tile(img_padded[0:1, :, :]*0 + padValue, (pad[0], 1, 1))
  54. img_padded = np.concatenate((pad_up, img_padded), axis=0)
  55. pad_left = np.tile(img_padded[:, 0:1, :]*0 + padValue, (1, pad[1], 1))
  56. img_padded = np.concatenate((pad_left, img_padded), axis=1)
  57. pad_down = np.tile(img_padded[-2:-1, :, :]*0 + padValue, (pad[2], 1, 1))
  58. img_padded = np.concatenate((img_padded, pad_down), axis=0)
  59. pad_right = np.tile(img_padded[:, -2:-1, :]*0 + padValue, (1, pad[3], 1))
  60. img_padded = np.concatenate((img_padded, pad_right), axis=1)
  61. return img_padded, pad