def run(params, capture, detector, reid): win_name = 'Multi camera tracking' config = {} if len(params.config): config = read_py_config(params.config) tracker = MultiCameraTracker(capture.get_num_sources(), reid, **config) thread_body = FramesThreadBody(capture, max_queue_length=len(capture.captures) * 2) frames_thread = Thread(target=thread_body) frames_thread.start() if len(params.output_video): video_output_size = (1920 // capture.get_num_sources(), 1080) fourcc = cv.VideoWriter_fourcc(*'XVID') output_video = cv.VideoWriter(params.output_video, fourcc, 24.0, video_output_size) else: output_video = None while thread_body.process: start = time.time() try: frames = thread_body.frames_queue.get_nowait() except queue.Empty: frames = None if frames is None: continue all_detections = detector.get_detections(frames) all_masks = [[] for _ in range(len(all_detections))] for i, detections in enumerate(all_detections): all_detections[i] = [det[0] for det in detections] all_masks[i] = [det[2] for det in detections if len(det) == 3] tracker.process(frames, all_detections, all_masks) tracked_objects = tracker.get_tracked_objects() fps = round(1 / (time.time() - start), 1) vis = visualize_multicam_detections(frames, tracked_objects, fps) if not params.no_show: cv.imshow(win_name, vis) if cv.waitKey(1) == 27: break if output_video: output_video.write(cv.resize(vis, video_output_size)) thread_body.process = False frames_thread.join() if len(params.history_file): history = tracker.get_all_tracks_history() with open(params.history_file, 'w') as outfile: json.dump(history, outfile)
def run(params, config, capture, detector, reid): win_name = 'Multi camera tracking' frame_number = 0 avg_latency = AverageEstimator() output_detections = [[] for _ in range(capture.get_num_sources())] key = -1 if config['normalizer_config']['enabled']: capture.add_transform( NormalizerCLAHE( config['normalizer_config']['clip_limit'], config['normalizer_config']['tile_size'], )) tracker = MultiCameraTracker(capture.get_num_sources(), reid, config['sct_config'], **config['mct_config'], visual_analyze=config['analyzer']) thread_body = FramesThreadBody(capture, max_queue_length=len(capture.captures) * 2) frames_thread = Thread(target=thread_body) frames_thread.start() if len(params.output_video): frame_size, fps = capture.get_source_parameters() target_width, target_height = get_target_size( frame_size, None, **config['visualization_config']) video_output_size = (target_width, target_height) fourcc = cv.VideoWriter_fourcc(*'XVID') output_video = cv.VideoWriter(params.output_video, fourcc, min(fps), video_output_size) else: output_video = None prev_frames = thread_body.frames_queue.get() detector.run_async(prev_frames, frame_number) presenter = monitors.Presenter(params.utilization_monitors, 0) while thread_body.process: if not params.no_show: key = check_pressed_keys(key) if key == 27: break presenter.handleKey(key) start = time.perf_counter() try: frames = thread_body.frames_queue.get_nowait() except queue.Empty: frames = None if frames is None: continue all_detections = detector.wait_and_grab() if params.save_detections: update_detections(output_detections, all_detections, frame_number) frame_number += 1 detector.run_async(frames, frame_number) all_masks = [[] for _ in range(len(all_detections))] for i, detections in enumerate(all_detections): all_detections[i] = [det[0] for det in detections] all_masks[i] = [det[2] for det in detections if len(det) == 3] tracker.process(prev_frames, all_detections, all_masks) tracked_objects = tracker.get_tracked_objects() latency = max(time.perf_counter() - start, sys.float_info.epsilon) avg_latency.update(latency) fps = round(1. / latency, 1) vis = visualize_multicam_detections(prev_frames, tracked_objects, fps, **config['visualization_config']) presenter.drawGraphs(vis) if not params.no_show: cv.imshow(win_name, vis) if output_video: output_video.write(cv.resize(vis, video_output_size)) print('\rProcessing frame: {}, fps = {} (avg_fps = {:.3})'.format( frame_number, fps, 1. / avg_latency.get()), end="") prev_frames, frames = frames, prev_frames print(presenter.reportMeans()) print('') thread_body.process = False frames_thread.join() if len(params.history_file): save_json_file(params.history_file, tracker.get_all_tracks_history(), description='History file') if len(params.save_detections): save_json_file(params.save_detections, output_detections, description='Detections') if len(config['embeddings']['save_path']): save_embeddings(tracker.scts, **config['embeddings'])
def main(): """Visualize the results of the multi camera multi person tracker demo""" parser = argparse.ArgumentParser(description='Multi camera multi person \ tracking visualization demo script') parser.add_argument('-i', type=str, nargs='+', help='Input videos') parser.add_argument('--history_file', type=str, default='', required=True, help='File with tracker history') parser.add_argument('--output_video', type=str, default='', required=False, help='Output video file') parser.add_argument('--gt_files', type=str, nargs='+', required=False, help='Files with ground truth annotation') parser.add_argument('--timeline', type=str, default='', help='Plot and save timeline') parser.add_argument('--match_gt_ids', default=False, action='store_true', help='Match GT ids to ids from history') parser.add_argument('--merge_outputs', default=False, action='store_true', help='Merge GT and history tracks into one frame') args = parser.parse_args() capture = MulticamCapture(args.i) with open(args.history_file) as hist_f: history = json.load(hist_f) assert len(history) == capture.get_num_sources() # Configure output video files output_video = None output_video_gt = None frame_size, fps_source = capture.get_source_parameters() if len(args.output_video): video_output_size, fps = calc_output_video_params(frame_size, fps_source, args.gt_files, args.merge_outputs) fourcc = cv.VideoWriter_fourcc(*'XVID') output_video = cv.VideoWriter(args.output_video, fourcc, fps, video_output_size) if args.gt_files and not args.merge_outputs: ext = args.output_video.split('.')[-1] output_path = args.output_video[:len(args.output_video) - len(ext) - 1] + '_gt.' + ext output_video_gt = cv.VideoWriter(output_path, fourcc, fps, video_output_size) # Read GT tracks if necessary if args.gt_files: assert len(args.gt_files) == capture.get_num_sources() gt_tracks, _ = read_gt_tracks(args.gt_files) accs = [mm.MOTAccumulator(auto_id=True) for _ in args.gt_files] else: gt_tracks = None # If we need for matching GT IDs, accumulate metrics if gt_tracks and args.match_gt_ids: accumulate_mot_metrics(accs, gt_tracks, history) match_gt_indices(gt_tracks, history, accs) metrics_accumulated = True else: metrics_accumulated = False # Process frames win_name = 'Multi camera tracking history visualizer' time = 0 key = -1 while True: print('\rVisualizing frame: {}'.format(time), end="") key = check_pressed_keys(key) if key == 27: break has_frames, frames = capture.get_frames() if not has_frames: break if gt_tracks: gt_detections = get_detections_from_tracks(gt_tracks, time) vis_gt = visualize_multicam_detections(copy.deepcopy(frames), gt_detections, fps='Ground truth') else: vis_gt = None active_detections = get_detections_from_tracks(history, time) vis = visualize_multicam_detections(frames, active_detections) if vis_gt is not None: if args.merge_outputs: vis = np.hstack([vis, vis_gt]) cv.imshow(win_name, vis) else: cv.imshow('GT', vis_gt) cv.imshow(win_name, vis) else: cv.imshow(win_name, vis) time += 1 if output_video: output_video.write(cv.resize(vis, video_output_size)) if vis_gt is not None and output_video_gt is not None: output_video_gt.write(cv.resize(vis_gt, video_output_size)) if len(args.timeline): for i in range(len(history)): log.info('Source_{}: drawing timeline...'.format(i)) plot_timeline(i, time, history[i], save_path=args.timeline, name='SCT') if gt_tracks: for i in range(len(gt_tracks)): log.info('GT_{}: drawing timeline...'.format(i)) plot_timeline(i, time, gt_tracks[i], save_path=args.timeline, name='GT') if gt_tracks: if not metrics_accumulated: accumulate_mot_metrics(accs, gt_tracks, history) mh = mm.metrics.create() summary = mh.compute_many(accs, metrics=mm.metrics.motchallenge_metrics, generate_overall=True, names=['video ' + str(i) for i in range(len(accs))]) strsummary = mm.io.render_summary(summary, formatters=mh.formatters, namemap=mm.io.motchallenge_metric_names) print(strsummary)
def run(params, config, capture, detector, reid): win_name = 'Multi camera tracking' frame_number = 0 output_detections = [[] for _ in range(capture.get_num_sources())] key = -1 if config.normalizer_config.enabled: capture.add_transform( NormalizerCLAHE( config.normalizer_config.clip_limit, config.normalizer_config.tile_size, )) tracker = MultiCameraTracker(capture.get_num_sources(), reid, config.sct_config, **vars(config.mct_config), visual_analyze=config.analyzer) thread_body = FramesThreadBody(capture, max_queue_length=len(capture.captures) * 2) frames_thread = Thread(target=thread_body) frames_thread.start() frames_read = False set_output_params = False prev_frames = thread_body.frames_queue.get() detector.run_async(prev_frames, frame_number) metrics = PerformanceMetrics() presenter = monitors.Presenter(params.utilization_monitors, 0) while thread_body.process: if not params.no_show: key = check_pressed_keys(key) if key == 27: break presenter.handleKey(key) start_time = time.perf_counter() try: frames = thread_body.frames_queue.get_nowait() frames_read = True except queue.Empty: frames = None if frames is None: continue all_detections = detector.wait_and_grab() if params.save_detections: update_detections(output_detections, all_detections, frame_number) frame_number += 1 detector.run_async(frames, frame_number) all_masks = [[] for _ in range(len(all_detections))] for i, detections in enumerate(all_detections): all_detections[i] = [det[0] for det in detections] all_masks[i] = [det[2] for det in detections if len(det) == 3] tracker.process(prev_frames, all_detections, all_masks) tracked_objects = tracker.get_tracked_objects() vis = visualize_multicam_detections( prev_frames, tracked_objects, **vars(config.visualization_config)) metrics.update(start_time, vis) presenter.drawGraphs(vis) if not params.no_show: cv.imshow(win_name, vis) if frames_read and not set_output_params: set_output_params = True if len(params.output_video): frame_size = [frame.shape[::-1] for frame in frames] fps = capture.get_fps() target_width, target_height = get_target_size( frame_size, None, **vars(config.visualization_config)) video_output_size = (target_width, target_height) fourcc = cv.VideoWriter_fourcc(*'XVID') output_video = cv.VideoWriter(params.output_video, fourcc, min(fps), video_output_size) else: output_video = None if set_output_params and output_video: output_video.write(cv.resize(vis, video_output_size)) prev_frames, frames = frames, prev_frames metrics.log_total() for rep in presenter.reportMeans(): log.info(rep) thread_body.process = False frames_thread.join() if len(params.history_file): save_json_file(params.history_file, tracker.get_all_tracks_history(), description='History file') if len(params.save_detections): save_json_file(params.save_detections, output_detections, description='Detections') if len(config.embeddings.save_path): save_embeddings(tracker.scts, **vars(config.embeddings))
def run(params, capture, detector, reid, jot): #params : args 임 win_name = 'TEAM_KOTLIN' config = {} if len(params.config): config = read_py_config(params.config) tracker = MultiCameraTracker(capture.get_num_sources(), reid, **config) thread_body = FramesThreadBody(capture, max_queue_length=len(capture.captures) * 2) frames_thread = Thread(target=thread_body) frames_thread.start() if len(params.output_video): video_output_size = (1920 // capture.get_num_sources(), 1080) fourcc = cv.VideoWriter_fourcc(*'XVID') output_video = cv.VideoWriter(params.output_video, fourcc, 24.0, video_output_size) else: output_video = None print("##################################################################") while thread_body.process: start = time.time() try: frames = thread_body.frames_queue.get_nowait() except queue.Empty: frames = None if frames is None: continue all_detections = detector.get_detections(frames) #all_detections 좌표 성분 : ((left, right, top, bot), confidence) 값들의 리스트 # 1번 영상의 디텍션 위치는 앞에 2번 영상의 디텍션 위치는 뒤에 표시됨 # all_detextions : [[1번영상 사람들의 좌표, 컨디션], [2번 영상 사람들의 좌표, 컨디션]] all_masks = [[] for _ in range(len(all_detections)) ] # 디텍션 갯수만큼 비어있는 마스크 리스트 만듬 for i, detections in enumerate(all_detections): all_detections[i] = [det[0] for det in detections] all_masks[i] = [det[2] for det in detections if len(det) == 3] feature_data = tracker.process(frames, all_detections, all_masks) tracked_objects = tracker.get_tracked_objects() #20200511 추가 track_data = copy.deepcopy(feature_data) for track in track_data: del track['features'] del track['boxes'] del track['timestamps'] del track['cam_id'] #jottable 넘기는 함수 콜 jot.check_jot(tracked_objects, frames, track_data) fps = round(1 / (time.time() - start), 1) #시간 처리 dates = datetime.now() vis = visualize_multicam_detections(frames, tracked_objects, fps, dates) if not params.no_show: cv.imshow(win_name, vis) if cv.waitKey(1) == 27: break if output_video: output_video.write(cv.resize(vis, video_output_size)) thread_body.process = False frames_thread.join() if len(params.history_file): history = tracker.get_all_tracks_history() with open(params.history_file, 'w') as outfile: json.dump(history, outfile) print("##################################################################")
def run(params, config, capture, detector, reid): ix,iy = -1,-1 pts_src = np.array([[561,1022],[990,698],[486,273],[95,504]],dtype='float32') pts_dest = np.array([[0,0],[0,400],[400,700],[0,700]],dtype='float32') # calculate matrix H h, status = cv.findHomography(pts_src,pts_dest) win_name = 'Multi camera tracking' frame_number = 0 avg_latency = AverageEstimator() output_detections = [[] for _ in range(capture.get_num_sources())] key = -1 refObj = [] if config['normalizer_config']['enabled']: capture.add_transform( NormalizerCLAHE( config['normalizer_config']['clip_limit'], config['normalizer_config']['tile_size'], ) ) tracker = MultiCameraTracker(capture.get_num_sources(), reid, config['sct_config'], **config['mct_config'], visual_analyze=config['analyzer']) thread_body = FramesThreadBody(capture, max_queue_length=len(capture.captures) * 2) frames_thread = Thread(target=thread_body) frames_thread.start() if len(params.output_video): frame_size, fps = capture.get_source_parameters() target_width, target_height = get_target_size(frame_size, None, **config['visualization_config']) video_output_size = (target_width, target_height) fourcc = cv.VideoWriter_fourcc(*'XVID') output_video = cv.VideoWriter(params.output_video,cv.VideoWriter_fourcc('M','J','P','G'),min(fps),video_output_size) # output_video = cv.VideoWriter(params.output_video, fourcc, min(fps), video_output_size) else: output_video = None prev_frames = thread_body.frames_queue.get() detector.run_async(prev_frames, frame_number) while thread_body.process: if not params.no_show: key = check_pressed_keys(key) if key == 27: break start = time.time() try: frames = thread_body.frames_queue.get_nowait() except queue.Empty: frames = None if frames is None: continue all_detections = detector.wait_and_grab() for det in all_detections: for obj in det: print("Boxes:",obj[0]) print("Confidence:",obj[1]) if params.save_detections: update_detections(output_detections, all_detections, frame_number) frame_number += 1 detector.run_async(frames, frame_number) all_masks = [[] for _ in range(len(all_detections))] for i, detections in enumerate(all_detections): all_detections[i] = [det[0] for det in detections] all_masks[i] = [det[2] for det in detections if len(det) == 3] tracker.process(prev_frames, all_detections, all_masks) tracked_objects = tracker.get_tracked_objects() latency = time.time() - start avg_latency.update(latency) fps = round(1. / latency, 1) vis = visualize_multicam_detections(prev_frames, tracked_objects, fps, **config['visualization_config'],h=h) if not params.no_show: cv.setMouseCallback(win_name, getMousePointer) if ix!=-1 and iy!=-1: refObj.append((ix,iy)) ix=-1 iy=-1 print(len(refObj)) if len(refObj)==2: print("Len 2 Rectangle Drawn.") vis = cv.rectangle(vis, refObj[0], refObj[1],(255,0,0), 2) refObj.clear() cv.imshow(win_name, vis) # cv.imwrite("refPicture.png",vis) if output_video: output_video.write(cv.resize(vis, video_output_size)) # print('\rProcessing frame: {}, fps = {} (avg_fps = {:.3})'.format( # frame_number, fps, 1. / avg_latency.get()), end="") prev_frames, frames = frames, prev_frames # print('') thread_body.process = False frames_thread.join() if len(params.history_file): save_json_file(params.history_file, tracker.get_all_tracks_history(), description='History file') if len(params.save_detections): save_json_file(params.save_detections, output_detections, description='Detections') if len(config['embeddings']['save_path']): save_embeddings(tracker.scts, **config['embeddings'])