utils.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. import collections
  19. import math
  20. __all__ = [
  21. 'MOTTimer', 'Detection', 'write_mot_results', 'load_det_results',
  22. 'preprocess_reid', 'get_crops', 'clip_box', 'scale_coords',
  23. 'flow_statistic', 'update_object_info'
  24. ]
  25. class MOTTimer(object):
  26. """
  27. This class used to compute and print the current FPS while evaling.
  28. """
  29. def __init__(self, window_size=20):
  30. self.start_time = 0.
  31. self.diff = 0.
  32. self.duration = 0.
  33. self.deque = collections.deque(maxlen=window_size)
  34. def tic(self):
  35. # using time.time instead of time.clock because time time.clock
  36. # does not normalize for multithreading
  37. self.start_time = time.time()
  38. def toc(self, average=True):
  39. self.diff = time.time() - self.start_time
  40. self.deque.append(self.diff)
  41. if average:
  42. self.duration = np.mean(self.deque)
  43. else:
  44. self.duration = np.sum(self.deque)
  45. return self.duration
  46. def clear(self):
  47. self.start_time = 0.
  48. self.diff = 0.
  49. self.duration = 0.
  50. class Detection(object):
  51. """
  52. This class represents a bounding box detection in a single image.
  53. Args:
  54. tlwh (Tensor): Bounding box in format `(top left x, top left y,
  55. width, height)`.
  56. score (Tensor): Bounding box confidence score.
  57. feature (Tensor): A feature vector that describes the object
  58. contained in this image.
  59. cls_id (Tensor): Bounding box category id.
  60. """
  61. def __init__(self, tlwh, score, feature, cls_id):
  62. self.tlwh = np.asarray(tlwh, dtype=np.float32)
  63. self.score = float(score)
  64. self.feature = np.asarray(feature, dtype=np.float32)
  65. self.cls_id = int(cls_id)
  66. def to_tlbr(self):
  67. """
  68. Convert bounding box to format `(min x, min y, max x, max y)`, i.e.,
  69. `(top left, bottom right)`.
  70. """
  71. ret = self.tlwh.copy()
  72. ret[2:] += ret[:2]
  73. return ret
  74. def to_xyah(self):
  75. """
  76. Convert bounding box to format `(center x, center y, aspect ratio,
  77. height)`, where the aspect ratio is `width / height`.
  78. """
  79. ret = self.tlwh.copy()
  80. ret[:2] += ret[2:] / 2
  81. ret[2] /= ret[3]
  82. return ret
  83. def write_mot_results(filename, results, data_type='mot', num_classes=1):
  84. # support single and multi classes
  85. if data_type in ['mot', 'mcmot']:
  86. save_format = '{frame},{id},{x1},{y1},{w},{h},{score},{cls_id},-1,-1\n'
  87. elif data_type == 'kitti':
  88. save_format = '{frame} {id} car 0 0 -10 {x1} {y1} {x2} {y2} -10 -10 -10 -1000 -1000 -1000 -10\n'
  89. else:
  90. raise ValueError(data_type)
  91. f = open(filename, 'w')
  92. for cls_id in range(num_classes):
  93. for frame_id, tlwhs, tscores, track_ids in results[cls_id]:
  94. if data_type == 'kitti':
  95. frame_id -= 1
  96. for tlwh, score, track_id in zip(tlwhs, tscores, track_ids):
  97. if track_id < 0: continue
  98. if data_type == 'mot':
  99. cls_id = -1
  100. x1, y1, w, h = tlwh
  101. x2, y2 = x1 + w, y1 + h
  102. line = save_format.format(
  103. frame=frame_id,
  104. id=track_id,
  105. x1=x1,
  106. y1=y1,
  107. x2=x2,
  108. y2=y2,
  109. w=w,
  110. h=h,
  111. score=score,
  112. cls_id=cls_id)
  113. f.write(line)
  114. print('MOT results save in {}'.format(filename))
  115. def load_det_results(det_file, num_frames):
  116. assert os.path.exists(det_file) and os.path.isfile(det_file), \
  117. '{} is not exist or not a file.'.format(det_file)
  118. labels = np.loadtxt(det_file, dtype='float32', delimiter=',')
  119. assert labels.shape[1] == 7, \
  120. "Each line of {} should have 7 items: '[frame_id],[x0],[y0],[w],[h],[score],[class_id]'.".format(det_file)
  121. results_list = []
  122. for frame_i in range(num_frames):
  123. results = {'bbox': [], 'score': [], 'cls_id': []}
  124. lables_with_frame = labels[labels[:, 0] == frame_i + 1]
  125. # each line of lables_with_frame:
  126. # [frame_id],[x0],[y0],[w],[h],[score],[class_id]
  127. for l in lables_with_frame:
  128. results['bbox'].append(l[1:5])
  129. results['score'].append(l[5:6])
  130. results['cls_id'].append(l[6:7])
  131. results_list.append(results)
  132. return results_list
  133. def scale_coords(coords, input_shape, im_shape, scale_factor):
  134. # Note: ratio has only one value, scale_factor[0] == scale_factor[1]
  135. #
  136. # This function only used for JDE YOLOv3 or other detectors with
  137. # LetterBoxResize and JDEBBoxPostProcess, coords output from detector had
  138. # not scaled back to the origin image.
  139. ratio = scale_factor[0]
  140. pad_w = (input_shape[1] - int(im_shape[1])) / 2
  141. pad_h = (input_shape[0] - int(im_shape[0])) / 2
  142. coords[:, 0::2] -= pad_w
  143. coords[:, 1::2] -= pad_h
  144. coords[:, 0:4] /= ratio
  145. coords[:, :4] = np.clip(coords[:, :4], a_min=0, a_max=coords[:, :4].max())
  146. return coords.round()
  147. def clip_box(xyxy, ori_image_shape):
  148. H, W = ori_image_shape
  149. xyxy[:, 0::2] = np.clip(xyxy[:, 0::2], a_min=0, a_max=W)
  150. xyxy[:, 1::2] = np.clip(xyxy[:, 1::2], a_min=0, a_max=H)
  151. w = xyxy[:, 2:3] - xyxy[:, 0:1]
  152. h = xyxy[:, 3:4] - xyxy[:, 1:2]
  153. mask = np.logical_and(h > 0, w > 0)
  154. keep_idx = np.nonzero(mask)
  155. return xyxy[keep_idx[0]], keep_idx
  156. def get_crops(xyxy, ori_img, w, h):
  157. crops = []
  158. xyxy = xyxy.astype(np.int64)
  159. ori_img = ori_img.transpose(1, 0, 2) # [h,w,3]->[w,h,3]
  160. for i, bbox in enumerate(xyxy):
  161. crop = ori_img[bbox[0]:bbox[2], bbox[1]:bbox[3], :]
  162. crops.append(crop)
  163. crops = preprocess_reid(crops, w, h)
  164. return crops
  165. def preprocess_reid(imgs,
  166. w=64,
  167. h=192,
  168. mean=[0.485, 0.456, 0.406],
  169. std=[0.229, 0.224, 0.225]):
  170. im_batch = []
  171. for img in imgs:
  172. img = cv2.resize(img, (w, h))
  173. img = img[:, :, ::-1].astype('float32').transpose((2, 0, 1)) / 255
  174. img_mean = np.array(mean).reshape((3, 1, 1))
  175. img_std = np.array(std).reshape((3, 1, 1))
  176. img -= img_mean
  177. img /= img_std
  178. img = np.expand_dims(img, axis=0)
  179. im_batch.append(img)
  180. im_batch = np.concatenate(im_batch, 0)
  181. return im_batch
  182. def flow_statistic(result,
  183. secs_interval,
  184. do_entrance_counting,
  185. do_break_in_counting,
  186. region_type,
  187. video_fps,
  188. entrance,
  189. id_set,
  190. interval_id_set,
  191. in_id_list,
  192. out_id_list,
  193. prev_center,
  194. records,
  195. data_type='mot',
  196. ids2names=['pedestrian']):
  197. # Count in/out number:
  198. # Note that 'region_type' should be one of ['horizontal', 'vertical', 'custom'],
  199. # 'horizontal' and 'vertical' means entrance is the center line as the entrance when do_entrance_counting,
  200. # 'custom' means entrance is a region defined by users when do_break_in_counting.
  201. if do_entrance_counting:
  202. assert region_type in [
  203. 'horizontal', 'vertical'
  204. ], "region_type should be 'horizontal' or 'vertical' when do entrance counting."
  205. entrance_x, entrance_y = entrance[0], entrance[1]
  206. frame_id, tlwhs, tscores, track_ids = result
  207. for tlwh, score, track_id in zip(tlwhs, tscores, track_ids):
  208. if track_id < 0: continue
  209. if data_type == 'kitti':
  210. frame_id -= 1
  211. x1, y1, w, h = tlwh
  212. center_x = x1 + w / 2.
  213. center_y = y1 + h / 2.
  214. if track_id in prev_center:
  215. if region_type == 'horizontal':
  216. # horizontal center line
  217. if prev_center[track_id][1] <= entrance_y and \
  218. center_y > entrance_y:
  219. in_id_list.append(track_id)
  220. if prev_center[track_id][1] >= entrance_y and \
  221. center_y < entrance_y:
  222. out_id_list.append(track_id)
  223. else:
  224. # vertical center line
  225. if prev_center[track_id][0] <= entrance_x and \
  226. center_x > entrance_x:
  227. in_id_list.append(track_id)
  228. if prev_center[track_id][0] >= entrance_x and \
  229. center_x < entrance_x:
  230. out_id_list.append(track_id)
  231. prev_center[track_id][0] = center_x
  232. prev_center[track_id][1] = center_y
  233. else:
  234. prev_center[track_id] = [center_x, center_y]
  235. if do_break_in_counting:
  236. assert region_type in [
  237. 'custom'
  238. ], "region_type should be 'custom' when do break_in counting."
  239. assert len(
  240. entrance
  241. ) >= 4, "entrance should be at least 3 points and (w,h) of image when do break_in counting."
  242. im_w, im_h = entrance[-1][:]
  243. entrance = np.array(entrance[:-1])
  244. frame_id, tlwhs, tscores, track_ids = result
  245. for tlwh, score, track_id in zip(tlwhs, tscores, track_ids):
  246. if track_id < 0: continue
  247. if data_type == 'kitti':
  248. frame_id -= 1
  249. x1, y1, w, h = tlwh
  250. center_x = min(x1 + w / 2., im_w - 1)
  251. if ids2names[0] == 'pedestrian':
  252. center_y = min(y1 + h, im_h - 1)
  253. else:
  254. center_y = min(y1 + h / 2, im_h - 1)
  255. # counting objects in region of the first frame
  256. if frame_id == 1:
  257. if in_quadrangle([center_x, center_y], entrance, im_h, im_w):
  258. in_id_list.append(-1)
  259. else:
  260. prev_center[track_id] = [center_x, center_y]
  261. else:
  262. if track_id in prev_center:
  263. if not in_quadrangle(prev_center[track_id], entrance, im_h,
  264. im_w) and in_quadrangle(
  265. [center_x, center_y], entrance,
  266. im_h, im_w):
  267. in_id_list.append(track_id)
  268. prev_center[track_id] = [center_x, center_y]
  269. else:
  270. prev_center[track_id] = [center_x, center_y]
  271. # Count totol number, number at a manual-setting interval
  272. frame_id, tlwhs, tscores, track_ids = result
  273. for tlwh, score, track_id in zip(tlwhs, tscores, track_ids):
  274. if track_id < 0: continue
  275. id_set.add(track_id)
  276. interval_id_set.add(track_id)
  277. # Reset counting at the interval beginning
  278. if frame_id % video_fps == 0 and frame_id / video_fps % secs_interval == 0:
  279. curr_interval_count = len(interval_id_set)
  280. interval_id_set.clear()
  281. info = "Frame id: {}, Total count: {}".format(frame_id, len(id_set))
  282. if do_entrance_counting:
  283. info += ", In count: {}, Out count: {}".format(
  284. len(in_id_list), len(out_id_list))
  285. if do_break_in_counting:
  286. info += ", Break_in count: {}".format(len(in_id_list))
  287. if frame_id % video_fps == 0 and frame_id / video_fps % secs_interval == 0:
  288. info += ", Count during {} secs: {}".format(secs_interval,
  289. curr_interval_count)
  290. interval_id_set.clear()
  291. # print(info)
  292. info += "\n"
  293. records.append(info)
  294. return {
  295. "id_set": id_set,
  296. "interval_id_set": interval_id_set,
  297. "in_id_list": in_id_list,
  298. "out_id_list": out_id_list,
  299. "prev_center": prev_center,
  300. "records": records,
  301. }
  302. def distance(center_1, center_2):
  303. return math.sqrt(
  304. math.pow(center_1[0] - center_2[0], 2) + math.pow(center_1[1] -
  305. center_2[1], 2))
  306. # update vehicle parking info
  307. def update_object_info(object_in_region_info,
  308. result,
  309. region_type,
  310. entrance,
  311. fps,
  312. illegal_parking_time,
  313. distance_threshold_frame=3,
  314. distance_threshold_interval=50):
  315. '''
  316. For consecutive frames, the distance between two frame is smaller than distance_threshold_frame, regard as parking
  317. For parking in general, the move distance should smaller than distance_threshold_interval
  318. The moving distance of the vehicle is scaled according to the y, which is inversely proportional to y.
  319. '''
  320. assert region_type in [
  321. 'custom'
  322. ], "region_type should be 'custom' when do break_in counting."
  323. assert len(
  324. entrance
  325. ) >= 4, "entrance should be at least 3 points and (w,h) of image when do break_in counting."
  326. frame_id, tlwhs, tscores, track_ids = result # result from mot
  327. im_w, im_h = entrance[-1][:]
  328. entrance = np.array(entrance[:-1])
  329. illegal_parking_dict = {}
  330. for tlwh, score, track_id in zip(tlwhs, tscores, track_ids):
  331. if track_id < 0: continue
  332. x1, y1, w, h = tlwh
  333. center_x = min(x1 + w / 2., im_w - 1)
  334. center_y = min(y1 + h / 2, im_h - 1)
  335. if not in_quadrangle([center_x, center_y], entrance, im_h, im_w):
  336. continue
  337. current_center = (center_x, center_y)
  338. if track_id not in object_in_region_info.keys(
  339. ): # first time appear in region
  340. object_in_region_info[track_id] = {}
  341. object_in_region_info[track_id]["start_frame"] = frame_id
  342. object_in_region_info[track_id]["end_frame"] = frame_id
  343. object_in_region_info[track_id]["prev_center"] = current_center
  344. object_in_region_info[track_id]["start_center"] = current_center
  345. else:
  346. prev_center = object_in_region_info[track_id]["prev_center"]
  347. dis = distance(current_center, prev_center)
  348. scaled_dis = 200 * dis / (
  349. current_center[1] + 1) # scale distance according to y
  350. dis = scaled_dis
  351. if dis < distance_threshold_frame: # not move
  352. object_in_region_info[track_id]["end_frame"] = frame_id
  353. object_in_region_info[track_id]["prev_center"] = current_center
  354. else: # move
  355. object_in_region_info[track_id]["start_frame"] = frame_id
  356. object_in_region_info[track_id]["end_frame"] = frame_id
  357. object_in_region_info[track_id]["prev_center"] = current_center
  358. object_in_region_info[track_id]["start_center"] = current_center
  359. # whether current object parking
  360. distance_from_start = distance(
  361. object_in_region_info[track_id]["start_center"], current_center)
  362. if distance_from_start > distance_threshold_interval:
  363. # moved
  364. object_in_region_info[track_id]["start_frame"] = frame_id
  365. object_in_region_info[track_id]["end_frame"] = frame_id
  366. object_in_region_info[track_id]["prev_center"] = current_center
  367. object_in_region_info[track_id]["start_center"] = current_center
  368. continue
  369. if (object_in_region_info[track_id]["end_frame"]-object_in_region_info[track_id]["start_frame"]) /fps >= illegal_parking_time \
  370. and distance_from_start<distance_threshold_interval:
  371. illegal_parking_dict[track_id] = {"bbox": [x1, y1, w, h]}
  372. return object_in_region_info, illegal_parking_dict
  373. def in_quadrangle(point, entrance, im_h, im_w):
  374. mask = np.zeros((im_h, im_w, 1), np.uint8)
  375. cv2.fillPoly(mask, [entrance], 255)
  376. p = tuple(map(int, point))
  377. if mask[p[1], p[0], :] > 0:
  378. return True
  379. else:
  380. return False