tracker.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import os
  18. import glob
  19. import re
  20. import paddle
  21. import paddle.nn as nn
  22. import numpy as np
  23. from tqdm import tqdm
  24. from collections import defaultdict
  25. from ppdet.core.workspace import create
  26. from ppdet.utils.checkpoint import load_weight, load_pretrain_weight
  27. from ppdet.modeling.mot.utils import Detection, get_crops, scale_coords, clip_box
  28. from ppdet.modeling.mot.utils import MOTTimer, load_det_results, write_mot_results, save_vis_results
  29. from ppdet.modeling.mot.tracker import JDETracker, CenterTracker
  30. from ppdet.modeling.mot.tracker import DeepSORTTracker, OCSORTTracker, BOTSORTTracker
  31. from ppdet.modeling.architectures import YOLOX
  32. from ppdet.metrics import Metric, MOTMetric, KITTIMOTMetric, MCMOTMetric
  33. from ppdet.data.source.category import get_categories
  34. import ppdet.utils.stats as stats
  35. from .callbacks import Callback, ComposeCallback
  36. from ppdet.utils.logger import setup_logger
  37. logger = setup_logger(__name__)
  38. MOT_ARCH = ['JDE', 'FairMOT', 'DeepSORT', 'ByteTrack', 'CenterTrack']
  39. MOT_ARCH_JDE = MOT_ARCH[:2]
  40. MOT_ARCH_SDE = MOT_ARCH[2:4]
  41. MOT_DATA_TYPE = ['mot', 'mcmot', 'kitti']
  42. __all__ = ['Tracker']
  43. class Tracker(object):
  44. def __init__(self, cfg, mode='eval'):
  45. self.cfg = cfg
  46. assert mode.lower() in ['test', 'eval'], \
  47. "mode should be 'test' or 'eval'"
  48. self.mode = mode.lower()
  49. self.optimizer = None
  50. # build MOT data loader
  51. self.dataset = cfg['{}MOTDataset'.format(self.mode.capitalize())]
  52. # build model
  53. self.model = create(cfg.architecture)
  54. if isinstance(self.model.detector, YOLOX):
  55. for k, m in self.model.named_sublayers():
  56. if isinstance(m, nn.BatchNorm2D):
  57. m._epsilon = 1e-3 # for amp(fp16)
  58. m._momentum = 0.97 # 0.03 in pytorch
  59. anno_file = self.dataset.get_anno()
  60. clsid2catid, catid2name = get_categories(
  61. self.cfg.metric, anno_file=anno_file)
  62. self.ids2names = []
  63. for k, v in catid2name.items():
  64. self.ids2names.append(v)
  65. self.status = {}
  66. self.start_epoch = 0
  67. # initial default callbacks
  68. self._init_callbacks()
  69. # initial default metrics
  70. self._init_metrics()
  71. self._reset_metrics()
  72. def _init_callbacks(self):
  73. self._callbacks = []
  74. self._compose_callback = None
  75. def _init_metrics(self):
  76. if self.mode in ['test']:
  77. self._metrics = []
  78. return
  79. if self.cfg.metric == 'MOT':
  80. self._metrics = [MOTMetric(), ]
  81. elif self.cfg.metric == 'MCMOT':
  82. self._metrics = [MCMOTMetric(self.cfg.num_classes), ]
  83. elif self.cfg.metric == 'KITTI':
  84. self._metrics = [KITTIMOTMetric(), ]
  85. else:
  86. logger.warning("Metric not support for metric type {}".format(
  87. self.cfg.metric))
  88. self._metrics = []
  89. def _reset_metrics(self):
  90. for metric in self._metrics:
  91. metric.reset()
  92. def register_callbacks(self, callbacks):
  93. callbacks = [h for h in list(callbacks) if h is not None]
  94. for c in callbacks:
  95. assert isinstance(c, Callback), \
  96. "metrics shoule be instances of subclass of Metric"
  97. self._callbacks.extend(callbacks)
  98. self._compose_callback = ComposeCallback(self._callbacks)
  99. def register_metrics(self, metrics):
  100. metrics = [m for m in list(metrics) if m is not None]
  101. for m in metrics:
  102. assert isinstance(m, Metric), \
  103. "metrics shoule be instances of subclass of Metric"
  104. self._metrics.extend(metrics)
  105. def load_weights_jde(self, weights):
  106. load_weight(self.model, weights, self.optimizer)
  107. def load_weights_sde(self, det_weights, reid_weights):
  108. with_detector = self.model.detector is not None
  109. with_reid = self.model.reid is not None
  110. if with_detector:
  111. load_weight(self.model.detector, det_weights)
  112. if with_reid:
  113. load_weight(self.model.reid, reid_weights)
  114. else:
  115. load_weight(self.model.reid, reid_weights)
  116. def _eval_seq_centertrack(self,
  117. dataloader,
  118. save_dir=None,
  119. show_image=False,
  120. frame_rate=30,
  121. draw_threshold=0):
  122. assert isinstance(self.model.tracker, CenterTracker)
  123. if save_dir:
  124. if not os.path.exists(save_dir): os.makedirs(save_dir)
  125. tracker = self.model.tracker
  126. timer = MOTTimer()
  127. frame_id = 0
  128. self.status['mode'] = 'track'
  129. self.model.eval()
  130. results = defaultdict(list) # only support single class now
  131. for step_id, data in enumerate(tqdm(dataloader)):
  132. self.status['step_id'] = step_id
  133. if step_id == 0:
  134. self.model.reset_tracking()
  135. # forward
  136. timer.tic()
  137. pred_ret = self.model(data)
  138. online_targets = tracker.update(pred_ret)
  139. online_tlwhs, online_scores, online_ids = [], [], []
  140. for t in online_targets:
  141. bbox = t['bbox']
  142. tlwh = [bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]]
  143. tscore = float(t['score'])
  144. tid = int(t['tracking_id'])
  145. if tlwh[2] * tlwh[3] > 0:
  146. online_tlwhs.append(tlwh)
  147. online_ids.append(tid)
  148. online_scores.append(tscore)
  149. timer.toc()
  150. # save results
  151. results[0].append(
  152. (frame_id + 1, online_tlwhs, online_scores, online_ids))
  153. save_vis_results(data, frame_id, online_ids, online_tlwhs,
  154. online_scores, timer.average_time, show_image,
  155. save_dir, self.cfg.num_classes, self.ids2names)
  156. frame_id += 1
  157. return results, frame_id, timer.average_time, timer.calls
  158. def _eval_seq_jde(self,
  159. dataloader,
  160. save_dir=None,
  161. show_image=False,
  162. frame_rate=30,
  163. draw_threshold=0):
  164. if save_dir:
  165. if not os.path.exists(save_dir): os.makedirs(save_dir)
  166. tracker = self.model.tracker
  167. tracker.max_time_lost = int(frame_rate / 30.0 * tracker.track_buffer)
  168. timer = MOTTimer()
  169. frame_id = 0
  170. self.status['mode'] = 'track'
  171. self.model.eval()
  172. results = defaultdict(list) # support single class and multi classes
  173. for step_id, data in enumerate(tqdm(dataloader)):
  174. self.status['step_id'] = step_id
  175. # forward
  176. timer.tic()
  177. pred_dets, pred_embs = self.model(data)
  178. pred_dets, pred_embs = pred_dets.numpy(), pred_embs.numpy()
  179. online_targets_dict = self.model.tracker.update(pred_dets,
  180. pred_embs)
  181. online_tlwhs = defaultdict(list)
  182. online_scores = defaultdict(list)
  183. online_ids = defaultdict(list)
  184. for cls_id in range(self.cfg.num_classes):
  185. online_targets = online_targets_dict[cls_id]
  186. for t in online_targets:
  187. tlwh = t.tlwh
  188. tid = t.track_id
  189. tscore = t.score
  190. if tlwh[2] * tlwh[3] <= tracker.min_box_area: continue
  191. if tracker.vertical_ratio > 0 and tlwh[2] / tlwh[
  192. 3] > tracker.vertical_ratio:
  193. continue
  194. online_tlwhs[cls_id].append(tlwh)
  195. online_ids[cls_id].append(tid)
  196. online_scores[cls_id].append(tscore)
  197. # save results
  198. results[cls_id].append(
  199. (frame_id + 1, online_tlwhs[cls_id], online_scores[cls_id],
  200. online_ids[cls_id]))
  201. timer.toc()
  202. save_vis_results(data, frame_id, online_ids, online_tlwhs,
  203. online_scores, timer.average_time, show_image,
  204. save_dir, self.cfg.num_classes, self.ids2names)
  205. frame_id += 1
  206. return results, frame_id, timer.average_time, timer.calls
  207. def _eval_seq_sde(self,
  208. dataloader,
  209. save_dir=None,
  210. show_image=False,
  211. frame_rate=30,
  212. seq_name='',
  213. scaled=False,
  214. det_file='',
  215. draw_threshold=0):
  216. if save_dir:
  217. if not os.path.exists(save_dir): os.makedirs(save_dir)
  218. use_detector = False if not self.model.detector else True
  219. use_reid = hasattr(self.model, 'reid')
  220. if use_reid and self.model.reid is not None:
  221. use_reid = True
  222. else:
  223. use_reid = False
  224. timer = MOTTimer()
  225. results = defaultdict(list)
  226. frame_id = 0
  227. self.status['mode'] = 'track'
  228. self.model.eval()
  229. if use_reid:
  230. self.model.reid.eval()
  231. if not use_detector:
  232. dets_list = load_det_results(det_file, len(dataloader))
  233. logger.info('Finish loading detection results file {}.'.format(
  234. det_file))
  235. tracker = self.model.tracker
  236. for step_id, data in enumerate(tqdm(dataloader)):
  237. self.status['step_id'] = step_id
  238. ori_image = data['ori_image'] # [bs, H, W, 3]
  239. ori_image_shape = data['ori_image'].shape[1:3]
  240. # ori_image_shape: [H, W]
  241. input_shape = data['image'].shape[2:]
  242. # input_shape: [h, w], before data transforms, set in model config
  243. im_shape = data['im_shape'][0].numpy()
  244. # im_shape: [new_h, new_w], after data transforms
  245. scale_factor = data['scale_factor'][0].numpy()
  246. empty_detections = False
  247. # when it has no detected bboxes, will not inference reid model
  248. # and if visualize, use original image instead
  249. # forward
  250. timer.tic()
  251. if not use_detector:
  252. dets = dets_list[frame_id]
  253. bbox_tlwh = np.array(dets['bbox'], dtype='float32')
  254. if bbox_tlwh.shape[0] > 0:
  255. # detector outputs: pred_cls_ids, pred_scores, pred_bboxes
  256. pred_cls_ids = np.array(dets['cls_id'], dtype='float32')
  257. pred_scores = np.array(dets['score'], dtype='float32')
  258. pred_bboxes = np.concatenate(
  259. (bbox_tlwh[:, 0:2],
  260. bbox_tlwh[:, 2:4] + bbox_tlwh[:, 0:2]),
  261. axis=1)
  262. else:
  263. logger.warning(
  264. 'Frame {} has not object, try to modify score threshold.'.
  265. format(frame_id))
  266. empty_detections = True
  267. else:
  268. outs = self.model.detector(data)
  269. outs['bbox'] = outs['bbox'].numpy()
  270. outs['bbox_num'] = outs['bbox_num'].numpy()
  271. if len(outs['bbox']) > 0 and empty_detections == False:
  272. # detector outputs: pred_cls_ids, pred_scores, pred_bboxes
  273. pred_cls_ids = outs['bbox'][:, 0:1]
  274. pred_scores = outs['bbox'][:, 1:2]
  275. if not scaled:
  276. # Note: scaled=False only in JDE YOLOv3 or other detectors
  277. # with LetterBoxResize and JDEBBoxPostProcess.
  278. #
  279. # 'scaled' means whether the coords after detector outputs
  280. # have been scaled back to the original image, set True
  281. # in general detector, set False in JDE YOLOv3.
  282. pred_bboxes = scale_coords(outs['bbox'][:, 2:],
  283. input_shape, im_shape,
  284. scale_factor)
  285. else:
  286. pred_bboxes = outs['bbox'][:, 2:]
  287. pred_dets_old = np.concatenate(
  288. (pred_cls_ids, pred_scores, pred_bboxes), axis=1)
  289. else:
  290. logger.warning(
  291. 'Frame {} has not detected object, try to modify score threshold.'.
  292. format(frame_id))
  293. empty_detections = True
  294. if not empty_detections:
  295. pred_xyxys, keep_idx = clip_box(pred_bboxes, ori_image_shape)
  296. if len(keep_idx[0]) == 0:
  297. logger.warning(
  298. 'Frame {} has not detected object left after clip_box.'.
  299. format(frame_id))
  300. empty_detections = True
  301. if empty_detections:
  302. timer.toc()
  303. # if visualize, use original image instead
  304. online_ids, online_tlwhs, online_scores = None, None, None
  305. save_vis_results(data, frame_id, online_ids, online_tlwhs,
  306. online_scores, timer.average_time, show_image,
  307. save_dir, self.cfg.num_classes, self.ids2names)
  308. frame_id += 1
  309. # thus will not inference reid model
  310. continue
  311. pred_cls_ids = pred_cls_ids[keep_idx[0]]
  312. pred_scores = pred_scores[keep_idx[0]]
  313. pred_dets = np.concatenate(
  314. (pred_cls_ids, pred_scores, pred_xyxys), axis=1)
  315. if use_reid:
  316. crops = get_crops(
  317. pred_xyxys,
  318. ori_image,
  319. w=tracker.input_size[0],
  320. h=tracker.input_size[1])
  321. crops = paddle.to_tensor(crops)
  322. data.update({'crops': crops})
  323. pred_embs = self.model(data)['embeddings'].numpy()
  324. else:
  325. pred_embs = None
  326. if isinstance(tracker, DeepSORTTracker):
  327. online_tlwhs, online_scores, online_ids = [], [], []
  328. tracker.predict()
  329. online_targets = tracker.update(pred_dets, pred_embs)
  330. for t in online_targets:
  331. if not t.is_confirmed() or t.time_since_update > 1:
  332. continue
  333. tlwh = t.to_tlwh()
  334. tscore = t.score
  335. tid = t.track_id
  336. if tscore < draw_threshold: continue
  337. if tlwh[2] * tlwh[3] <= tracker.min_box_area: continue
  338. if tracker.vertical_ratio > 0 and tlwh[2] / tlwh[
  339. 3] > tracker.vertical_ratio:
  340. continue
  341. online_tlwhs.append(tlwh)
  342. online_scores.append(tscore)
  343. online_ids.append(tid)
  344. timer.toc()
  345. # save results
  346. results[0].append(
  347. (frame_id + 1, online_tlwhs, online_scores, online_ids))
  348. save_vis_results(data, frame_id, online_ids, online_tlwhs,
  349. online_scores, timer.average_time, show_image,
  350. save_dir, self.cfg.num_classes, self.ids2names)
  351. elif isinstance(tracker, JDETracker):
  352. # trick hyperparams only used for MOTChallenge (MOT17, MOT20) Test-set
  353. tracker.track_buffer, tracker.conf_thres = get_trick_hyperparams(
  354. seq_name, tracker.track_buffer, tracker.conf_thres)
  355. online_targets_dict = tracker.update(pred_dets_old, pred_embs)
  356. online_tlwhs = defaultdict(list)
  357. online_scores = defaultdict(list)
  358. online_ids = defaultdict(list)
  359. for cls_id in range(self.cfg.num_classes):
  360. online_targets = online_targets_dict[cls_id]
  361. for t in online_targets:
  362. tlwh = t.tlwh
  363. tid = t.track_id
  364. tscore = t.score
  365. if tlwh[2] * tlwh[3] <= tracker.min_box_area: continue
  366. if tracker.vertical_ratio > 0 and tlwh[2] / tlwh[
  367. 3] > tracker.vertical_ratio:
  368. continue
  369. online_tlwhs[cls_id].append(tlwh)
  370. online_ids[cls_id].append(tid)
  371. online_scores[cls_id].append(tscore)
  372. # save results
  373. results[cls_id].append(
  374. (frame_id + 1, online_tlwhs[cls_id],
  375. online_scores[cls_id], online_ids[cls_id]))
  376. timer.toc()
  377. save_vis_results(data, frame_id, online_ids, online_tlwhs,
  378. online_scores, timer.average_time, show_image,
  379. save_dir, self.cfg.num_classes, self.ids2names)
  380. elif isinstance(tracker, OCSORTTracker):
  381. # OC_SORT Tracker
  382. online_targets = tracker.update(pred_dets_old, pred_embs)
  383. online_tlwhs = []
  384. online_ids = []
  385. online_scores = []
  386. for t in online_targets:
  387. tlwh = [t[0], t[1], t[2] - t[0], t[3] - t[1]]
  388. tscore = float(t[4])
  389. tid = int(t[5])
  390. if tlwh[2] * tlwh[3] > 0:
  391. online_tlwhs.append(tlwh)
  392. online_ids.append(tid)
  393. online_scores.append(tscore)
  394. timer.toc()
  395. # save results
  396. results[0].append(
  397. (frame_id + 1, online_tlwhs, online_scores, online_ids))
  398. save_vis_results(data, frame_id, online_ids, online_tlwhs,
  399. online_scores, timer.average_time, show_image,
  400. save_dir, self.cfg.num_classes, self.ids2names)
  401. elif isinstance(tracker, BOTSORTTracker):
  402. # BOTSORT Tracker
  403. online_targets = tracker.update(
  404. pred_dets_old, img=ori_image.numpy())
  405. online_tlwhs = []
  406. online_ids = []
  407. online_scores = []
  408. for t in online_targets:
  409. tlwh = t.tlwh
  410. tid = t.track_id
  411. tscore = t.score
  412. if tlwh[2] * tlwh[3] > 0:
  413. online_tlwhs.append(tlwh)
  414. online_ids.append(tid)
  415. online_scores.append(tscore)
  416. timer.toc()
  417. # save results
  418. results[0].append(
  419. (frame_id + 1, online_tlwhs, online_scores, online_ids))
  420. save_vis_results(data, frame_id, online_ids, online_tlwhs,
  421. online_scores, timer.average_time, show_image,
  422. save_dir, self.cfg.num_classes, self.ids2names)
  423. else:
  424. raise ValueError(tracker)
  425. frame_id += 1
  426. return results, frame_id, timer.average_time, timer.calls
  427. def mot_evaluate(self,
  428. data_root,
  429. seqs,
  430. output_dir,
  431. data_type='mot',
  432. model_type='JDE',
  433. save_images=False,
  434. save_videos=False,
  435. show_image=False,
  436. scaled=False,
  437. det_results_dir=''):
  438. if not os.path.exists(output_dir): os.makedirs(output_dir)
  439. result_root = os.path.join(output_dir, 'mot_results')
  440. if not os.path.exists(result_root): os.makedirs(result_root)
  441. assert data_type in MOT_DATA_TYPE, \
  442. "data_type should be 'mot', 'mcmot' or 'kitti'"
  443. assert model_type in MOT_ARCH, \
  444. "model_type should be 'JDE', 'DeepSORT', 'FairMOT' or 'ByteTrack'"
  445. # run tracking
  446. n_frame = 0
  447. timer_avgs, timer_calls = [], []
  448. for seq in seqs:
  449. infer_dir = os.path.join(data_root, seq)
  450. if not os.path.exists(infer_dir) or not os.path.isdir(infer_dir):
  451. logger.warning("Seq {} error, {} has no images.".format(
  452. seq, infer_dir))
  453. continue
  454. if os.path.exists(os.path.join(infer_dir, 'img1')):
  455. infer_dir = os.path.join(infer_dir, 'img1')
  456. frame_rate = 30
  457. seqinfo = os.path.join(data_root, seq, 'seqinfo.ini')
  458. if os.path.exists(seqinfo):
  459. meta_info = open(seqinfo).read()
  460. frame_rate = int(meta_info[meta_info.find('frameRate') + 10:
  461. meta_info.find('\nseqLength')])
  462. save_dir = os.path.join(output_dir, 'mot_outputs',
  463. seq) if save_images or save_videos else None
  464. logger.info('Evaluate seq: {}'.format(seq))
  465. self.dataset.set_images(self.get_infer_images(infer_dir))
  466. dataloader = create('EvalMOTReader')(self.dataset, 0)
  467. result_filename = os.path.join(result_root, '{}.txt'.format(seq))
  468. with paddle.no_grad():
  469. if model_type in MOT_ARCH_JDE:
  470. results, nf, ta, tc = self._eval_seq_jde(
  471. dataloader,
  472. save_dir=save_dir,
  473. show_image=show_image,
  474. frame_rate=frame_rate)
  475. elif model_type in MOT_ARCH_SDE:
  476. results, nf, ta, tc = self._eval_seq_sde(
  477. dataloader,
  478. save_dir=save_dir,
  479. show_image=show_image,
  480. frame_rate=frame_rate,
  481. seq_name=seq,
  482. scaled=scaled,
  483. det_file=os.path.join(det_results_dir,
  484. '{}.txt'.format(seq)))
  485. elif model_type == 'CenterTrack':
  486. results, nf, ta, tc = self._eval_seq_centertrack(
  487. dataloader,
  488. save_dir=save_dir,
  489. show_image=show_image,
  490. frame_rate=frame_rate)
  491. else:
  492. raise ValueError(model_type)
  493. write_mot_results(result_filename, results, data_type,
  494. self.cfg.num_classes)
  495. n_frame += nf
  496. timer_avgs.append(ta)
  497. timer_calls.append(tc)
  498. if save_videos:
  499. output_video_path = os.path.join(save_dir, '..',
  500. '{}_vis.mp4'.format(seq))
  501. cmd_str = 'ffmpeg -f image2 -i {}/%05d.jpg {}'.format(
  502. save_dir, output_video_path)
  503. os.system(cmd_str)
  504. logger.info('Save video in {}.'.format(output_video_path))
  505. # update metrics
  506. for metric in self._metrics:
  507. metric.update(data_root, seq, data_type, result_root,
  508. result_filename)
  509. timer_avgs = np.asarray(timer_avgs)
  510. timer_calls = np.asarray(timer_calls)
  511. all_time = np.dot(timer_avgs, timer_calls)
  512. avg_time = all_time / np.sum(timer_calls)
  513. logger.info('Time elapsed: {:.2f} seconds, FPS: {:.2f}'.format(
  514. all_time, 1.0 / avg_time))
  515. # accumulate metric to log out
  516. for metric in self._metrics:
  517. metric.accumulate()
  518. metric.log()
  519. # reset metric states for metric may performed multiple times
  520. self._reset_metrics()
  521. def get_infer_images(self, infer_dir):
  522. assert infer_dir is None or os.path.isdir(infer_dir), \
  523. "{} is not a directory".format(infer_dir)
  524. images = set()
  525. assert os.path.isdir(infer_dir), \
  526. "infer_dir {} is not a directory".format(infer_dir)
  527. exts = ['jpg', 'jpeg', 'png', 'bmp']
  528. exts += [ext.upper() for ext in exts]
  529. for ext in exts:
  530. images.update(glob.glob('{}/*.{}'.format(infer_dir, ext)))
  531. images = list(images)
  532. images.sort()
  533. assert len(images) > 0, "no image found in {}".format(infer_dir)
  534. logger.info("Found {} inference images in total.".format(len(images)))
  535. return images
  536. def mot_predict_seq(self,
  537. video_file,
  538. frame_rate,
  539. image_dir,
  540. output_dir,
  541. data_type='mot',
  542. model_type='JDE',
  543. save_images=False,
  544. save_videos=True,
  545. show_image=False,
  546. scaled=False,
  547. det_results_dir='',
  548. draw_threshold=0.5):
  549. assert video_file is not None or image_dir is not None, \
  550. "--video_file or --image_dir should be set."
  551. assert video_file is None or os.path.isfile(video_file), \
  552. "{} is not a file".format(video_file)
  553. assert image_dir is None or os.path.isdir(image_dir), \
  554. "{} is not a directory".format(image_dir)
  555. if not os.path.exists(output_dir): os.makedirs(output_dir)
  556. result_root = os.path.join(output_dir, 'mot_results')
  557. if not os.path.exists(result_root): os.makedirs(result_root)
  558. assert data_type in MOT_DATA_TYPE, \
  559. "data_type should be 'mot', 'mcmot' or 'kitti'"
  560. assert model_type in MOT_ARCH, \
  561. "model_type should be 'JDE', 'DeepSORT', 'FairMOT' or 'ByteTrack'"
  562. # run tracking
  563. if video_file:
  564. seq = video_file.split('/')[-1].split('.')[0]
  565. self.dataset.set_video(video_file, frame_rate)
  566. logger.info('Starting tracking video {}'.format(video_file))
  567. elif image_dir:
  568. seq = image_dir.split('/')[-1].split('.')[0]
  569. if os.path.exists(os.path.join(image_dir, 'img1')):
  570. image_dir = os.path.join(image_dir, 'img1')
  571. images = [
  572. '{}/{}'.format(image_dir, x) for x in os.listdir(image_dir)
  573. ]
  574. images.sort()
  575. self.dataset.set_images(images)
  576. logger.info('Starting tracking folder {}, found {} images'.format(
  577. image_dir, len(images)))
  578. else:
  579. raise ValueError('--video_file or --image_dir should be set.')
  580. save_dir = os.path.join(output_dir, 'mot_outputs',
  581. seq) if save_images or save_videos else None
  582. dataloader = create('TestMOTReader')(self.dataset, 0)
  583. result_filename = os.path.join(result_root, '{}.txt'.format(seq))
  584. if frame_rate == -1:
  585. frame_rate = self.dataset.frame_rate
  586. with paddle.no_grad():
  587. if model_type in MOT_ARCH_JDE:
  588. results, nf, ta, tc = self._eval_seq_jde(
  589. dataloader,
  590. save_dir=save_dir,
  591. show_image=show_image,
  592. frame_rate=frame_rate,
  593. draw_threshold=draw_threshold)
  594. elif model_type in MOT_ARCH_SDE:
  595. results, nf, ta, tc = self._eval_seq_sde(
  596. dataloader,
  597. save_dir=save_dir,
  598. show_image=show_image,
  599. frame_rate=frame_rate,
  600. seq_name=seq,
  601. scaled=scaled,
  602. det_file=os.path.join(det_results_dir,
  603. '{}.txt'.format(seq)),
  604. draw_threshold=draw_threshold)
  605. elif model_type == 'CenterTrack':
  606. results, nf, ta, tc = self._eval_seq_centertrack(
  607. dataloader,
  608. save_dir=save_dir,
  609. show_image=show_image,
  610. frame_rate=frame_rate)
  611. else:
  612. raise ValueError(model_type)
  613. if save_videos:
  614. output_video_path = os.path.join(save_dir, '..',
  615. '{}_vis.mp4'.format(seq))
  616. cmd_str = 'ffmpeg -f image2 -i {}/%05d.jpg {}'.format(
  617. save_dir, output_video_path)
  618. os.system(cmd_str)
  619. logger.info('Save video in {}'.format(output_video_path))
  620. write_mot_results(result_filename, results, data_type,
  621. self.cfg.num_classes)
  622. def get_trick_hyperparams(video_name, ori_buffer, ori_thresh):
  623. if video_name[:3] != 'MOT':
  624. # only used for MOTChallenge (MOT17, MOT20) Test-set
  625. return ori_buffer, ori_thresh
  626. video_name = video_name[:8]
  627. if 'MOT17-05' in video_name:
  628. track_buffer = 14
  629. elif 'MOT17-13' in video_name:
  630. track_buffer = 25
  631. else:
  632. track_buffer = ori_buffer
  633. if 'MOT17-01' in video_name:
  634. track_thresh = 0.65
  635. elif 'MOT17-06' in video_name:
  636. track_thresh = 0.65
  637. elif 'MOT17-12' in video_name:
  638. track_thresh = 0.7
  639. elif 'MOT17-14' in video_name:
  640. track_thresh = 0.67
  641. else:
  642. track_thresh = ori_thresh
  643. if 'MOT20-06' in video_name or 'MOT20-08' in video_name:
  644. track_thresh = 0.3
  645. else:
  646. track_thresh = ori_thresh
  647. return track_buffer, ori_thresh