tracker.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. from collections import deque
  2. import os
  3. import cv2
  4. import numpy as np
  5. import torch
  6. import torch.nn.functional as F
  7. from torchsummary import summary
  8. from core.mot.general import non_max_suppression_and_inds, non_max_suppression_jde, non_max_suppression, scale_coords
  9. from core.mot.torch_utils import intersect_dicts
  10. from models.mot.cstrack import Model
  11. from mot_online import matching
  12. from mot_online.kalman_filter import KalmanFilter
  13. from mot_online.log import logger
  14. from mot_online.utils import *
  15. from mot_online.basetrack import BaseTrack, TrackState
  16. class STrack(BaseTrack):
  17. shared_kalman = KalmanFilter()
  18. def __init__(self, tlwh, score, temp_feat, buffer_size=30):
  19. # wait activate
  20. self._tlwh = np.asarray(tlwh, dtype=np.float)
  21. self.kalman_filter = None
  22. self.mean, self.covariance = None, None
  23. self.is_activated = False
  24. self.score = score
  25. self.tracklet_len = 0
  26. self.smooth_feat = None
  27. self.update_features(temp_feat)
  28. self.features = deque([], maxlen=buffer_size)
  29. self.alpha = 0.9
  30. def update_features(self, feat):
  31. feat /= np.linalg.norm(feat)
  32. self.curr_feat = feat
  33. if self.smooth_feat is None:
  34. self.smooth_feat = feat
  35. else:
  36. self.smooth_feat = self.alpha * self.smooth_feat + (1 - self.alpha) * feat
  37. self.features.append(feat)
  38. self.smooth_feat /= np.linalg.norm(self.smooth_feat)
  39. def predict(self):
  40. mean_state = self.mean.copy()
  41. if self.state != TrackState.Tracked:
  42. mean_state[7] = 0
  43. self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance)
  44. @staticmethod
  45. def multi_predict(stracks):
  46. if len(stracks) > 0:
  47. multi_mean = np.asarray([st.mean.copy() for st in stracks])
  48. multi_covariance = np.asarray([st.covariance for st in stracks])
  49. for i, st in enumerate(stracks):
  50. if st.state != TrackState.Tracked:
  51. multi_mean[i][7] = 0
  52. multi_mean, multi_covariance = STrack.shared_kalman.multi_predict(multi_mean, multi_covariance)
  53. for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):
  54. stracks[i].mean = mean
  55. stracks[i].covariance = cov
  56. def activate(self, kalman_filter, frame_id):
  57. """Start a new tracklet"""
  58. self.kalman_filter = kalman_filter
  59. self.track_id = self.next_id()
  60. self.mean, self.covariance = self.kalman_filter.initiate(self.tlwh_to_xyah(self._tlwh))
  61. self.tracklet_len = 0
  62. self.state = TrackState.Tracked
  63. #self.is_activated = True
  64. self.frame_id = frame_id
  65. self.start_frame = frame_id
  66. def re_activate(self, new_track, frame_id, new_id=False):
  67. self.mean, self.covariance = self.kalman_filter.update(
  68. self.mean, self.covariance, self.tlwh_to_xyah(new_track.tlwh)
  69. )
  70. self.update_features(new_track.curr_feat)
  71. self.tracklet_len = 0
  72. self.state = TrackState.Tracked
  73. self.is_activated = True
  74. self.frame_id = frame_id
  75. if new_id:
  76. self.track_id = self.next_id()
  77. def update(self, new_track, frame_id, update_feature=True):
  78. """
  79. Update a matched track
  80. :type new_track: STrack
  81. :type frame_id: int
  82. :type update_feature: bool
  83. :return:
  84. """
  85. self.frame_id = frame_id
  86. self.tracklet_len += 1
  87. new_tlwh = new_track.tlwh
  88. self.mean, self.covariance = self.kalman_filter.update(
  89. self.mean, self.covariance, self.tlwh_to_xyah(new_tlwh))
  90. self.state = TrackState.Tracked
  91. self.is_activated = True
  92. self.score = new_track.score
  93. if update_feature:
  94. self.update_features(new_track.curr_feat)
  95. @property
  96. # @jit(nopython=True)
  97. def tlwh(self):
  98. """Get current position in bounding box format `(top left x, top left y,
  99. width, height)`.
  100. """
  101. if self.mean is None:
  102. return self._tlwh.copy()
  103. ret = self.mean[:4].copy()
  104. ret[2] *= ret[3]
  105. ret[:2] -= ret[2:] / 2
  106. return ret
  107. @property
  108. # @jit(nopython=True)
  109. def tlbr(self):
  110. """Convert bounding box to format `(min x, min y, max x, max y)`, i.e.,
  111. `(top left, bottom right)`.
  112. """
  113. ret = self.tlwh.copy()
  114. ret[2:] += ret[:2]
  115. return ret
  116. @staticmethod
  117. # @jit(nopython=True)
  118. def tlwh_to_xyah(tlwh):
  119. """Convert bounding box to format `(center x, center y, aspect ratio,
  120. height)`, where the aspect ratio is `width / height`.
  121. """
  122. ret = np.asarray(tlwh).copy()
  123. ret[:2] += ret[2:] / 2
  124. ret[2] /= ret[3]
  125. return ret
  126. def to_xyah(self):
  127. return self.tlwh_to_xyah(self.tlwh)
  128. @staticmethod
  129. # @jit(nopython=True)
  130. def tlbr_to_tlwh(tlbr):
  131. ret = np.asarray(tlbr).copy()
  132. ret[2:] -= ret[:2]
  133. return ret
  134. @staticmethod
  135. # @jit(nopython=True)
  136. def tlwh_to_tlbr(tlwh):
  137. ret = np.asarray(tlwh).copy()
  138. ret[2:] += ret[:2]
  139. return ret
  140. def __repr__(self):
  141. return 'OT_{}_({}-{})'.format(self.track_id, self.start_frame, self.end_frame)
  142. class JDETracker(object):
  143. def __init__(self, opt, frame_rate=30):
  144. self.opt = opt
  145. if int(opt.gpus[0]) >= 0:
  146. opt.device = torch.device('cuda')
  147. else:
  148. opt.device = torch.device('cpu')
  149. print('Creating model...')
  150. ckpt = torch.load(opt.weights, map_location=opt.device) # load checkpoint
  151. self.model = Model(opt.cfg or ckpt['model'].yaml, ch=3, nc=1).to(opt.device) # create
  152. exclude = ['anchor'] if opt.cfg else [] # exclude keys
  153. if type(ckpt['model']).__name__ == "OrderedDict":
  154. state_dict = ckpt['model']
  155. else:
  156. state_dict = ckpt['model'].float().state_dict() # to FP32
  157. state_dict = intersect_dicts(state_dict, self.model.state_dict(), exclude=exclude) # intersect
  158. self.model.load_state_dict(state_dict, strict=False) # load
  159. self.model.cuda().eval()
  160. total_params = sum(p.numel() for p in self.model.parameters())
  161. print(f'{total_params:,} total parameters.')
  162. self.tracked_stracks = [] # type: list[STrack]
  163. self.lost_stracks = [] # type: list[STrack]
  164. self.removed_stracks = [] # type: list[STrack]
  165. self.frame_id = 0
  166. self.det_thresh = opt.conf_thres
  167. self.buffer_size = int(frame_rate / 30.0 * opt.track_buffer)
  168. self.max_time_lost = self.buffer_size
  169. self.mean = np.array(opt.mean, dtype=np.float32).reshape(1, 1, 3)
  170. self.std = np.array(opt.std, dtype=np.float32).reshape(1, 1, 3)
  171. self.kalman_filter = KalmanFilter()
  172. self.low_thres = 0.1
  173. self.high_thres = self.opt.conf_thres + 0.1
  174. def update(self, im_blob, img0,seq_num, save_dir):
  175. self.frame_id += 1
  176. activated_starcks = []
  177. refind_stracks = []
  178. lost_stracks = []
  179. removed_stracks = []
  180. dets = []
  181. ''' Step 1: Network forward, get detections & embeddings'''
  182. with torch.no_grad():
  183. output = self.model(im_blob, augment=False)
  184. pred, train_out = output[1]
  185. pred = pred[pred[:, :, 4] > self.low_thres]
  186. detections = []
  187. if len(pred) > 0:
  188. dets,x_inds,y_inds = non_max_suppression_and_inds(pred[:,:6].unsqueeze(0), 0.1, self.opt.nms_thres,method='cluster_diou')
  189. dets = dets.numpy()
  190. if len(dets) != 0:
  191. scale_coords(self.opt.img_size, dets[:, :4], img0.shape).round()
  192. id_feature = output[0][0, y_inds, x_inds, :].cpu().numpy()
  193. remain_inds = dets[:, 4] > self.opt.conf_thres
  194. inds_low = dets[:, 4] > self.low_thres
  195. inds_high = dets[:, 4] < self.opt.conf_thres
  196. inds_second = np.logical_and(inds_low, inds_high)
  197. dets_second = dets[inds_second]
  198. if id_feature.shape[0] == 1:
  199. id_feature_second = id_feature
  200. else:
  201. id_feature_second = id_feature[inds_second]
  202. dets = dets[remain_inds]
  203. id_feature = id_feature[remain_inds]
  204. detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for
  205. (tlbrs, f) in zip(dets[:, :5], id_feature)]
  206. else:
  207. detections = []
  208. dets_second = []
  209. id_feature_second = []
  210. else:
  211. detections = []
  212. dets_second = []
  213. id_feature_second = []
  214. ''' Add newly detected tracklets to tracked_stracks'''
  215. unconfirmed = []
  216. tracked_stracks = [] # type: list[STrack]
  217. for track in self.tracked_stracks:
  218. if not track.is_activated:
  219. unconfirmed.append(track)
  220. else:
  221. tracked_stracks.append(track)
  222. ''' Step 2: First association, with embedding'''
  223. strack_pool = joint_stracks(tracked_stracks, self.lost_stracks)
  224. # Predict the current location with KF
  225. #for strack in strack_pool:
  226. #strack.predict()
  227. STrack.multi_predict(strack_pool)
  228. dists = matching.embedding_distance(strack_pool, detections)
  229. dists = matching.fuse_motion(self.kalman_filter, dists, strack_pool, detections)
  230. #dists = matching.iou_distance(strack_pool, detections)
  231. matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.4)
  232. for itracked, idet in matches:
  233. track = strack_pool[itracked]
  234. det = detections[idet]
  235. if track.state == TrackState.Tracked:
  236. track.update(detections[idet], self.frame_id)
  237. activated_starcks.append(track)
  238. else:
  239. track.re_activate(det, self.frame_id, new_id=False)
  240. refind_stracks.append(track)
  241. # vis
  242. track_features, det_features, cost_matrix, cost_matrix_det, cost_matrix_track = [],[],[],[],[]
  243. if self.opt.vis_state == 1 and self.frame_id % 20 == 0:
  244. if len(dets) != 0:
  245. for i in range(0, dets.shape[0]):
  246. bbox = dets[i][0:4]
  247. cv2.rectangle(img0, (int(bbox[0]), int(bbox[1])),(int(bbox[2]), int(bbox[3])),(0, 255, 0), 2)
  248. track_features, det_features, cost_matrix, cost_matrix_det, cost_matrix_track = matching.vis_id_feature_A_distance(strack_pool, detections)
  249. vis_feature(self.frame_id,seq_num,img0,track_features,
  250. det_features, cost_matrix, cost_matrix_det, cost_matrix_track, max_num=5, out_path=save_dir)
  251. ''' Step 3: Second association, with IOU'''
  252. detections = [detections[i] for i in u_detection]
  253. r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]
  254. dists = matching.iou_distance(r_tracked_stracks, detections)
  255. matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5)
  256. for itracked, idet in matches:
  257. track = r_tracked_stracks[itracked]
  258. det = detections[idet]
  259. if track.state == TrackState.Tracked:
  260. track.update(det, self.frame_id)
  261. activated_starcks.append(track)
  262. else:
  263. track.re_activate(det, self.frame_id, new_id=False)
  264. refind_stracks.append(track)
  265. # association the untrack to the low score detections
  266. if len(dets_second) > 0:
  267. detections_second = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for
  268. (tlbrs, f) in zip(dets_second[:, :5], id_feature_second)]
  269. else:
  270. detections_second = []
  271. second_tracked_stracks = [r_tracked_stracks[i] for i in u_track if r_tracked_stracks[i].state == TrackState.Tracked]
  272. dists = matching.iou_distance(second_tracked_stracks, detections_second)
  273. matches, u_track, u_detection_second = matching.linear_assignment(dists, thresh=0.4)
  274. for itracked, idet in matches:
  275. track = second_tracked_stracks[itracked]
  276. det = detections_second[idet]
  277. if track.state == TrackState.Tracked:
  278. track.update(det, self.frame_id)
  279. activated_starcks.append(track)
  280. else:
  281. track.re_activate(det, self.frame_id, new_id=False)
  282. refind_stracks.append(track)
  283. for it in u_track:
  284. track = second_tracked_stracks[it]
  285. if not track.state == TrackState.Lost:
  286. track.mark_lost()
  287. lost_stracks.append(track)
  288. '''Deal with unconfirmed tracks, usually tracks with only one beginning frame'''
  289. detections = [detections[i] for i in u_detection]
  290. dists = matching.iou_distance(unconfirmed, detections)
  291. matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)
  292. for itracked, idet in matches:
  293. unconfirmed[itracked].update(detections[idet], self.frame_id)
  294. activated_starcks.append(unconfirmed[itracked])
  295. for it in u_unconfirmed:
  296. track = unconfirmed[it]
  297. track.mark_removed()
  298. removed_stracks.append(track)
  299. """ Step 4: Init new stracks"""
  300. for inew in u_detection:
  301. track = detections[inew]
  302. if track.score < self.high_thres:
  303. continue
  304. track.activate(self.kalman_filter, self.frame_id)
  305. activated_starcks.append(track)
  306. """ Step 5: Update state"""
  307. for track in self.lost_stracks:
  308. if self.frame_id - track.end_frame > self.max_time_lost:
  309. track.mark_removed()
  310. removed_stracks.append(track)
  311. # print('Ramained match {} s'.format(t4-t3))
  312. self.tracked_stracks = [t for t in self.tracked_stracks if t.state == TrackState.Tracked]
  313. self.tracked_stracks = joint_stracks(self.tracked_stracks, activated_starcks)
  314. self.tracked_stracks = joint_stracks(self.tracked_stracks, refind_stracks)
  315. self.lost_stracks = sub_stracks(self.lost_stracks, self.tracked_stracks)
  316. self.lost_stracks.extend(lost_stracks)
  317. self.lost_stracks = sub_stracks(self.lost_stracks, self.removed_stracks)
  318. self.removed_stracks.extend(removed_stracks)
  319. self.tracked_stracks, self.lost_stracks = remove_duplicate_stracks(self.tracked_stracks, self.lost_stracks)
  320. # get scores of lost tracks
  321. output_stracks = [track for track in self.tracked_stracks if track.is_activated]
  322. logger.debug('===========Frame {}=========='.format(self.frame_id))
  323. logger.debug('Activated: {}'.format([track.track_id for track in activated_starcks]))
  324. logger.debug('Refind: {}'.format([track.track_id for track in refind_stracks]))
  325. logger.debug('Lost: {}'.format([track.track_id for track in lost_stracks]))
  326. logger.debug('Removed: {}'.format([track.track_id for track in removed_stracks]))
  327. return output_stracks
  328. def joint_stracks(tlista, tlistb):
  329. exists = {}
  330. res = []
  331. for t in tlista:
  332. exists[t.track_id] = 1
  333. res.append(t)
  334. for t in tlistb:
  335. tid = t.track_id
  336. if not exists.get(tid, 0):
  337. exists[tid] = 1
  338. res.append(t)
  339. return res
  340. def sub_stracks(tlista, tlistb):
  341. stracks = {}
  342. for t in tlista:
  343. stracks[t.track_id] = t
  344. for t in tlistb:
  345. tid = t.track_id
  346. if stracks.get(tid, 0):
  347. del stracks[tid]
  348. return list(stracks.values())
  349. def remove_duplicate_stracks(stracksa, stracksb):
  350. pdist = matching.iou_distance(stracksa, stracksb)
  351. pairs = np.where(pdist < 0.15)
  352. dupa, dupb = list(), list()
  353. for p, q in zip(*pairs):
  354. timep = stracksa[p].frame_id - stracksa[p].start_frame
  355. timeq = stracksb[q].frame_id - stracksb[q].start_frame
  356. if timep > timeq:
  357. dupb.append(q)
  358. else:
  359. dupa.append(p)
  360. resa = [t for i, t in enumerate(stracksa) if not i in dupa]
  361. resb = [t for i, t in enumerate(stracksb) if not i in dupb]
  362. return resa, resb
  363. def vis_feature(frame_id,seq_num,img,track_features, det_features, cost_matrix, cost_matrix_det, cost_matrix_track,max_num=5, out_path='/home/XX/'):
  364. num_zero = ["0000","000","00","0"]
  365. img = cv2.resize(img, (778, 435))
  366. if len(det_features) != 0:
  367. max_f = det_features.max()
  368. min_f = det_features.min()
  369. det_features = np.round((det_features - min_f) / (max_f - min_f) * 255)
  370. det_features = det_features.astype(np.uint8)
  371. d_F_M = []
  372. cutpff_line = [40]*512
  373. for d_f in det_features:
  374. for row in range(45):
  375. d_F_M += [[40]*3+d_f.tolist()+[40]*3]
  376. for row in range(3):
  377. d_F_M += [[40]*3+cutpff_line+[40]*3]
  378. d_F_M = np.array(d_F_M)
  379. d_F_M = d_F_M.astype(np.uint8)
  380. det_features_img = cv2.applyColorMap(d_F_M, cv2.COLORMAP_JET)
  381. feature_img2 = cv2.resize(det_features_img, (435, 435))
  382. #cv2.putText(feature_img2, "det_features", (5, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
  383. else:
  384. feature_img2 = np.zeros((435, 435))
  385. feature_img2 = feature_img2.astype(np.uint8)
  386. feature_img2 = cv2.applyColorMap(feature_img2, cv2.COLORMAP_JET)
  387. #cv2.putText(feature_img2, "det_features", (5, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
  388. feature_img = np.concatenate((img, feature_img2), axis=1)
  389. if len(cost_matrix_det) != 0 and len(cost_matrix_det[0]) != 0:
  390. max_f = cost_matrix_det.max()
  391. min_f = cost_matrix_det.min()
  392. cost_matrix_det = np.round((cost_matrix_det - min_f) / (max_f - min_f) * 255)
  393. d_F_M = []
  394. cutpff_line = [40]*len(cost_matrix_det)*10
  395. for c_m in cost_matrix_det:
  396. add = []
  397. for row in range(len(c_m)):
  398. add += [255-c_m[row]]*10
  399. for row in range(10):
  400. d_F_M += [[40]+add+[40]]
  401. d_F_M = np.array(d_F_M)
  402. d_F_M = d_F_M.astype(np.uint8)
  403. cost_matrix_det_img = cv2.applyColorMap(d_F_M, cv2.COLORMAP_JET)
  404. feature_img2 = cv2.resize(cost_matrix_det_img, (435, 435))
  405. #cv2.putText(feature_img2, "cost_matrix_det", (5, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
  406. else:
  407. feature_img2 = np.zeros((435, 435))
  408. feature_img2 = feature_img2.astype(np.uint8)
  409. feature_img2 = cv2.applyColorMap(feature_img2, cv2.COLORMAP_JET)
  410. #cv2.putText(feature_img2, "cost_matrix_det", (5, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
  411. feature_img = np.concatenate((feature_img, feature_img2), axis=1)
  412. if len(track_features) != 0:
  413. max_f = track_features.max()
  414. min_f = track_features.min()
  415. track_features = np.round((track_features - min_f) / (max_f - min_f) * 255)
  416. track_features = track_features.astype(np.uint8)
  417. d_F_M = []
  418. cutpff_line = [40]*512
  419. for d_f in track_features:
  420. for row in range(45):
  421. d_F_M += [[40]*3+d_f.tolist()+[40]*3]
  422. for row in range(3):
  423. d_F_M += [[40]*3+cutpff_line+[40]*3]
  424. d_F_M = np.array(d_F_M)
  425. d_F_M = d_F_M.astype(np.uint8)
  426. track_features_img = cv2.applyColorMap(d_F_M, cv2.COLORMAP_JET)
  427. feature_img2 = cv2.resize(track_features_img, (435, 435))
  428. #cv2.putText(feature_img2, "track_features", (5, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
  429. else:
  430. feature_img2 = np.zeros((435, 435))
  431. feature_img2 = feature_img2.astype(np.uint8)
  432. feature_img2 = cv2.applyColorMap(feature_img2, cv2.COLORMAP_JET)
  433. #cv2.putText(feature_img2, "track_features", (5, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
  434. feature_img = np.concatenate((feature_img, feature_img2), axis=1)
  435. if len(cost_matrix_track) != 0 and len(cost_matrix_track[0]) != 0:
  436. max_f = cost_matrix_track.max()
  437. min_f = cost_matrix_track.min()
  438. cost_matrix_track = np.round((cost_matrix_track - min_f) / (max_f - min_f) * 255)
  439. d_F_M = []
  440. cutpff_line = [40]*len(cost_matrix_track)*10
  441. for c_m in cost_matrix_track:
  442. add = []
  443. for row in range(len(c_m)):
  444. add += [255-c_m[row]]*10
  445. for row in range(10):
  446. d_F_M += [[40]+add+[40]]
  447. d_F_M = np.array(d_F_M)
  448. d_F_M = d_F_M.astype(np.uint8)
  449. cost_matrix_track_img = cv2.applyColorMap(d_F_M, cv2.COLORMAP_JET)
  450. feature_img2 = cv2.resize(cost_matrix_track_img, (435, 435))
  451. #cv2.putText(feature_img2, "cost_matrix_track", (5, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
  452. else:
  453. feature_img2 = np.zeros((435, 435))
  454. feature_img2 = feature_img2.astype(np.uint8)
  455. feature_img2 = cv2.applyColorMap(feature_img2, cv2.COLORMAP_JET)
  456. #cv2.putText(feature_img2, "cost_matrix_track", (5, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
  457. feature_img = np.concatenate((feature_img, feature_img2), axis=1)
  458. if len(cost_matrix) != 0 and len(cost_matrix[0]) != 0:
  459. max_f = cost_matrix.max()
  460. min_f = cost_matrix.min()
  461. cost_matrix = np.round((cost_matrix - min_f) / (max_f - min_f) * 255)
  462. d_F_M = []
  463. cutpff_line = [40]*len(cost_matrix[0])*10
  464. for c_m in cost_matrix:
  465. add = []
  466. for row in range(len(c_m)):
  467. add += [255-c_m[row]]*10
  468. for row in range(10):
  469. d_F_M += [[40]+add+[40]]
  470. d_F_M = np.array(d_F_M)
  471. d_F_M = d_F_M.astype(np.uint8)
  472. cost_matrix_img = cv2.applyColorMap(d_F_M, cv2.COLORMAP_JET)
  473. feature_img2 = cv2.resize(cost_matrix_img, (435, 435))
  474. #cv2.putText(feature_img2, "cost_matrix", (5, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
  475. else:
  476. feature_img2 = np.zeros((435, 435))
  477. feature_img2 = feature_img2.astype(np.uint8)
  478. feature_img2 = cv2.applyColorMap(feature_img2, cv2.COLORMAP_JET)
  479. #cv2.putText(feature_img2, "cost_matrix", (5, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
  480. feature_img = np.concatenate((feature_img, feature_img2), axis=1)
  481. dst_path = out_path + "/" + seq_num + "_" + num_zero[len(str(frame_id))-1] + str(frame_id) + '.png'
  482. cv2.imwrite(dst_path, feature_img)