vis_tools.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. import cv2
  2. import os
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. # -------------------------- For Detection Task --------------------------
  6. ## Draw bbox & label on the image
  7. def plot_bbox_labels(img, bbox, label=None, cls_color=None, text_scale=0.4):
  8. x1, y1, x2, y2 = bbox
  9. x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
  10. t_size = cv2.getTextSize(label, 0, fontScale=1, thickness=2)[0]
  11. # plot bbox
  12. cv2.rectangle(img, (x1, y1), (x2, y2), cls_color, 2)
  13. if label is not None:
  14. # plot title bbox
  15. cv2.rectangle(img, (x1, y1-t_size[1]), (int(x1 + t_size[0] * text_scale), y1), cls_color, -1)
  16. # put the test on the title bbox
  17. cv2.putText(img, label, (int(x1), int(y1 - 5)), 0, text_scale, (0, 0, 0), 1, lineType=cv2.LINE_AA)
  18. return img
  19. ## Visualize the detection results
  20. def visualize(image, bboxes, scores, labels, class_colors, class_names, class_indexs):
  21. ts = 0.4
  22. for i, bbox in enumerate(bboxes):
  23. cls_id = int(labels[i])
  24. cls_color = class_colors[cls_id]
  25. cls_id = class_indexs[cls_id]
  26. mess = '%s: %.2f' % (class_names[cls_id], scores[i])
  27. image = plot_bbox_labels(image, bbox, mess, cls_color, text_scale=ts)
  28. return image
  29. ## Visualize the input data during the training stage
  30. def vis_data(images, targets, num_classes=80, normalized_bbox=False, pixel_mean=None, pixel_std=None):
  31. """
  32. images: (tensor) [B, 3, H, W]
  33. targets: (list) a list of targets
  34. """
  35. batch_size = images.size(0)
  36. np.random.seed(0)
  37. class_colors = [(np.random.randint(255),
  38. np.random.randint(255),
  39. np.random.randint(255)) for _ in range(num_classes)]
  40. for bi in range(batch_size):
  41. tgt_boxes = target['boxes']
  42. tgt_labels = target['labels']
  43. # to numpy
  44. image = images[bi].permute(1, 2, 0).cpu().numpy()
  45. target = targets[bi]
  46. image = image.astype(np.uint8)
  47. image = image.copy()
  48. img_h, img_w = image.shape[:2]
  49. # denormalize image
  50. if pixel_mean is not None and pixel_std is not None:
  51. image = image * pixel_std + pixel_mean
  52. image = image[..., (2, 1, 0)] # RGB to BGR
  53. # denormalize bbox
  54. if normalized_bbox:
  55. tgt_boxes[:, [0, 2]] *= img_w
  56. tgt_boxes[:, [1, 3]] *= img_h
  57. # visualize target
  58. for box, label in zip(tgt_boxes, tgt_labels):
  59. x1, y1, x2, y2 = box
  60. cls_id = int(label)
  61. x1, y1 = int(x1), int(y1)
  62. x2, y2 = int(x2), int(y2)
  63. color = class_colors[cls_id]
  64. # draw box
  65. cv2.rectangle(image, (x1, y1), (x2, y2), color, 2)
  66. cv2.imshow('train target', image)
  67. cv2.waitKey(0)
  68. ## convert feature to he heatmap
  69. def convert_feature_heatmap(feature):
  70. """
  71. feature: (ndarray) [H, W, C]
  72. """
  73. heatmap = None
  74. return heatmap
  75. ## draw feature on the image
  76. def draw_feature(img, features, save=None):
  77. """
  78. img: (ndarray & cv2.Mat) [H, W, C], where the C is 3 for RGB or 1 for Gray.
  79. features: (List[ndarray]). It is a list of the multiple feature map whose shape is [H, W, C].
  80. save: (bool) save the result or not.
  81. """
  82. img_h, img_w = img.shape[:2]
  83. for i, fmp in enumerate(features):
  84. hmp = convert_feature_heatmap(fmp)
  85. hmp = cv2.resize(hmp, (img_w, img_h))
  86. hmp = hmp.astype(np.uint8)*255
  87. hmp_rgb = cv2.applyColorMap(hmp, cv2.COLORMAP_JET)
  88. superimposed_img = hmp_rgb * 0.4 + img
  89. # show the heatmap
  90. plt.imshow(hmp)
  91. plt.close()
  92. # show the image with heatmap
  93. cv2.imshow("image with heatmap", superimposed_img)
  94. cv2.waitKey(0)
  95. cv2.destroyAllWindows()
  96. if save:
  97. save_dir = 'feature_heatmap'
  98. os.makedirs(save_dir, exist_ok=True)
  99. cv2.imwrite(os.path.join(save_dir, 'feature_{}.png'.format(i) ), superimposed_img)
  100. # -------------------------- For Tracking Task --------------------------
  101. def get_color(idx):
  102. idx = idx * 3
  103. color = ((37 * idx) % 255, (17 * idx) % 255, (29 * idx) % 255)
  104. return color
  105. def plot_tracking(image, tlwhs, obj_ids, scores=None, frame_id=0, fps=0., ids2=None):
  106. im = np.ascontiguousarray(np.copy(image))
  107. im_h, im_w = im.shape[:2]
  108. top_view = np.zeros([im_w, im_w, 3], dtype=np.uint8) + 255
  109. #text_scale = max(1, image.shape[1] / 1600.)
  110. #text_thickness = 2
  111. #line_thickness = max(1, int(image.shape[1] / 500.))
  112. text_scale = 2
  113. text_thickness = 2
  114. line_thickness = 3
  115. radius = max(5, int(im_w/140.))
  116. cv2.putText(im, 'frame: %d fps: %.2f num: %d' % (frame_id, fps, len(tlwhs)),
  117. (0, int(15 * text_scale)), cv2.FONT_HERSHEY_PLAIN, 2, (0, 0, 255), thickness=2)
  118. for i, tlwh in enumerate(tlwhs):
  119. x1, y1, w, h = tlwh
  120. intbox = tuple(map(int, (x1, y1, x1 + w, y1 + h)))
  121. obj_id = int(obj_ids[i])
  122. id_text = '{}'.format(int(obj_id))
  123. if ids2 is not None:
  124. id_text = id_text + ', {}'.format(int(ids2[i]))
  125. color = get_color(abs(obj_id))
  126. cv2.rectangle(im, intbox[0:2], intbox[2:4], color=color, thickness=line_thickness)
  127. cv2.putText(im, id_text, (intbox[0], intbox[1]), cv2.FONT_HERSHEY_PLAIN, text_scale, (0, 0, 255),
  128. thickness=text_thickness)
  129. return im