utils.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. import os
  15. import cv2
  16. import time
  17. import numpy as np
  18. from .visualization import plot_tracking_dict, plot_tracking
  19. __all__ = [
  20. 'MOTTimer',
  21. 'Detection',
  22. 'write_mot_results',
  23. 'save_vis_results',
  24. 'load_det_results',
  25. 'preprocess_reid',
  26. 'get_crops',
  27. 'clip_box',
  28. 'scale_coords',
  29. ]
  30. class MOTTimer(object):
  31. """
  32. This class used to compute and print the current FPS while evaling.
  33. """
  34. def __init__(self):
  35. self.total_time = 0.
  36. self.calls = 0
  37. self.start_time = 0.
  38. self.diff = 0.
  39. self.average_time = 0.
  40. self.duration = 0.
  41. def tic(self):
  42. # using time.time instead of time.clock because time time.clock
  43. # does not normalize for multithreading
  44. self.start_time = time.time()
  45. def toc(self, average=True):
  46. self.diff = time.time() - self.start_time
  47. self.total_time += self.diff
  48. self.calls += 1
  49. self.average_time = self.total_time / self.calls
  50. if average:
  51. self.duration = self.average_time
  52. else:
  53. self.duration = self.diff
  54. return self.duration
  55. def clear(self):
  56. self.total_time = 0.
  57. self.calls = 0
  58. self.start_time = 0.
  59. self.diff = 0.
  60. self.average_time = 0.
  61. self.duration = 0.
  62. class Detection(object):
  63. """
  64. This class represents a bounding box detection in a single image.
  65. Args:
  66. tlwh (Tensor): Bounding box in format `(top left x, top left y,
  67. width, height)`.
  68. score (Tensor): Bounding box confidence score.
  69. feature (Tensor): A feature vector that describes the object
  70. contained in this image.
  71. cls_id (Tensor): Bounding box category id.
  72. """
  73. def __init__(self, tlwh, score, feature, cls_id):
  74. self.tlwh = np.asarray(tlwh, dtype=np.float32)
  75. self.score = float(score)
  76. self.feature = np.asarray(feature, dtype=np.float32)
  77. self.cls_id = int(cls_id)
  78. def to_tlbr(self):
  79. """
  80. Convert bounding box to format `(min x, min y, max x, max y)`, i.e.,
  81. `(top left, bottom right)`.
  82. """
  83. ret = self.tlwh.copy()
  84. ret[2:] += ret[:2]
  85. return ret
  86. def to_xyah(self):
  87. """
  88. Convert bounding box to format `(center x, center y, aspect ratio,
  89. height)`, where the aspect ratio is `width / height`.
  90. """
  91. ret = self.tlwh.copy()
  92. ret[:2] += ret[2:] / 2
  93. ret[2] /= ret[3]
  94. return ret
  95. def write_mot_results(filename, results, data_type='mot', num_classes=1):
  96. # support single and multi classes
  97. if data_type in ['mot', 'mcmot']:
  98. save_format = '{frame},{id},{x1},{y1},{w},{h},{score},{cls_id},-1,-1\n'
  99. elif data_type == 'kitti':
  100. save_format = '{frame} {id} car 0 0 -10 {x1} {y1} {x2} {y2} -10 -10 -10 -1000 -1000 -1000 -10\n'
  101. else:
  102. raise ValueError(data_type)
  103. f = open(filename, 'w')
  104. for cls_id in range(num_classes):
  105. for frame_id, tlwhs, tscores, track_ids in results[cls_id]:
  106. if data_type == 'kitti':
  107. frame_id -= 1
  108. for tlwh, score, track_id in zip(tlwhs, tscores, track_ids):
  109. if track_id < 0: continue
  110. if data_type == 'mot':
  111. cls_id = -1
  112. x1, y1, w, h = tlwh
  113. x2, y2 = x1 + w, y1 + h
  114. line = save_format.format(
  115. frame=frame_id,
  116. id=track_id,
  117. x1=x1,
  118. y1=y1,
  119. x2=x2,
  120. y2=y2,
  121. w=w,
  122. h=h,
  123. score=score,
  124. cls_id=cls_id)
  125. f.write(line)
  126. print('MOT results save in {}'.format(filename))
  127. def save_vis_results(data,
  128. frame_id,
  129. online_ids,
  130. online_tlwhs,
  131. online_scores,
  132. average_time,
  133. show_image,
  134. save_dir,
  135. num_classes=1):
  136. if show_image or save_dir is not None:
  137. assert 'ori_image' in data
  138. img0 = data['ori_image'].numpy()[0]
  139. if online_ids is None:
  140. online_im = img0
  141. else:
  142. if isinstance(online_tlwhs, dict):
  143. online_im = plot_tracking_dict(
  144. img0,
  145. num_classes,
  146. online_tlwhs,
  147. online_ids,
  148. online_scores,
  149. frame_id=frame_id,
  150. fps=1. / average_time)
  151. else:
  152. online_im = plot_tracking(
  153. img0,
  154. online_tlwhs,
  155. online_ids,
  156. online_scores,
  157. frame_id=frame_id,
  158. fps=1. / average_time)
  159. if show_image:
  160. cv2.imshow('online_im', online_im)
  161. if save_dir is not None:
  162. cv2.imwrite(
  163. os.path.join(save_dir, '{:05d}.jpg'.format(frame_id)), online_im)
  164. def load_det_results(det_file, num_frames):
  165. assert os.path.exists(det_file) and os.path.isfile(det_file), \
  166. '{} is not exist or not a file.'.format(det_file)
  167. labels = np.loadtxt(det_file, dtype='float32', delimiter=',')
  168. assert labels.shape[1] == 7, \
  169. "Each line of {} should have 7 items: '[frame_id],[x0],[y0],[w],[h],[score],[class_id]'.".format(det_file)
  170. results_list = []
  171. for frame_i in range(num_frames):
  172. results = {'bbox': [], 'score': [], 'cls_id': []}
  173. lables_with_frame = labels[labels[:, 0] == frame_i + 1]
  174. # each line of lables_with_frame:
  175. # [frame_id],[x0],[y0],[w],[h],[score],[class_id]
  176. for l in lables_with_frame:
  177. results['bbox'].append(l[1:5])
  178. results['score'].append(l[5:6])
  179. results['cls_id'].append(l[6:7])
  180. results_list.append(results)
  181. return results_list
  182. def scale_coords(coords, input_shape, im_shape, scale_factor):
  183. # Note: ratio has only one value, scale_factor[0] == scale_factor[1]
  184. #
  185. # This function only used for JDE YOLOv3 or other detectors with
  186. # LetterBoxResize and JDEBBoxPostProcess, coords output from detector had
  187. # not scaled back to the origin image.
  188. ratio = scale_factor[0]
  189. pad_w = (input_shape[1] - int(im_shape[1])) / 2
  190. pad_h = (input_shape[0] - int(im_shape[0])) / 2
  191. coords[:, 0::2] -= pad_w
  192. coords[:, 1::2] -= pad_h
  193. coords[:, 0:4] /= ratio
  194. coords[:, :4] = np.clip(coords[:, :4], a_min=0, a_max=coords[:, :4].max())
  195. return coords.round()
  196. def clip_box(xyxy, ori_image_shape):
  197. H, W = ori_image_shape
  198. xyxy[:, 0::2] = np.clip(xyxy[:, 0::2], a_min=0, a_max=W)
  199. xyxy[:, 1::2] = np.clip(xyxy[:, 1::2], a_min=0, a_max=H)
  200. w = xyxy[:, 2:3] - xyxy[:, 0:1]
  201. h = xyxy[:, 3:4] - xyxy[:, 1:2]
  202. mask = np.logical_and(h > 0, w > 0)
  203. keep_idx = np.nonzero(mask)
  204. return xyxy[keep_idx[0]], keep_idx
  205. def get_crops(xyxy, ori_img, w, h):
  206. crops = []
  207. xyxy = xyxy.astype(np.int64)
  208. ori_img = ori_img.numpy()
  209. ori_img = np.squeeze(ori_img, axis=0).transpose(1, 0, 2) # [h,w,3]->[w,h,3]
  210. for i, bbox in enumerate(xyxy):
  211. crop = ori_img[bbox[0]:bbox[2], bbox[1]:bbox[3], :]
  212. crops.append(crop)
  213. crops = preprocess_reid(crops, w, h)
  214. return crops
  215. def preprocess_reid(imgs,
  216. w=64,
  217. h=192,
  218. mean=[0.485, 0.456, 0.406],
  219. std=[0.229, 0.224, 0.225]):
  220. im_batch = []
  221. for img in imgs:
  222. img = cv2.resize(img, (w, h))
  223. img = img[:, :, ::-1].astype('float32').transpose((2, 0, 1)) / 255
  224. img_mean = np.array(mean).reshape((3, 1, 1))
  225. img_std = np.array(std).reshape((3, 1, 1))
  226. img -= img_mean
  227. img /= img_std
  228. img = np.expand_dims(img, axis=0)
  229. im_batch.append(img)
  230. im_batch = np.concatenate(im_batch, 0)
  231. return im_batch