mot_metrics.py 50 KB

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