You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. from __future__ import print_function
  2. import os
  3. import numpy as np
  4. import matplotlib
  5. matplotlib.use('Agg')
  6. import matplotlib.pyplot as plt
  7. import matplotlib.patches as patches
  8. from skimage import io
  9. import glob
  10. import time,cv2
  11. import argparse
  12. from filterpy.kalman import KalmanFilter
  13. np.random.seed(0)
  14. def plot_one_box_ForTrack(x, im, color=None, label=None, line_thickness=3):
  15. # Plots one bounding box on image 'im' using OpenCV
  16. assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to plot_on_box() input image.'
  17. tl = line_thickness or round(0.002 * (im.shape[0] + im.shape[1]) / 2) + 1 # line/font thickness
  18. color = color or [random.randint(0, 255) for _ in range(3)]
  19. c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
  20. cv2.rectangle(im, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
  21. if label:
  22. tf = max(tl - 1, 1) # font thickness
  23. t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
  24. c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
  25. cv2.rectangle(im, c1, c2, color, -1, cv2.LINE_AA) # filled
  26. cv2.putText(im, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
  27. def drawBoxTraceSimplied(track_det_result,iiframe, img_draw,rainbows=None,boxFlag=True,traceFlag=True):
  28. boxes_oneFrame = track_det_result[ track_det_result[:,6]==iiframe ]
  29. if boxFlag:
  30. ###在某一帧上,画上检测框
  31. for box in boxes_oneFrame:
  32. x0,y0,x1,y1,conf,cls = box[0:6]
  33. #cv2.rectangle(img_draw, ( int(x0), int(y0) ), ( int(x1), int(y1) ), (255,0,20), 2)
  34. txtstring='%d:%.2f'%(cls,conf)
  35. plot_one_box_ForTrack( box[0:4], img_draw, color=rainbows[ int(cls)], label=txtstring, line_thickness=3)
  36. if traceFlag:
  37. ###在某一帧上,画上轨迹
  38. track_ids = boxes_oneFrame[:,7].tolist()
  39. boxes_before_oneFrame = track_det_result[ track_det_result[:,6]<=iiframe ]
  40. for trackId in track_ids:
  41. boxes_before_oneFrame_oneId = boxes_before_oneFrame[boxes_before_oneFrame[:,7]==trackId]
  42. xcs = (boxes_before_oneFrame_oneId[:,0]+boxes_before_oneFrame_oneId[:,2])//2
  43. ycs = (boxes_before_oneFrame_oneId[:,1]+boxes_before_oneFrame_oneId[:,3])//2
  44. [cv2.line(img_draw, ( int(xcs[i]) , int(ycs[i]) ),
  45. ( int(xcs[i+1]),int(ycs[i+1]) ),(255,0,0), thickness=2)
  46. for i,_ in enumerate(xcs) if i < len(xcs)-1 ]
  47. return img_draw
  48. def moving_average_wang(interval, windowsize):
  49. outNum = interval.copy()
  50. if windowsize==1:
  51. return outNum
  52. assert windowsize%2!=0
  53. window = np.ones(int(windowsize)) / float(windowsize)
  54. re = np.convolve(interval, window, 'valid')
  55. cnt = int((windowsize - 1)/2+0.5)
  56. total = len(interval)
  57. outNum = np.zeros( (total,),dtype=np.float32 )
  58. outNum[0]=interval[0]
  59. outNum[-1]=interval[-1]
  60. for i in range(1,cnt):
  61. outNum[i] = np.mean( interval[0:2*i-1] )
  62. outNum[-i-1] = np.mean( interval[-2*i-1:] )
  63. #print('###line113:',outNum.shape,re.shape,cnt,windowsize)
  64. outNum[cnt:-cnt]=re[:]
  65. return outNum
  66. def track_draw_trace(tracks,im0):
  67. for track in tracks:
  68. [cv2.line(im0, (int(track.centroidarr[i][0]),
  69. int(track.centroidarr[i][1])),
  70. (int(track.centroidarr[i+1][0]),
  71. int(track.centroidarr[i+1][1])),
  72. (255,0,0), thickness=2)
  73. for i,_ in enumerate(track.centroidarr)
  74. if i < len(track.centroidarr)-1 ]
  75. return im0
  76. """Function to Draw Bounding boxes"""
  77. def track_draw_boxes(img, bbox, identities=None, categories=None, names=None ):
  78. for i, box in enumerate(bbox):
  79. #print('####line33 sort.py:',box)
  80. x1, y1, x2, y2 = [int(x) for x in box]
  81. cat = int(categories[i]) if categories is not None else 0
  82. id = int(identities[i]) if identities is not None else 0
  83. data = (int((box[0]+box[2])/2),(int((box[1]+box[3])/2)))
  84. label = str(id) + ":"+ names[cat]
  85. (w, h), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 1)
  86. cv2.rectangle(img, (x1, y1), (x2, y2), (255,0,20), 2)
  87. cv2.rectangle(img, (x1, y1 - 20), (x1 + w, y1), (255,144,30), -1)
  88. cv2.putText(img, label, (x1, y1 - 5),cv2.FONT_HERSHEY_SIMPLEX,
  89. 0.6, [255, 255, 255], 1)
  90. # cv2.circle(img, data, 6, color,-1) #centroid of box
  91. return img
  92. def track_draw_all_boxes(tracked_dets,im0,names):
  93. if len(tracked_dets)>0:
  94. bbox_xyxy = tracked_dets[:,:4]
  95. identities = tracked_dets[:, 8]
  96. categories = tracked_dets[:, 4]
  97. track_draw_boxes(im0, bbox_xyxy, identities, categories, names)
  98. return im0
  99. ####轨迹采用跟踪链中的结果。box采用track.update后的结果。
  100. def track_draw_boxAndTrace(tracked_dets,tracks,im0,names):
  101. track_draw_all_boxes(tracked_dets,im0,names)
  102. track_draw_trace(tracks,im0)
  103. return im0
  104. ####轨迹和box都采用跟踪链中的结果
  105. def track_draw_trace_boxes(tracks,im0,names):
  106. for track in tracks:
  107. [cv2.line(im0, (int(track.centroidarr[i][0]),
  108. int(track.centroidarr[i][1])),
  109. (int(track.centroidarr[i+1][0]),
  110. int(track.centroidarr[i+1][1])),
  111. (255,0,0), thickness=2)
  112. for i,_ in enumerate(track.centroidarr)
  113. if i < len(track.centroidarr)-1 ]
  114. bbox_xyxy = track.bbox_history[-1][0:4]
  115. identities,categories = track.id , track.detclass
  116. #print('####sort.py line74:',bbox_xyxy)
  117. track_draw_boxes(im0, [bbox_xyxy], [identities], [categories], names)
  118. return im0
  119. def linear_assignment(cost_matrix):
  120. try:
  121. import lap #linear assignment problem solver
  122. _, x, y = lap.lapjv(cost_matrix, extend_cost = True)
  123. return np.array([[y[i],i] for i in x if i>=0])
  124. except ImportError:
  125. from scipy.optimize import linear_sum_assignment
  126. x,y = linear_sum_assignment(cost_matrix)
  127. return np.array(list(zip(x,y)))
  128. """From SORT: Computes IOU between two boxes in the form [x1,y1,x2,y2]"""
  129. def iou_batch(bb_test, bb_gt):
  130. bb_gt = np.expand_dims(bb_gt, 0)
  131. bb_test = np.expand_dims(bb_test, 1)
  132. xx1 = np.maximum(bb_test[...,0], bb_gt[..., 0])
  133. yy1 = np.maximum(bb_test[..., 1], bb_gt[..., 1])
  134. xx2 = np.minimum(bb_test[..., 2], bb_gt[..., 2])
  135. yy2 = np.minimum(bb_test[..., 3], bb_gt[..., 3])
  136. w = np.maximum(0., xx2 - xx1)
  137. h = np.maximum(0., yy2 - yy1)
  138. wh = w * h
  139. o = wh / ((bb_test[..., 2] - bb_test[..., 0]) * (bb_test[..., 3] - bb_test[..., 1])
  140. + (bb_gt[..., 2] - bb_gt[..., 0]) * (bb_gt[..., 3] - bb_gt[..., 1]) - wh)
  141. return(o)
  142. """Takes a bounding box in the form [x1,y1,x2,y2] and returns z in the form [x,y,s,r] where x,y is the center of the box and s is the scale/area and r is the aspect ratio"""
  143. def convert_bbox_to_z(bbox):
  144. w = bbox[2] - bbox[0]
  145. h = bbox[3] - bbox[1]
  146. x = bbox[0] + w/2.
  147. y = bbox[1] + h/2.
  148. s = w * h
  149. #scale is just area
  150. r = w / float(h)
  151. return np.array([x, y, s, r]).reshape((4, 1))
  152. """Takes a bounding box in the centre form [x,y,s,r] and returns it in the form
  153. [x1,y1,x2,y2] where x1,y1 is the top left and x2,y2 is the bottom right"""
  154. def convert_x_to_bbox(x, score=None):
  155. w = np.sqrt(x[2] * x[3])
  156. h = x[2] / w
  157. if(score==None):
  158. return np.array([x[0]-w/2.,x[1]-h/2.,x[0]+w/2.,x[1]+h/2.]).reshape((1,4))
  159. else:
  160. return np.array([x[0]-w/2.,x[1]-h/2.,x[0]+w/2.,x[1]+h/2.,score]).reshape((1,5))
  161. """This class represents the internal state of individual tracked objects observed as bbox."""
  162. class KalmanBoxTracker(object):
  163. count = 0
  164. def __init__(self, bbox):
  165. """
  166. Initialize a tracker using initial bounding box
  167. Parameter 'bbox' must have 'detected class' int number at the -1 position.
  168. """
  169. self.kf = KalmanFilter(dim_x=7, dim_z=4)
  170. self.kf.F = np.array([[1,0,0,0,1,0,0],[0,1,0,0,0,1,0],[0,0,1,0,0,0,1],[0,0,0,1,0,0,0],[0,0,0,0,1,0,0],[0,0,0,0,0,1,0],[0,0,0,0,0,0,1]])
  171. self.kf.H = np.array([[1,0,0,0,0,0,0],[0,1,0,0,0,0,0],[0,0,1,0,0,0,0],[0,0,0,1,0,0,0]])
  172. self.kf.R[2:,2:] *= 10. # R: Covariance matrix of measurement noise (set to high for noisy inputs -> more 'inertia' of boxes')
  173. self.kf.P[4:,4:] *= 1000. #give high uncertainty to the unobservable initial velocities
  174. self.kf.P *= 10.
  175. self.kf.Q[-1,-1] *= 0.5 # Q: Covariance matrix of process noise (set to high for erratically moving things)
  176. self.kf.Q[4:,4:] *= 0.5
  177. self.kf.x[:4] = convert_bbox_to_z(bbox) # STATE VECTOR
  178. self.time_since_update = 0
  179. self.id = KalmanBoxTracker.count
  180. KalmanBoxTracker.count += 1
  181. self.history = []
  182. self.hits = 0
  183. self.hit_streak = 0
  184. self.age = 0
  185. self.frames = []
  186. self.centroidarr = []
  187. CX = (bbox[0]+bbox[2])//2
  188. CY = (bbox[1]+bbox[3])//2
  189. self.centroidarr.append((CX,CY))
  190. #keep yolov5 detected class information
  191. self.detclass = bbox[5]
  192. self.frames.append( bbox[6] ) ###new added for interpolation
  193. # If we want to store bbox
  194. self.bbox_history = [bbox]
  195. def update(self, bbox):
  196. """
  197. Updates the state vector with observed bbox
  198. """
  199. self.time_since_update = 0
  200. self.history = []
  201. self.hits += 1
  202. self.hit_streak += 1
  203. self.kf.update(convert_bbox_to_z(bbox))
  204. self.detclass = bbox[5]
  205. CX = (bbox[0]+bbox[2])//2
  206. CY = (bbox[1]+bbox[3])//2
  207. self.centroidarr.append((CX,CY))
  208. self.frames.append( bbox[6] ) ###new added for interpolation
  209. self.bbox_history.append(bbox)
  210. def predict(self):
  211. """
  212. Advances the state vector and returns the predicted bounding box estimate
  213. """
  214. if((self.kf.x[6]+self.kf.x[2])<=0):
  215. self.kf.x[6] *= 0.0
  216. self.kf.predict()
  217. self.age += 1
  218. if(self.time_since_update>0):
  219. self.hit_streak = 0
  220. self.time_since_update += 1
  221. self.history.append(convert_x_to_bbox(self.kf.x))
  222. # bbox=self.history[-1]
  223. # CX = (bbox[0]+bbox[2])/2
  224. # CY = (bbox[1]+bbox[3])/2
  225. # self.centroidarr.append((CX,CY))
  226. return self.history[-1]
  227. def get_state(self):
  228. """
  229. Returns the current bounding box estimate
  230. # test
  231. arr1 = np.array([[1,2,3,4]])
  232. arr2 = np.array([0])
  233. arr3 = np.expand_dims(arr2, 0)
  234. np.concatenate((arr1,arr3), axis=1)
  235. """
  236. arr_detclass = np.expand_dims(np.array([self.detclass]), 0)
  237. arr_u_dot = np.expand_dims(self.kf.x[4],0)
  238. arr_v_dot = np.expand_dims(self.kf.x[5],0)
  239. arr_s_dot = np.expand_dims(self.kf.x[6],0)
  240. return np.concatenate((convert_x_to_bbox(self.kf.x), arr_detclass, arr_u_dot, arr_v_dot, arr_s_dot), axis=1)
  241. def associate_detections_to_trackers(detections, trackers, iou_threshold = 0.3):
  242. """
  243. Assigns detections to tracked object (both represented as bounding boxes)
  244. Returns 3 lists of
  245. 1. matches,
  246. 2. unmatched_detections
  247. 3. unmatched_trackers
  248. """
  249. if(len(trackers)==0):
  250. return np.empty((0,2),dtype=int), np.arange(len(detections)), np.empty((0,5),dtype=int)
  251. iou_matrix = iou_batch(detections, trackers)
  252. if min(iou_matrix.shape) > 0:
  253. a = (iou_matrix > iou_threshold).astype(np.int32)
  254. if a.sum(1).max() == 1 and a.sum(0).max() ==1:
  255. matched_indices = np.stack(np.where(a), axis=1)
  256. else:
  257. matched_indices = linear_assignment(-iou_matrix)
  258. else:
  259. matched_indices = np.empty(shape=(0,2))
  260. unmatched_detections = []
  261. for d, det in enumerate(detections):
  262. if(d not in matched_indices[:,0]):
  263. unmatched_detections.append(d)
  264. unmatched_trackers = []
  265. for t, trk in enumerate(trackers):
  266. if(t not in matched_indices[:,1]):
  267. unmatched_trackers.append(t)
  268. #filter out matched with low IOU
  269. matches = []
  270. for m in matched_indices:
  271. if(iou_matrix[m[0], m[1]]<iou_threshold):
  272. unmatched_detections.append(m[0])
  273. unmatched_trackers.append(m[1])
  274. else:
  275. matches.append(m.reshape(1,2))
  276. if(len(matches)==0):
  277. matches = np.empty((0,2), dtype=int)
  278. else:
  279. matches = np.concatenate(matches, axis=0)
  280. return matches, np.array(unmatched_detections), np.array(unmatched_trackers)
  281. class Sort(object):
  282. # def __init__(self, max_age=1, min_hits=3, iou_threshold=0.3):
  283. def __init__(self, max_age=1, min_hits=1000, iou_threshold=0.1):
  284. """
  285. Parameters for SORT
  286. """
  287. self.max_age = max_age # 最大检测数:目标未被检测到的帧数,超过之后会被删
  288. self.min_hits = min_hits # 目标命中的最小次数,小于该次数不返回
  289. self.iou_threshold = iou_threshold
  290. self.trackers = []
  291. self.frame_count = 0
  292. def getTrackers(self,):
  293. return self.trackers
  294. def update(self, dets= np.empty((0,6))):
  295. """
  296. Parameters:
  297. 'dets' - a numpy array of detection in the format [[x1, y1, x2, y2, score], [x1,y1,x2,y2,score],...]
  298. Ensure to call this method even frame has no detections. (pass np.empty((0,5)))
  299. Returns a similar array, where the last column is object ID (replacing confidence score)
  300. NOTE: The number of objects returned may differ from the number of objects provided.
  301. """
  302. self.frame_count += 1
  303. # 在当前帧逐个预测轨迹位置,记录状态异常的跟踪器索引
  304. # 根据当前所有的卡尔曼跟踪器个数(即上一帧中跟踪的目标个数)创建二维数组:行号为卡尔曼滤波器的标识索引,列向量为跟踪
  305. # Get predicted locations from existing trackers
  306. trks = np.zeros((len(self.trackers), 6)) # 存储跟踪器的预测
  307. to_del = [] # 存储要删除的目标框
  308. ret = [] # 存储要返回的追踪目标框
  309. # 循环遍历卡尔曼跟踪器列表
  310. for t, trk in enumerate(trks):
  311. # 使用卡尔曼跟踪器t产生对应目标的跟踪框
  312. pos = self.trackers[t].predict()[0]
  313. # 遍历完成后,trk中存储了上一帧中跟踪的目标的预测跟踪框
  314. trk[:] = [pos[0], pos[1], pos[2], pos[3], 0, 0]
  315. # 如果跟踪框中包含空值则将该跟踪框添加到要删除的列表中
  316. if np.any(np.isnan(pos)):
  317. to_del.append(t)
  318. # numpy.ma.masked_invalid 屏蔽出现无效值的数组(NaN 或 inf)
  319. # numpy.ma.compress_rows 压缩包含掩码值的2-D 数组的整行,将包含掩码值的整行去除
  320. # trks中存储了上一帧中跟踪的目标并且在当前帧中的预测跟踪框
  321. trks = np.ma.compress_rows(np.ma.masked_invalid(trks))
  322. # 逆向删除异常的跟踪器,防止破坏索引
  323. for t in reversed(to_del):
  324. self.trackers.pop(t)
  325. # 将目标检测框与卡尔曼滤波器预测的跟踪框关联获取跟踪成功的目标,新增的目标,离开画面的目标
  326. matched, unmatched_dets, unmatched_trks = associate_detections_to_trackers(dets, trks, self.iou_threshold)
  327. # 将跟踪成功的目标框更新到对应的卡尔曼滤波器
  328. # Update matched trackers with assigned detections
  329. for m in matched:
  330. self.trackers[m[1]].update(dets[m[0], :])
  331. # 为新增的目标创建新的卡尔曼滤波器对象进行跟踪
  332. # Create and initialize new trackers for unmatched detections
  333. for i in unmatched_dets:
  334. trk = KalmanBoxTracker(np.hstack(dets[i,:]))
  335. #trk = KalmanBoxTracker(np.hstack( (dets[i,:], np.array([0] )) ) ) ##初始化多了一个数,可能是为了标记说明这是第一次出现,box有7个数
  336. #print(' ###line271: ', np.hstack((dets[i,:], np.array([0])) ).shape)
  337. self.trackers.append(trk)
  338. # 自后向前遍历,仅返回在当前帧出现且命中周期大于self.min_hits(除非跟踪刚开始)的跟踪结果;如果未命中时间大于self.max_age则删除跟踪器。
  339. # hit_streak忽略目标初始的若干帧
  340. i = len(self.trackers)
  341. for trk in reversed(self.trackers):
  342. # 返回当前边界框的估计值
  343. d = trk.get_state()[0]
  344. # 跟踪成功目标的box与id放入ret列表中
  345. if (trk.time_since_update < 1) and (trk.hit_streak >= self.min_hits or self.frame_count <= self.min_hits):
  346. ret.append(np.concatenate((d, [trk.id+1])).reshape(1,-1)) #+1'd because MOT benchmark requires positive value
  347. i -= 1
  348. #remove dead tracklet
  349. # 跟踪失败或离开画面的目标从卡尔曼跟踪器中删除
  350. if(trk.time_since_update >self.max_age):
  351. self.trackers.pop(i) #pop按键或索引位置删除对应元素
  352. # 返回当前画面中所有目标的box与id,以二维矩阵形式返回
  353. if(len(ret) > 0):
  354. #print('####sort.py line282:',len(ret),ret[0].shape, (np.concatenate(ret)).shape)
  355. return np.concatenate(ret)
  356. return np.empty((0,6))
  357. def parse_args():
  358. """Parse input arguments."""
  359. parser = argparse.ArgumentParser(description='SORT demo')
  360. parser.add_argument('--display', dest='display', help='Display online tracker output (slow) [False]',action='store_true')
  361. parser.add_argument("--seq_path", help="Path to detections.", type=str, default='data')
  362. parser.add_argument("--phase", help="Subdirectory in seq_path.", type=str, default='train')
  363. parser.add_argument("--max_age",
  364. help="Maximum number of frames to keep alive a track without associated detections.",
  365. type=int, default=1)
  366. parser.add_argument("--min_hits",
  367. help="Minimum number of associated detections before track is initialised.",
  368. type=int, default=3)
  369. parser.add_argument("--iou_threshold", help="Minimum IOU for match.", type=float, default=0.3)
  370. args = parser.parse_args()
  371. return args
  372. if __name__ == '__main__':
  373. # all train
  374. args = parse_args()
  375. display = args.display
  376. phase = args.phase
  377. total_time = 0.0
  378. total_frames = 0
  379. colours = np.random.rand(32, 3) #used only for display
  380. if(display):
  381. if not os.path.exists('mot_benchmark'):
  382. print('\n\tERROR: mot_benchmark link not found!\n\n Create a symbolic link to the MOT benchmark\n (https://motchallenge.net/data/2D_MOT_2015/#download). E.g.:\n\n $ ln -s /path/to/MOT2015_challenge/2DMOT2015 mot_benchmark\n\n')
  383. exit()
  384. plt.ion()
  385. fig = plt.figure()
  386. ax1 = fig.add_subplot(111, aspect='equal')
  387. if not os.path.exists('output'):
  388. os.makedirs('output')
  389. pattern = os.path.join(args.seq_path, phase, '*', 'det', 'det.txt')
  390. for seq_dets_fn in glob.glob(pattern):
  391. mot_tracker = Sort(max_age=args.max_age,
  392. min_hits=args.min_hits,
  393. iou_threshold=args.iou_threshold) #create instance of the SORT tracker
  394. seq_dets = np.loadtxt(seq_dets_fn, delimiter=',')
  395. seq = seq_dets_fn[pattern.find('*'):].split(os.path.sep)[0]
  396. with open(os.path.join('output', '%s.txt'%(seq)),'w') as out_file:
  397. print("Processing %s."%(seq))
  398. for frame in range(int(seq_dets[:,0].max())):
  399. frame += 1 #detection and frame numbers begin at 1
  400. dets = seq_dets[seq_dets[:, 0]==frame, 2:7]
  401. dets[:, 2:4] += dets[:, 0:2] #convert to [x1,y1,w,h] to [x1,y1,x2,y2]
  402. total_frames += 1
  403. if(display):
  404. fn = os.path.join('mot_benchmark', phase, seq, 'img1', '%06d.jpg'%(frame))
  405. im =io.imread(fn)
  406. ax1.imshow(im)
  407. plt.title(seq + ' Tracked Targets')
  408. start_time = time.time()
  409. trackers = mot_tracker.update(dets)
  410. cycle_time = time.time() - start_time
  411. total_time += cycle_time
  412. for d in trackers:
  413. print('%d,%d,%.2f,%.2f,%.2f,%.2f,1,-1,-1,-1'%(frame,d[4],d[0],d[1],d[2]-d[0],d[3]-d[1]),file=out_file)
  414. if(display):
  415. d = d.astype(np.int32)
  416. ax1.add_patch(patches.Rectangle((d[0],d[1]),d[2]-d[0],d[3]-d[1],fill=False,lw=3,ec=colours[d[4]%32,:]))
  417. if(display):
  418. fig.canvas.flush_events()
  419. plt.draw()
  420. ax1.cla()
  421. print("Total Tracking took: %.3f seconds for %d frames or %.1f FPS" % (total_time, total_frames, total_frames / total_time))
  422. if(display):
  423. print("Note: to get real runtime results run without the option: --display")