mot_metrics.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  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 copy
  19. import sys
  20. import math
  21. from collections import defaultdict
  22. import numpy as np
  23. from ppdet.modeling.bbox_utils import bbox_iou_np_expand
  24. from .map_utils import ap_per_class
  25. from .metrics import Metric
  26. from .munkres import Munkres
  27. try:
  28. import motmetrics as mm
  29. mm.lap.default_solver = 'lap'
  30. except:
  31. print(
  32. 'Warning: Unable to use MOT metric, please install motmetrics, for example: `pip install motmetrics`, see https://github.com/longcw/py-motmetrics'
  33. )
  34. pass
  35. from ppdet.utils.logger import setup_logger
  36. logger = setup_logger(__name__)
  37. __all__ = ['MOTEvaluator', 'MOTMetric', 'JDEDetMetric', 'KITTIMOTMetric']
  38. def read_mot_results(filename, is_gt=False, is_ignore=False):
  39. valid_label = [1]
  40. ignore_labels = [2, 7, 8, 12] # only in motchallenge datasets like 'MOT16'
  41. if is_gt:
  42. logger.info(
  43. "In MOT16/17 dataset the valid_label of ground truth is '{}', "
  44. "in other dataset it should be '0' for single classs MOT.".format(
  45. valid_label[0]))
  46. results_dict = dict()
  47. if os.path.isfile(filename):
  48. with open(filename, 'r') as f:
  49. for line in f.readlines():
  50. linelist = line.split(',')
  51. if len(linelist) < 7:
  52. continue
  53. fid = int(linelist[0])
  54. if fid < 1:
  55. continue
  56. results_dict.setdefault(fid, list())
  57. if is_gt:
  58. label = int(float(linelist[7]))
  59. mark = int(float(linelist[6]))
  60. if mark == 0 or label not in valid_label:
  61. continue
  62. score = 1
  63. elif is_ignore:
  64. if 'MOT16-' in filename or 'MOT17-' in filename or 'MOT15-' in filename or 'MOT20-' in filename:
  65. label = int(float(linelist[7]))
  66. vis_ratio = float(linelist[8])
  67. if label not in ignore_labels and vis_ratio >= 0:
  68. continue
  69. else:
  70. continue
  71. score = 1
  72. else:
  73. score = float(linelist[6])
  74. tlwh = tuple(map(float, linelist[2:6]))
  75. target_id = int(linelist[1])
  76. results_dict[fid].append((tlwh, target_id, score))
  77. return results_dict
  78. """
  79. MOT dataset label list, see in https://motchallenge.net
  80. labels={'ped', ... % 1
  81. 'person_on_vhcl', ... % 2
  82. 'car', ... % 3
  83. 'bicycle', ... % 4
  84. 'mbike', ... % 5
  85. 'non_mot_vhcl', ... % 6
  86. 'static_person', ... % 7
  87. 'distractor', ... % 8
  88. 'occluder', ... % 9
  89. 'occluder_on_grnd', ... % 10
  90. 'occluder_full', ... % 11
  91. 'reflection', ... % 12
  92. 'crowd' ... % 13
  93. };
  94. """
  95. def unzip_objs(objs):
  96. if len(objs) > 0:
  97. tlwhs, ids, scores = zip(*objs)
  98. else:
  99. tlwhs, ids, scores = [], [], []
  100. tlwhs = np.asarray(tlwhs, dtype=float).reshape(-1, 4)
  101. return tlwhs, ids, scores
  102. class MOTEvaluator(object):
  103. def __init__(self, data_root, seq_name, data_type):
  104. self.data_root = data_root
  105. self.seq_name = seq_name
  106. self.data_type = data_type
  107. self.load_annotations()
  108. try:
  109. import motmetrics as mm
  110. mm.lap.default_solver = 'lap'
  111. except Exception as e:
  112. raise RuntimeError(
  113. 'Unable to use MOT metric, please install motmetrics, for example: `pip install motmetrics`, see https://github.com/longcw/py-motmetrics'
  114. )
  115. self.reset_accumulator()
  116. def load_annotations(self):
  117. assert self.data_type == 'mot'
  118. gt_filename = os.path.join(self.data_root, self.seq_name, 'gt',
  119. 'gt.txt')
  120. if not os.path.exists(gt_filename):
  121. logger.warning(
  122. "gt_filename '{}' of MOTEvaluator is not exist, so the MOTA will be -INF."
  123. )
  124. self.gt_frame_dict = read_mot_results(gt_filename, is_gt=True)
  125. self.gt_ignore_frame_dict = read_mot_results(
  126. gt_filename, is_ignore=True)
  127. def reset_accumulator(self):
  128. self.acc = mm.MOTAccumulator(auto_id=True)
  129. def eval_frame(self, frame_id, trk_tlwhs, trk_ids, rtn_events=False):
  130. # results
  131. trk_tlwhs = np.copy(trk_tlwhs)
  132. trk_ids = np.copy(trk_ids)
  133. # gts
  134. gt_objs = self.gt_frame_dict.get(frame_id, [])
  135. gt_tlwhs, gt_ids = unzip_objs(gt_objs)[:2]
  136. # ignore boxes
  137. ignore_objs = self.gt_ignore_frame_dict.get(frame_id, [])
  138. ignore_tlwhs = unzip_objs(ignore_objs)[0]
  139. # remove ignored results
  140. keep = np.ones(len(trk_tlwhs), dtype=bool)
  141. iou_distance = mm.distances.iou_matrix(
  142. ignore_tlwhs, trk_tlwhs, max_iou=0.5)
  143. if len(iou_distance) > 0:
  144. match_is, match_js = mm.lap.linear_sum_assignment(iou_distance)
  145. match_is, match_js = map(lambda a: np.asarray(a, dtype=int), [match_is, match_js])
  146. match_ious = iou_distance[match_is, match_js]
  147. match_js = np.asarray(match_js, dtype=int)
  148. match_js = match_js[np.logical_not(np.isnan(match_ious))]
  149. keep[match_js] = False
  150. trk_tlwhs = trk_tlwhs[keep]
  151. trk_ids = trk_ids[keep]
  152. # get distance matrix
  153. iou_distance = mm.distances.iou_matrix(gt_tlwhs, trk_tlwhs, max_iou=0.5)
  154. # acc
  155. self.acc.update(gt_ids, trk_ids, iou_distance)
  156. if rtn_events and iou_distance.size > 0 and hasattr(self.acc,
  157. 'last_mot_events'):
  158. events = self.acc.last_mot_events # only supported by https://github.com/longcw/py-motmetrics
  159. else:
  160. events = None
  161. return events
  162. def eval_file(self, filename):
  163. self.reset_accumulator()
  164. result_frame_dict = read_mot_results(filename, is_gt=False)
  165. frames = sorted(list(set(result_frame_dict.keys())))
  166. for frame_id in frames:
  167. trk_objs = result_frame_dict.get(frame_id, [])
  168. trk_tlwhs, trk_ids = unzip_objs(trk_objs)[:2]
  169. self.eval_frame(frame_id, trk_tlwhs, trk_ids, rtn_events=False)
  170. return self.acc
  171. @staticmethod
  172. def get_summary(accs,
  173. names,
  174. metrics=('mota', 'num_switches', 'idp', 'idr', 'idf1',
  175. 'precision', 'recall')):
  176. names = copy.deepcopy(names)
  177. if metrics is None:
  178. metrics = mm.metrics.motchallenge_metrics
  179. metrics = copy.deepcopy(metrics)
  180. mh = mm.metrics.create()
  181. summary = mh.compute_many(
  182. accs, metrics=metrics, names=names, generate_overall=True)
  183. return summary
  184. @staticmethod
  185. def save_summary(summary, filename):
  186. import pandas as pd
  187. writer = pd.ExcelWriter(filename)
  188. summary.to_excel(writer)
  189. writer.save()
  190. class MOTMetric(Metric):
  191. def __init__(self, save_summary=False):
  192. self.save_summary = save_summary
  193. self.MOTEvaluator = MOTEvaluator
  194. self.result_root = None
  195. self.reset()
  196. def reset(self):
  197. self.accs = []
  198. self.seqs = []
  199. def update(self, data_root, seq, data_type, result_root, result_filename):
  200. evaluator = self.MOTEvaluator(data_root, seq, data_type)
  201. self.accs.append(evaluator.eval_file(result_filename))
  202. self.seqs.append(seq)
  203. self.result_root = result_root
  204. def accumulate(self):
  205. metrics = mm.metrics.motchallenge_metrics
  206. mh = mm.metrics.create()
  207. summary = self.MOTEvaluator.get_summary(self.accs, self.seqs, metrics)
  208. self.strsummary = mm.io.render_summary(
  209. summary,
  210. formatters=mh.formatters,
  211. namemap=mm.io.motchallenge_metric_names)
  212. if self.save_summary:
  213. self.MOTEvaluator.save_summary(
  214. summary, os.path.join(self.result_root, 'summary.xlsx'))
  215. def log(self):
  216. print(self.strsummary)
  217. def get_results(self):
  218. return self.strsummary
  219. class JDEDetMetric(Metric):
  220. # Note this detection AP metric is different from COCOMetric or VOCMetric,
  221. # and the bboxes coordinates are not scaled to the original image
  222. def __init__(self, overlap_thresh=0.5):
  223. self.overlap_thresh = overlap_thresh
  224. self.reset()
  225. def reset(self):
  226. self.AP_accum = np.zeros(1)
  227. self.AP_accum_count = np.zeros(1)
  228. def update(self, inputs, outputs):
  229. bboxes = outputs['bbox'][:, 2:].numpy()
  230. scores = outputs['bbox'][:, 1].numpy()
  231. labels = outputs['bbox'][:, 0].numpy()
  232. bbox_lengths = outputs['bbox_num'].numpy()
  233. if bboxes.shape[0] == 1 and bboxes.sum() == 0.0:
  234. return
  235. gt_boxes = inputs['gt_bbox'].numpy()[0]
  236. gt_labels = inputs['gt_class'].numpy()[0]
  237. if gt_labels.shape[0] == 0:
  238. return
  239. correct = []
  240. detected = []
  241. for i in range(bboxes.shape[0]):
  242. obj_pred = 0
  243. pred_bbox = bboxes[i].reshape(1, 4)
  244. # Compute iou with target boxes
  245. iou = bbox_iou_np_expand(pred_bbox, gt_boxes, x1y1x2y2=True)[0]
  246. # Extract index of largest overlap
  247. best_i = np.argmax(iou)
  248. # If overlap exceeds threshold and classification is correct mark as correct
  249. if iou[best_i] > self.overlap_thresh and obj_pred == gt_labels[
  250. best_i] and best_i not in detected:
  251. correct.append(1)
  252. detected.append(best_i)
  253. else:
  254. correct.append(0)
  255. # Compute Average Precision (AP) per class
  256. target_cls = list(gt_labels.T[0])
  257. AP, AP_class, R, P = ap_per_class(
  258. tp=correct,
  259. conf=scores,
  260. pred_cls=np.zeros_like(scores),
  261. target_cls=target_cls)
  262. self.AP_accum_count += np.bincount(AP_class, minlength=1)
  263. self.AP_accum += np.bincount(AP_class, minlength=1, weights=AP)
  264. def accumulate(self):
  265. logger.info("Accumulating evaluatation results...")
  266. self.map_stat = self.AP_accum[0] / (self.AP_accum_count[0] + 1E-16)
  267. def log(self):
  268. map_stat = 100. * self.map_stat
  269. logger.info("mAP({:.2f}) = {:.2f}%".format(self.overlap_thresh,
  270. map_stat))
  271. def get_results(self):
  272. return self.map_stat
  273. """
  274. Following code is borrow from https://github.com/xingyizhou/CenterTrack/blob/master/src/tools/eval_kitti_track/evaluate_tracking.py
  275. """
  276. class tData:
  277. """
  278. Utility class to load data.
  279. """
  280. def __init__(self,frame=-1,obj_type="unset",truncation=-1,occlusion=-1,\
  281. obs_angle=-10,x1=-1,y1=-1,x2=-1,y2=-1,w=-1,h=-1,l=-1,\
  282. X=-1000,Y=-1000,Z=-1000,yaw=-10,score=-1000,track_id=-1):
  283. """
  284. Constructor, initializes the object given the parameters.
  285. """
  286. self.frame = frame
  287. self.track_id = track_id
  288. self.obj_type = obj_type
  289. self.truncation = truncation
  290. self.occlusion = occlusion
  291. self.obs_angle = obs_angle
  292. self.x1 = x1
  293. self.y1 = y1
  294. self.x2 = x2
  295. self.y2 = y2
  296. self.w = w
  297. self.h = h
  298. self.l = l
  299. self.X = X
  300. self.Y = Y
  301. self.Z = Z
  302. self.yaw = yaw
  303. self.score = score
  304. self.ignored = False
  305. self.valid = False
  306. self.tracker = -1
  307. def __str__(self):
  308. attrs = vars(self)
  309. return '\n'.join("%s: %s" % item for item in attrs.items())
  310. class KITTIEvaluation(object):
  311. """ KITTI tracking statistics (CLEAR MOT, id-switches, fragments, ML/PT/MT, precision/recall)
  312. MOTA - Multi-object tracking accuracy in [0,100]
  313. MOTP - Multi-object tracking precision in [0,100] (3D) / [td,100] (2D)
  314. MOTAL - Multi-object tracking accuracy in [0,100] with log10(id-switches)
  315. id-switches - number of id switches
  316. fragments - number of fragmentations
  317. MT, PT, ML - number of mostly tracked, partially tracked and mostly lost trajectories
  318. recall - recall = percentage of detected targets
  319. precision - precision = percentage of correctly detected targets
  320. FAR - number of false alarms per frame
  321. falsepositives - number of false positives (FP)
  322. missed - number of missed targets (FN)
  323. """
  324. def __init__(self, result_path, gt_path, min_overlap=0.5, max_truncation = 0,\
  325. min_height = 25, max_occlusion = 2, cls="car",\
  326. n_frames=[], seqs=[], n_sequences=0):
  327. # get number of sequences and
  328. # get number of frames per sequence from test mapping
  329. # (created while extracting the benchmark)
  330. self.gt_path = os.path.join(gt_path, "../labels")
  331. self.n_frames = n_frames
  332. self.sequence_name = seqs
  333. self.n_sequences = n_sequences
  334. self.cls = cls # class to evaluate, i.e. pedestrian or car
  335. self.result_path = result_path
  336. # statistics and numbers for evaluation
  337. self.n_gt = 0 # number of ground truth detections minus ignored false negatives and true positives
  338. self.n_igt = 0 # number of ignored ground truth detections
  339. self.n_gts = [
  340. ] # number of ground truth detections minus ignored false negatives and true positives PER SEQUENCE
  341. self.n_igts = [
  342. ] # number of ground ignored truth detections PER SEQUENCE
  343. self.n_gt_trajectories = 0
  344. self.n_gt_seq = []
  345. self.n_tr = 0 # number of tracker detections minus ignored tracker detections
  346. self.n_trs = [
  347. ] # number of tracker detections minus ignored tracker detections PER SEQUENCE
  348. self.n_itr = 0 # number of ignored tracker detections
  349. self.n_itrs = [] # number of ignored tracker detections PER SEQUENCE
  350. self.n_igttr = 0 # number of ignored ground truth detections where the corresponding associated tracker detection is also ignored
  351. self.n_tr_trajectories = 0
  352. self.n_tr_seq = []
  353. self.MOTA = 0
  354. self.MOTP = 0
  355. self.MOTAL = 0
  356. self.MODA = 0
  357. self.MODP = 0
  358. self.MODP_t = []
  359. self.recall = 0
  360. self.precision = 0
  361. self.F1 = 0
  362. self.FAR = 0
  363. self.total_cost = 0
  364. self.itp = 0 # number of ignored true positives
  365. self.itps = [] # number of ignored true positives PER SEQUENCE
  366. self.tp = 0 # number of true positives including ignored true positives!
  367. self.tps = [
  368. ] # number of true positives including ignored true positives PER SEQUENCE
  369. self.fn = 0 # number of false negatives WITHOUT ignored false negatives
  370. self.fns = [
  371. ] # number of false negatives WITHOUT ignored false negatives PER SEQUENCE
  372. self.ifn = 0 # number of ignored false negatives
  373. self.ifns = [] # number of ignored false negatives PER SEQUENCE
  374. self.fp = 0 # number of false positives
  375. # a bit tricky, the number of ignored false negatives and ignored true positives
  376. # is subtracted, but if both tracker detection and ground truth detection
  377. # are ignored this number is added again to avoid double counting
  378. self.fps = [] # above PER SEQUENCE
  379. self.mme = 0
  380. self.fragments = 0
  381. self.id_switches = 0
  382. self.MT = 0
  383. self.PT = 0
  384. self.ML = 0
  385. self.min_overlap = min_overlap # minimum bounding box overlap for 3rd party metrics
  386. self.max_truncation = max_truncation # maximum truncation of an object for evaluation
  387. self.max_occlusion = max_occlusion # maximum occlusion of an object for evaluation
  388. self.min_height = min_height # minimum height of an object for evaluation
  389. self.n_sample_points = 500
  390. # this should be enough to hold all groundtruth trajectories
  391. # is expanded if necessary and reduced in any case
  392. self.gt_trajectories = [[] for x in range(self.n_sequences)]
  393. self.ign_trajectories = [[] for x in range(self.n_sequences)]
  394. def loadGroundtruth(self):
  395. try:
  396. self._loadData(self.gt_path, cls=self.cls, loading_groundtruth=True)
  397. except IOError:
  398. return False
  399. return True
  400. def loadTracker(self):
  401. try:
  402. if not self._loadData(
  403. self.result_path, cls=self.cls, loading_groundtruth=False):
  404. return False
  405. except IOError:
  406. return False
  407. return True
  408. def _loadData(self,
  409. root_dir,
  410. cls,
  411. min_score=-1000,
  412. loading_groundtruth=False):
  413. """
  414. Generic loader for ground truth and tracking data.
  415. Use loadGroundtruth() or loadTracker() to load this data.
  416. Loads detections in KITTI format from textfiles.
  417. """
  418. # construct objectDetections object to hold detection data
  419. t_data = tData()
  420. data = []
  421. eval_2d = True
  422. eval_3d = True
  423. seq_data = []
  424. n_trajectories = 0
  425. n_trajectories_seq = []
  426. for seq, s_name in enumerate(self.sequence_name):
  427. i = 0
  428. filename = os.path.join(root_dir, "%s.txt" % s_name)
  429. f = open(filename, "r")
  430. f_data = [
  431. [] for x in range(self.n_frames[seq])
  432. ] # current set has only 1059 entries, sufficient length is checked anyway
  433. ids = []
  434. n_in_seq = 0
  435. id_frame_cache = []
  436. for line in f:
  437. # KITTI tracking benchmark data format:
  438. # (frame,tracklet_id,objectType,truncation,occlusion,alpha,x1,y1,x2,y2,h,w,l,X,Y,Z,ry)
  439. line = line.strip()
  440. fields = line.split(" ")
  441. # classes that should be loaded (ignored neighboring classes)
  442. if "car" in cls.lower():
  443. classes = ["car", "van"]
  444. elif "pedestrian" in cls.lower():
  445. classes = ["pedestrian", "person_sitting"]
  446. else:
  447. classes = [cls.lower()]
  448. classes += ["dontcare"]
  449. if not any([s for s in classes if s in fields[2].lower()]):
  450. continue
  451. # get fields from table
  452. t_data.frame = int(float(fields[0])) # frame
  453. t_data.track_id = int(float(fields[1])) # id
  454. t_data.obj_type = fields[
  455. 2].lower() # object type [car, pedestrian, cyclist, ...]
  456. t_data.truncation = int(
  457. float(fields[3])) # truncation [-1,0,1,2]
  458. t_data.occlusion = int(
  459. float(fields[4])) # occlusion [-1,0,1,2]
  460. t_data.obs_angle = float(fields[5]) # observation angle [rad]
  461. t_data.x1 = float(fields[6]) # left [px]
  462. t_data.y1 = float(fields[7]) # top [px]
  463. t_data.x2 = float(fields[8]) # right [px]
  464. t_data.y2 = float(fields[9]) # bottom [px]
  465. t_data.h = float(fields[10]) # height [m]
  466. t_data.w = float(fields[11]) # width [m]
  467. t_data.l = float(fields[12]) # length [m]
  468. t_data.X = float(fields[13]) # X [m]
  469. t_data.Y = float(fields[14]) # Y [m]
  470. t_data.Z = float(fields[15]) # Z [m]
  471. t_data.yaw = float(fields[16]) # yaw angle [rad]
  472. if not loading_groundtruth:
  473. if len(fields) == 17:
  474. t_data.score = -1
  475. elif len(fields) == 18:
  476. t_data.score = float(fields[17]) # detection score
  477. else:
  478. logger.info("file is not in KITTI format")
  479. return
  480. # do not consider objects marked as invalid
  481. if t_data.track_id is -1 and t_data.obj_type != "dontcare":
  482. continue
  483. idx = t_data.frame
  484. # check if length for frame data is sufficient
  485. if idx >= len(f_data):
  486. print("extend f_data", idx, len(f_data))
  487. f_data += [[] for x in range(max(500, idx - len(f_data)))]
  488. try:
  489. id_frame = (t_data.frame, t_data.track_id)
  490. if id_frame in id_frame_cache and not loading_groundtruth:
  491. logger.info(
  492. "track ids are not unique for sequence %d: frame %d"
  493. % (seq, t_data.frame))
  494. logger.info(
  495. "track id %d occurred at least twice for this frame"
  496. % t_data.track_id)
  497. logger.info("Exiting...")
  498. #continue # this allows to evaluate non-unique result files
  499. return False
  500. id_frame_cache.append(id_frame)
  501. f_data[t_data.frame].append(copy.copy(t_data))
  502. except:
  503. print(len(f_data), idx)
  504. raise
  505. if t_data.track_id not in ids and t_data.obj_type != "dontcare":
  506. ids.append(t_data.track_id)
  507. n_trajectories += 1
  508. n_in_seq += 1
  509. # check if uploaded data provides information for 2D and 3D evaluation
  510. if not loading_groundtruth and eval_2d is True and (
  511. t_data.x1 == -1 or t_data.x2 == -1 or t_data.y1 == -1 or
  512. t_data.y2 == -1):
  513. eval_2d = False
  514. if not loading_groundtruth and eval_3d is True and (
  515. t_data.X == -1000 or t_data.Y == -1000 or
  516. t_data.Z == -1000):
  517. eval_3d = False
  518. # only add existing frames
  519. n_trajectories_seq.append(n_in_seq)
  520. seq_data.append(f_data)
  521. f.close()
  522. if not loading_groundtruth:
  523. self.tracker = seq_data
  524. self.n_tr_trajectories = n_trajectories
  525. self.eval_2d = eval_2d
  526. self.eval_3d = eval_3d
  527. self.n_tr_seq = n_trajectories_seq
  528. if self.n_tr_trajectories == 0:
  529. return False
  530. else:
  531. # split ground truth and DontCare areas
  532. self.dcareas = []
  533. self.groundtruth = []
  534. for seq_idx in range(len(seq_data)):
  535. seq_gt = seq_data[seq_idx]
  536. s_g, s_dc = [], []
  537. for f in range(len(seq_gt)):
  538. all_gt = seq_gt[f]
  539. g, dc = [], []
  540. for gg in all_gt:
  541. if gg.obj_type == "dontcare":
  542. dc.append(gg)
  543. else:
  544. g.append(gg)
  545. s_g.append(g)
  546. s_dc.append(dc)
  547. self.dcareas.append(s_dc)
  548. self.groundtruth.append(s_g)
  549. self.n_gt_seq = n_trajectories_seq
  550. self.n_gt_trajectories = n_trajectories
  551. return True
  552. def boxoverlap(self, a, b, criterion="union"):
  553. """
  554. boxoverlap computes intersection over union for bbox a and b in KITTI format.
  555. If the criterion is 'union', overlap = (a inter b) / a union b).
  556. If the criterion is 'a', overlap = (a inter b) / a, where b should be a dontcare area.
  557. """
  558. x1 = max(a.x1, b.x1)
  559. y1 = max(a.y1, b.y1)
  560. x2 = min(a.x2, b.x2)
  561. y2 = min(a.y2, b.y2)
  562. w = x2 - x1
  563. h = y2 - y1
  564. if w <= 0. or h <= 0.:
  565. return 0.
  566. inter = w * h
  567. aarea = (a.x2 - a.x1) * (a.y2 - a.y1)
  568. barea = (b.x2 - b.x1) * (b.y2 - b.y1)
  569. # intersection over union overlap
  570. if criterion.lower() == "union":
  571. o = inter / float(aarea + barea - inter)
  572. elif criterion.lower() == "a":
  573. o = float(inter) / float(aarea)
  574. else:
  575. raise TypeError("Unkown type for criterion")
  576. return o
  577. def compute3rdPartyMetrics(self):
  578. """
  579. Computes the metrics defined in
  580. - Stiefelhagen 2008: Evaluating Multiple Object Tracking Performance: The CLEAR MOT Metrics
  581. MOTA, MOTAL, MOTP
  582. - Nevatia 2008: Global Data Association for Multi-Object Tracking Using Network Flows
  583. MT/PT/ML
  584. """
  585. # construct Munkres object for Hungarian Method association
  586. hm = Munkres()
  587. max_cost = 1e9
  588. # go through all frames and associate ground truth and tracker results
  589. # groundtruth and tracker contain lists for every single frame containing lists of KITTI format detections
  590. fr, ids = 0, 0
  591. for seq_idx in range(len(self.groundtruth)):
  592. seq_gt = self.groundtruth[seq_idx]
  593. seq_dc = self.dcareas[seq_idx] # don't care areas
  594. seq_tracker = self.tracker[seq_idx]
  595. seq_trajectories = defaultdict(list)
  596. seq_ignored = defaultdict(list)
  597. # statistics over the current sequence, check the corresponding
  598. # variable comments in __init__ to get their meaning
  599. seqtp = 0
  600. seqitp = 0
  601. seqfn = 0
  602. seqifn = 0
  603. seqfp = 0
  604. seqigt = 0
  605. seqitr = 0
  606. last_ids = [[], []]
  607. n_gts = 0
  608. n_trs = 0
  609. for f in range(len(seq_gt)):
  610. g = seq_gt[f]
  611. dc = seq_dc[f]
  612. t = seq_tracker[f]
  613. # counting total number of ground truth and tracker objects
  614. self.n_gt += len(g)
  615. self.n_tr += len(t)
  616. n_gts += len(g)
  617. n_trs += len(t)
  618. # use hungarian method to associate, using boxoverlap 0..1 as cost
  619. # build cost matrix
  620. cost_matrix = []
  621. this_ids = [[], []]
  622. for gg in g:
  623. # save current ids
  624. this_ids[0].append(gg.track_id)
  625. this_ids[1].append(-1)
  626. gg.tracker = -1
  627. gg.id_switch = 0
  628. gg.fragmentation = 0
  629. cost_row = []
  630. for tt in t:
  631. # overlap == 1 is cost ==0
  632. c = 1 - self.boxoverlap(gg, tt)
  633. # gating for boxoverlap
  634. if c <= self.min_overlap:
  635. cost_row.append(c)
  636. else:
  637. cost_row.append(max_cost) # = 1e9
  638. cost_matrix.append(cost_row)
  639. # all ground truth trajectories are initially not associated
  640. # extend groundtruth trajectories lists (merge lists)
  641. seq_trajectories[gg.track_id].append(-1)
  642. seq_ignored[gg.track_id].append(False)
  643. if len(g) is 0:
  644. cost_matrix = [[]]
  645. # associate
  646. association_matrix = hm.compute(cost_matrix)
  647. # tmp variables for sanity checks and MODP computation
  648. tmptp = 0
  649. tmpfp = 0
  650. tmpfn = 0
  651. tmpc = 0 # this will sum up the overlaps for all true positives
  652. tmpcs = [0] * len(
  653. g) # this will save the overlaps for all true positives
  654. # the reason is that some true positives might be ignored
  655. # later such that the corrsponding overlaps can
  656. # be subtracted from tmpc for MODP computation
  657. # mapping for tracker ids and ground truth ids
  658. for row, col in association_matrix:
  659. # apply gating on boxoverlap
  660. c = cost_matrix[row][col]
  661. if c < max_cost:
  662. g[row].tracker = t[col].track_id
  663. this_ids[1][row] = t[col].track_id
  664. t[col].valid = True
  665. g[row].distance = c
  666. self.total_cost += 1 - c
  667. tmpc += 1 - c
  668. tmpcs[row] = 1 - c
  669. seq_trajectories[g[row].track_id][-1] = t[col].track_id
  670. # true positives are only valid associations
  671. self.tp += 1
  672. tmptp += 1
  673. else:
  674. g[row].tracker = -1
  675. self.fn += 1
  676. tmpfn += 1
  677. # associate tracker and DontCare areas
  678. # ignore tracker in neighboring classes
  679. nignoredtracker = 0 # number of ignored tracker detections
  680. ignoredtrackers = dict() # will associate the track_id with -1
  681. # if it is not ignored and 1 if it is
  682. # ignored;
  683. # this is used to avoid double counting ignored
  684. # cases, see the next loop
  685. for tt in t:
  686. ignoredtrackers[tt.track_id] = -1
  687. # ignore detection if it belongs to a neighboring class or is
  688. # smaller or equal to the minimum height
  689. tt_height = abs(tt.y1 - tt.y2)
  690. if ((self.cls == "car" and tt.obj_type == "van") or
  691. (self.cls == "pedestrian" and
  692. tt.obj_type == "person_sitting") or
  693. tt_height <= self.min_height) and not tt.valid:
  694. nignoredtracker += 1
  695. tt.ignored = True
  696. ignoredtrackers[tt.track_id] = 1
  697. continue
  698. for d in dc:
  699. overlap = self.boxoverlap(tt, d, "a")
  700. if overlap > 0.5 and not tt.valid:
  701. tt.ignored = True
  702. nignoredtracker += 1
  703. ignoredtrackers[tt.track_id] = 1
  704. break
  705. # check for ignored FN/TP (truncation or neighboring object class)
  706. ignoredfn = 0 # the number of ignored false negatives
  707. nignoredtp = 0 # the number of ignored true positives
  708. nignoredpairs = 0 # the number of ignored pairs, i.e. a true positive
  709. # which is ignored but where the associated tracker
  710. # detection has already been ignored
  711. gi = 0
  712. for gg in g:
  713. if gg.tracker < 0:
  714. if gg.occlusion>self.max_occlusion or gg.truncation>self.max_truncation\
  715. or (self.cls=="car" and gg.obj_type=="van") or (self.cls=="pedestrian" and gg.obj_type=="person_sitting"):
  716. seq_ignored[gg.track_id][-1] = True
  717. gg.ignored = True
  718. ignoredfn += 1
  719. elif gg.tracker >= 0:
  720. if gg.occlusion>self.max_occlusion or gg.truncation>self.max_truncation\
  721. or (self.cls=="car" and gg.obj_type=="van") or (self.cls=="pedestrian" and gg.obj_type=="person_sitting"):
  722. seq_ignored[gg.track_id][-1] = True
  723. gg.ignored = True
  724. nignoredtp += 1
  725. # if the associated tracker detection is already ignored,
  726. # we want to avoid double counting ignored detections
  727. if ignoredtrackers[gg.tracker] > 0:
  728. nignoredpairs += 1
  729. # for computing MODP, the overlaps from ignored detections
  730. # are subtracted
  731. tmpc -= tmpcs[gi]
  732. gi += 1
  733. # the below might be confusion, check the comments in __init__
  734. # to see what the individual statistics represent
  735. # correct TP by number of ignored TP due to truncation
  736. # ignored TP are shown as tracked in visualization
  737. tmptp -= nignoredtp
  738. # count the number of ignored true positives
  739. self.itp += nignoredtp
  740. # adjust the number of ground truth objects considered
  741. self.n_gt -= (ignoredfn + nignoredtp)
  742. # count the number of ignored ground truth objects
  743. self.n_igt += ignoredfn + nignoredtp
  744. # count the number of ignored tracker objects
  745. self.n_itr += nignoredtracker
  746. # count the number of ignored pairs, i.e. associated tracker and
  747. # ground truth objects that are both ignored
  748. self.n_igttr += nignoredpairs
  749. # false negatives = associated gt bboxes exceding association threshold + non-associated gt bboxes
  750. tmpfn += len(g) - len(association_matrix) - ignoredfn
  751. self.fn += len(g) - len(association_matrix) - ignoredfn
  752. self.ifn += ignoredfn
  753. # false positives = tracker bboxes - associated tracker bboxes
  754. # mismatches (mme_t)
  755. tmpfp += len(
  756. t) - tmptp - nignoredtracker - nignoredtp + nignoredpairs
  757. self.fp += len(
  758. t) - tmptp - nignoredtracker - nignoredtp + nignoredpairs
  759. # update sequence data
  760. seqtp += tmptp
  761. seqitp += nignoredtp
  762. seqfp += tmpfp
  763. seqfn += tmpfn
  764. seqifn += ignoredfn
  765. seqigt += ignoredfn + nignoredtp
  766. seqitr += nignoredtracker
  767. # sanity checks
  768. # - the number of true positives minues ignored true positives
  769. # should be greater or equal to 0
  770. # - the number of false negatives should be greater or equal to 0
  771. # - the number of false positives needs to be greater or equal to 0
  772. # otherwise ignored detections might be counted double
  773. # - the number of counted true positives (plus ignored ones)
  774. # and the number of counted false negatives (plus ignored ones)
  775. # should match the total number of ground truth objects
  776. # - the number of counted true positives (plus ignored ones)
  777. # and the number of counted false positives
  778. # plus the number of ignored tracker detections should
  779. # match the total number of tracker detections; note that
  780. # nignoredpairs is subtracted here to avoid double counting
  781. # of ignored detection sin nignoredtp and nignoredtracker
  782. if tmptp < 0:
  783. print(tmptp, nignoredtp)
  784. raise NameError("Something went wrong! TP is negative")
  785. if tmpfn < 0:
  786. print(tmpfn,
  787. len(g),
  788. len(association_matrix), ignoredfn, nignoredpairs)
  789. raise NameError("Something went wrong! FN is negative")
  790. if tmpfp < 0:
  791. print(tmpfp,
  792. len(t), tmptp, nignoredtracker, nignoredtp,
  793. nignoredpairs)
  794. raise NameError("Something went wrong! FP is negative")
  795. if tmptp + tmpfn is not len(g) - ignoredfn - nignoredtp:
  796. print("seqidx", seq_idx)
  797. print("frame ", f)
  798. print("TP ", tmptp)
  799. print("FN ", tmpfn)
  800. print("FP ", tmpfp)
  801. print("nGT ", len(g))
  802. print("nAss ", len(association_matrix))
  803. print("ign GT", ignoredfn)
  804. print("ign TP", nignoredtp)
  805. raise NameError(
  806. "Something went wrong! nGroundtruth is not TP+FN")
  807. if tmptp + tmpfp + nignoredtp + nignoredtracker - nignoredpairs is not len(
  808. t):
  809. print(seq_idx, f, len(t), tmptp, tmpfp)
  810. print(len(association_matrix), association_matrix)
  811. raise NameError(
  812. "Something went wrong! nTracker is not TP+FP")
  813. # check for id switches or fragmentations
  814. for i, tt in enumerate(this_ids[0]):
  815. if tt in last_ids[0]:
  816. idx = last_ids[0].index(tt)
  817. tid = this_ids[1][i]
  818. lid = last_ids[1][idx]
  819. if tid != lid and lid != -1 and tid != -1:
  820. if g[i].truncation < self.max_truncation:
  821. g[i].id_switch = 1
  822. ids += 1
  823. if tid != lid and lid != -1:
  824. if g[i].truncation < self.max_truncation:
  825. g[i].fragmentation = 1
  826. fr += 1
  827. # save current index
  828. last_ids = this_ids
  829. # compute MOTP_t
  830. MODP_t = 1
  831. if tmptp != 0:
  832. MODP_t = tmpc / float(tmptp)
  833. self.MODP_t.append(MODP_t)
  834. # remove empty lists for current gt trajectories
  835. self.gt_trajectories[seq_idx] = seq_trajectories
  836. self.ign_trajectories[seq_idx] = seq_ignored
  837. # gather statistics for "per sequence" statistics.
  838. self.n_gts.append(n_gts)
  839. self.n_trs.append(n_trs)
  840. self.tps.append(seqtp)
  841. self.itps.append(seqitp)
  842. self.fps.append(seqfp)
  843. self.fns.append(seqfn)
  844. self.ifns.append(seqifn)
  845. self.n_igts.append(seqigt)
  846. self.n_itrs.append(seqitr)
  847. # compute MT/PT/ML, fragments, idswitches for all groundtruth trajectories
  848. n_ignored_tr_total = 0
  849. for seq_idx, (
  850. seq_trajectories, seq_ignored
  851. ) in enumerate(zip(self.gt_trajectories, self.ign_trajectories)):
  852. if len(seq_trajectories) == 0:
  853. continue
  854. tmpMT, tmpML, tmpPT, tmpId_switches, tmpFragments = [0] * 5
  855. n_ignored_tr = 0
  856. for g, ign_g in zip(seq_trajectories.values(),
  857. seq_ignored.values()):
  858. # all frames of this gt trajectory are ignored
  859. if all(ign_g):
  860. n_ignored_tr += 1
  861. n_ignored_tr_total += 1
  862. continue
  863. # all frames of this gt trajectory are not assigned to any detections
  864. if all([this == -1 for this in g]):
  865. tmpML += 1
  866. self.ML += 1
  867. continue
  868. # compute tracked frames in trajectory
  869. last_id = g[0]
  870. # first detection (necessary to be in gt_trajectories) is always tracked
  871. tracked = 1 if g[0] >= 0 else 0
  872. lgt = 0 if ign_g[0] else 1
  873. for f in range(1, len(g)):
  874. if ign_g[f]:
  875. last_id = -1
  876. continue
  877. lgt += 1
  878. if last_id != g[f] and last_id != -1 and g[f] != -1 and g[
  879. f - 1] != -1:
  880. tmpId_switches += 1
  881. self.id_switches += 1
  882. if f < len(g) - 1 and g[f - 1] != g[
  883. f] and last_id != -1 and g[f] != -1 and g[f +
  884. 1] != -1:
  885. tmpFragments += 1
  886. self.fragments += 1
  887. if g[f] != -1:
  888. tracked += 1
  889. last_id = g[f]
  890. # handle last frame; tracked state is handled in for loop (g[f]!=-1)
  891. if len(g) > 1 and g[f - 1] != g[f] and last_id != -1 and g[
  892. f] != -1 and not ign_g[f]:
  893. tmpFragments += 1
  894. self.fragments += 1
  895. # compute MT/PT/ML
  896. tracking_ratio = tracked / float(len(g) - sum(ign_g))
  897. if tracking_ratio > 0.8:
  898. tmpMT += 1
  899. self.MT += 1
  900. elif tracking_ratio < 0.2:
  901. tmpML += 1
  902. self.ML += 1
  903. else: # 0.2 <= tracking_ratio <= 0.8
  904. tmpPT += 1
  905. self.PT += 1
  906. if (self.n_gt_trajectories - n_ignored_tr_total) == 0:
  907. self.MT = 0.
  908. self.PT = 0.
  909. self.ML = 0.
  910. else:
  911. self.MT /= float(self.n_gt_trajectories - n_ignored_tr_total)
  912. self.PT /= float(self.n_gt_trajectories - n_ignored_tr_total)
  913. self.ML /= float(self.n_gt_trajectories - n_ignored_tr_total)
  914. # precision/recall etc.
  915. if (self.fp + self.tp) == 0 or (self.tp + self.fn) == 0:
  916. self.recall = 0.
  917. self.precision = 0.
  918. else:
  919. self.recall = self.tp / float(self.tp + self.fn)
  920. self.precision = self.tp / float(self.fp + self.tp)
  921. if (self.recall + self.precision) == 0:
  922. self.F1 = 0.
  923. else:
  924. self.F1 = 2. * (self.precision * self.recall) / (
  925. self.precision + self.recall)
  926. if sum(self.n_frames) == 0:
  927. self.FAR = "n/a"
  928. else:
  929. self.FAR = self.fp / float(sum(self.n_frames))
  930. # compute CLEARMOT
  931. if self.n_gt == 0:
  932. self.MOTA = -float("inf")
  933. self.MODA = -float("inf")
  934. else:
  935. self.MOTA = 1 - (self.fn + self.fp + self.id_switches
  936. ) / float(self.n_gt)
  937. self.MODA = 1 - (self.fn + self.fp) / float(self.n_gt)
  938. if self.tp == 0:
  939. self.MOTP = float("inf")
  940. else:
  941. self.MOTP = self.total_cost / float(self.tp)
  942. if self.n_gt != 0:
  943. if self.id_switches == 0:
  944. self.MOTAL = 1 - (self.fn + self.fp + self.id_switches
  945. ) / float(self.n_gt)
  946. else:
  947. self.MOTAL = 1 - (self.fn + self.fp +
  948. math.log10(self.id_switches)
  949. ) / float(self.n_gt)
  950. else:
  951. self.MOTAL = -float("inf")
  952. if sum(self.n_frames) == 0:
  953. self.MODP = "n/a"
  954. else:
  955. self.MODP = sum(self.MODP_t) / float(sum(self.n_frames))
  956. return True
  957. def createSummary(self):
  958. summary = ""
  959. summary += "tracking evaluation summary".center(80, "=") + "\n"
  960. summary += self.printEntry("Multiple Object Tracking Accuracy (MOTA)",
  961. self.MOTA) + "\n"
  962. summary += self.printEntry("Multiple Object Tracking Precision (MOTP)",
  963. self.MOTP) + "\n"
  964. summary += self.printEntry("Multiple Object Tracking Accuracy (MOTAL)",
  965. self.MOTAL) + "\n"
  966. summary += self.printEntry("Multiple Object Detection Accuracy (MODA)",
  967. self.MODA) + "\n"
  968. summary += self.printEntry("Multiple Object Detection Precision (MODP)",
  969. self.MODP) + "\n"
  970. summary += "\n"
  971. summary += self.printEntry("Recall", self.recall) + "\n"
  972. summary += self.printEntry("Precision", self.precision) + "\n"
  973. summary += self.printEntry("F1", self.F1) + "\n"
  974. summary += self.printEntry("False Alarm Rate", self.FAR) + "\n"
  975. summary += "\n"
  976. summary += self.printEntry("Mostly Tracked", self.MT) + "\n"
  977. summary += self.printEntry("Partly Tracked", self.PT) + "\n"
  978. summary += self.printEntry("Mostly Lost", self.ML) + "\n"
  979. summary += "\n"
  980. summary += self.printEntry("True Positives", self.tp) + "\n"
  981. #summary += self.printEntry("True Positives per Sequence", self.tps) + "\n"
  982. summary += self.printEntry("Ignored True Positives", self.itp) + "\n"
  983. #summary += self.printEntry("Ignored True Positives per Sequence", self.itps) + "\n"
  984. summary += self.printEntry("False Positives", self.fp) + "\n"
  985. #summary += self.printEntry("False Positives per Sequence", self.fps) + "\n"
  986. summary += self.printEntry("False Negatives", self.fn) + "\n"
  987. #summary += self.printEntry("False Negatives per Sequence", self.fns) + "\n"
  988. summary += self.printEntry("ID-switches", self.id_switches) + "\n"
  989. self.fp = self.fp / self.n_gt
  990. self.fn = self.fn / self.n_gt
  991. self.id_switches = self.id_switches / self.n_gt
  992. summary += self.printEntry("False Positives Ratio", self.fp) + "\n"
  993. #summary += self.printEntry("False Positives per Sequence", self.fps) + "\n"
  994. summary += self.printEntry("False Negatives Ratio", self.fn) + "\n"
  995. #summary += self.printEntry("False Negatives per Sequence", self.fns) + "\n"
  996. summary += self.printEntry("Ignored False Negatives Ratio",
  997. self.ifn) + "\n"
  998. #summary += self.printEntry("Ignored False Negatives per Sequence", self.ifns) + "\n"
  999. summary += self.printEntry("Missed Targets", self.fn) + "\n"
  1000. summary += self.printEntry("ID-switches", self.id_switches) + "\n"
  1001. summary += self.printEntry("Fragmentations", self.fragments) + "\n"
  1002. summary += "\n"
  1003. summary += self.printEntry("Ground Truth Objects (Total)", self.n_gt +
  1004. self.n_igt) + "\n"
  1005. #summary += self.printEntry("Ground Truth Objects (Total) per Sequence", self.n_gts) + "\n"
  1006. summary += self.printEntry("Ignored Ground Truth Objects",
  1007. self.n_igt) + "\n"
  1008. #summary += self.printEntry("Ignored Ground Truth Objects per Sequence", self.n_igts) + "\n"
  1009. summary += self.printEntry("Ground Truth Trajectories",
  1010. self.n_gt_trajectories) + "\n"
  1011. summary += "\n"
  1012. summary += self.printEntry("Tracker Objects (Total)", self.n_tr) + "\n"
  1013. #summary += self.printEntry("Tracker Objects (Total) per Sequence", self.n_trs) + "\n"
  1014. summary += self.printEntry("Ignored Tracker Objects", self.n_itr) + "\n"
  1015. #summary += self.printEntry("Ignored Tracker Objects per Sequence", self.n_itrs) + "\n"
  1016. summary += self.printEntry("Tracker Trajectories",
  1017. self.n_tr_trajectories) + "\n"
  1018. #summary += "\n"
  1019. #summary += self.printEntry("Ignored Tracker Objects with Associated Ignored Ground Truth Objects", self.n_igttr) + "\n"
  1020. summary += "=" * 80
  1021. return summary
  1022. def printEntry(self, key, val, width=(70, 10)):
  1023. """
  1024. Pretty print an entry in a table fashion.
  1025. """
  1026. s_out = key.ljust(width[0])
  1027. if type(val) == int:
  1028. s = "%%%dd" % width[1]
  1029. s_out += s % val
  1030. elif type(val) == float:
  1031. s = "%%%df" % (width[1])
  1032. s_out += s % val
  1033. else:
  1034. s_out += ("%s" % val).rjust(width[1])
  1035. return s_out
  1036. def saveToStats(self, save_summary):
  1037. """
  1038. Save the statistics in a whitespace separate file.
  1039. """
  1040. summary = self.createSummary()
  1041. if save_summary:
  1042. filename = os.path.join(self.result_path,
  1043. "summary_%s.txt" % self.cls)
  1044. dump = open(filename, "w+")
  1045. dump.write(summary)
  1046. dump.close()
  1047. return summary
  1048. class KITTIMOTMetric(Metric):
  1049. def __init__(self, save_summary=True):
  1050. self.save_summary = save_summary
  1051. self.MOTEvaluator = KITTIEvaluation
  1052. self.result_root = None
  1053. self.reset()
  1054. def reset(self):
  1055. self.seqs = []
  1056. self.n_sequences = 0
  1057. self.n_frames = []
  1058. self.strsummary = ''
  1059. def update(self, data_root, seq, data_type, result_root, result_filename):
  1060. assert data_type == 'kitti', "data_type should 'kitti'"
  1061. self.result_root = result_root
  1062. self.gt_path = data_root
  1063. gt_path = '{}/../labels/{}.txt'.format(data_root, seq)
  1064. gt = open(gt_path, "r")
  1065. max_frame = 0
  1066. for line in gt:
  1067. line = line.strip()
  1068. line_list = line.split(" ")
  1069. if int(line_list[0]) > max_frame:
  1070. max_frame = int(line_list[0])
  1071. rs = open(result_filename, "r")
  1072. for line in rs:
  1073. line = line.strip()
  1074. line_list = line.split(" ")
  1075. if int(line_list[0]) > max_frame:
  1076. max_frame = int(line_list[0])
  1077. gt.close()
  1078. rs.close()
  1079. self.n_frames.append(max_frame + 1)
  1080. self.seqs.append(seq)
  1081. self.n_sequences += 1
  1082. def accumulate(self):
  1083. logger.info("Processing Result for KITTI Tracking Benchmark")
  1084. e = self.MOTEvaluator(result_path=self.result_root, gt_path=self.gt_path,\
  1085. n_frames=self.n_frames, seqs=self.seqs, n_sequences=self.n_sequences)
  1086. try:
  1087. if not e.loadTracker():
  1088. return
  1089. logger.info("Loading Results - Success")
  1090. logger.info("Evaluate Object Class: %s" % c.upper())
  1091. except:
  1092. logger.info("Caught exception while loading result data.")
  1093. if not e.loadGroundtruth():
  1094. raise ValueError("Ground truth not found.")
  1095. logger.info("Loading Groundtruth - Success")
  1096. # sanity checks
  1097. if len(e.groundtruth) is not len(e.tracker):
  1098. logger.info(
  1099. "The uploaded data does not provide results for every sequence.")
  1100. return False
  1101. logger.info("Loaded %d Sequences." % len(e.groundtruth))
  1102. logger.info("Start Evaluation...")
  1103. if e.compute3rdPartyMetrics():
  1104. self.strsummary = e.saveToStats(self.save_summary)
  1105. else:
  1106. logger.info(
  1107. "There seem to be no true positives or false positives at all in the submitted data."
  1108. )
  1109. def log(self):
  1110. print(self.strsummary)
  1111. def get_results(self):
  1112. return self.strsummary