def __init__(self, args, tube_queue, frame_queue, running): self.yolo = YOLO(args) self.tracker = Tracker(args.max_age, args.min_hits) self.max_frame = args.max_frame self.video_fps = args.video_fps self.batch = args.batch self.tube_queue = tube_queue self.frame_queue = frame_queue self.running = running src = args.video_src if src.isdigit(): src = int(src) elif not os.path.exists(src): print('TUBE: cannot read video!') return self.cap = cv2.VideoCapture(src) self.tube_holder = TubeHolder() self.valid = True
def write(): st.markdown(f'# {PAGE_TITLE}') # initialize models user = User() user_id = user.db_user['id'] tracker = Tracker() # TBU - make hours_back based on goal type (calories 24, workout 7*24) st.markdown('## 1. Choose Goal & Submit Entry') choose = submit_entry(tracker, user_id) st.markdown('## 2. Review Entries') df = tracker.existing_entries df = df[df['entry_type'] == choose] sum = df.sum() sum['entry_type'] = 'Total' sum['description'] = '24hr Total' df = df.append(sum, ignore_index=True) df.drop(columns=['user_id', 'created_at'], inplace=True) st.write(df) st.markdown('## 3. Create New Entry Type') create_type(tracker, user_id) footer()
def main(): args = parse_args() cfg = get_config() cfg.merge_from_file(args.config_deepsort) cam = Camera(args) cam.open() if not cam.is_opened: sys.exit('Failed to open camera!') tracker = Tracker(cfg, args.engine_path) cam.start() open_window(WINDOW_NAME, args.image_width, args.image_height, 'TrtYolov3_deepsort') loop_and_track(cam, tracker, args) cam.stop() cam.release() cv2.destroyAllWindows() if args.filename: print('result video saved at (%s)' % (args.output_file)) else: print('close')
async def send_track(message: types.Message): try: track_info_dict = Tracker(track_code=message.text).track() track_info = ( f"From: {track_info_dict['js']['Content']['cityFrom']['name']} \n" f"To: {track_info_dict['js']['Content']['cityTo']['name']}\n" f"Status: {track_info_dict['js']['Content']['status']['name']}\n" f"Tel. 1: {track_info_dict['js']['Content']['receiverStockPhone'][0]['phoneNumber']}\n" f"Tel. 2: {track_info_dict['js']['Content']['receiverStockPhone'][1]['phoneNumber']}\n\n" ) for data in track_info_dict["js"]["Content"]["trackingDetails"]: track_info += f"{data['date']}\n" track_info += f"{data['statusName']} | {data['cityName']}\n\n" except Exception as e: track_info = e if track_info == "'Content'": track_info = "Order not found" await message.reply(track_info, reply=False)
def run_project_demo(args): # Load video video_path = args.video_filepath video = cv2.VideoCapture(video_path) # Load network (for CPU or PI/NCS2) pi_usage = args.pi net, net_input_shape = load_person_detection_retail_0013_to_IE(pi_usage) # Load Tracker figure_path = args.figure_filepath tracker = Tracker(figure_path) # Loop in video FLAG = True while FLAG: _, frame = video.read() if not _: print("fin de video") FLAG = False continue filtered_detections = get_results_from_person_detection_retail_0013( net, net_input_shape, frame) # frame_with_filtered_detections = put_in_frame(filtered_detections,frame) # cv2.imshow("detecting", frame_with_filtered_detections) # tracked_detections = tracker.track_dets(filtered_detections) # frame_with_tracked_detections = put_tracked_in_frame(tracked_detections,frame) # cv2.imshow("tracking", frame_with_tracked_detections) tracker.track_dets(filtered_detections) frame_with_tracking_regions_and_counting = tracker.put_tracking_in_frame_with_regions_with_couting( frame) cv2.imshow("tracking with data showing", frame_with_tracking_regions_and_counting) key = cv2.waitKey(1) & 0xFF if key == ord("q"): break cv2.destroyAllWindows() # save data counted save_file = args.save_filepath tracker.save_data(save_file)
shutil.rmtree(e.path) except OSError: # Already removed pass r = ruTorrent( options.url ) if options.basic_auth: r.set_basic_auth_hash( options.basic_auth ) tracker = Tracker( options.log_dir, 'rutorrent-track' ) g = r.commands.get_torrent_list() if True: torrent_count = 0 remove_old_output_directories( options.remove_old_output_compare_file, 300 # Five hours ) remove_empty_directories() for t in g: torrent_count += 1
# Parse the command line arguments cmdline_args = parserags(sys.argv[1:]) # First Initialize the logging module if cmdline_args.debug: init_logging(logging.DEBUG) else: init_logging(logging.INFO) # Get filename sheetname = cmdline_args.sheet_name log.info("Starting the program to pull all data from {0}".format(cmdline_args.command)) # Call program based on the program command called. filename = None if cmdline_args.command == 'tracker': # If tracker filename = create_filename(cmdline_args.command, cmdline_args.project_id) tracker = Tracker(filename, sheetname, cmdline_args.project_id, cmdline_args.query_string, cmdline_args.tracker_token) tracker.TrackerWorkflow() elif cmdline_args.command == 'zendesk': # If zendesk filename = create_filename(cmdline_args.command) zendesk = ZendeskHC(filename, sheetname, cmdline_args.zd_username, cmdline_args.zd_password, cmdline_args.zd_endpoint, cmdline_args.query_string) zendesk.ZendeskWorkflow() else: # It will never reach here since argparse will not anyways allow. log.error("Invalid option specified on the command line arguments") # Success message current_loc_filename = os.getcwd() + "/" + filename log.info("The program has successfully completed, the data is stored on location: {0}".format(current_loc_filename))
break if root is None: print(fps[i]) continue _pic = cv2.imread(os.path.join(root, fps[i] + '.jpg'))[..., ::-1] save_fp = os.path.join(save, fps[i] + ".txt") pic, (s_h, s_w), pad = get_input(_pic, size) s_h, s_w = s_h / size[1], s_w / size[0] num = int(fps[i].split('_')[-1]) vid_name = '_'.join(fps[i].split('_')[:-1]) if vid_name != curr_vid: curr_vid = vid_name tracker = Tracker(args) if num % 10 != 0: continue prev_frame_fp = None prev_frame = None if num > 1: prev_frame_fp = "_".join( fps[i].split("_")[:-1]) + "_" + str(num - skip_frame) if prev_frame_fp is not None and os.path.exists( os.path.join(root, prev_frame_fp + '.jpg')): _pic = cv2.imread(os.path.join(root, prev_frame_fp + '.jpg'))[..., ::-1] prev_frame, (s_h, s_w), pad = get_input(_pic, size) s_h, s_w = s_h / size[1], s_w / size[0]
class TubeExtractor: def __init__(self, args, tube_queue, frame_queue, running): self.yolo = YOLO(args) self.tracker = Tracker(args.max_age, args.min_hits) self.max_frame = args.max_frame self.video_fps = args.video_fps self.batch = args.batch self.tube_queue = tube_queue self.frame_queue = frame_queue self.running = running src = args.video_src if src.isdigit(): src = int(src) elif not os.path.exists(src): print('TUBE: cannot read video!') return self.cap = cv2.VideoCapture(src) self.tube_holder = TubeHolder() self.valid = True def get_fps(self): pass # return self. def dummy_tracker(self, dets): res = [] cnt = 0 for d in dets: res.append(d[:4] + [cnt]) cnt += 1 return res def run(self): frame_id = 0 total_time = 0 while self.running[0]: ret, frame = self.cap.read() if not ret: print('TUBE: cannot read frame!') self.running[0] = False break frame_id += 1 if frame_id > self.max_frame and self.max_frame > 0: print('TUBE: Exceeds max frame id %d' % self.max_frame) self.running[0] = False break cur_time = time() det = self.yolo.detect_frame(frame) det_people, det_obj = self.yolo.parse_det(det) # print(det_people) for i in range(len(det_people)): det_people[i] = det_people[i][:4] tks = self.tracker.update(det_people) # tks = self.dummy_tracker(det_people) # use det res as tracking res self.frame_queue.write({ 'frame_id': frame_id, 'frame': frame, 'time': cur_time }) self.tube_holder.add_tks(tks, frame, frame_id) total_time += time() - cur_time if frame_id % (self.batch * self.video_fps) == 0: if frame_id == 0: continue print('TUBE: FPS %d' % (self.batch * self.video_fps / total_time)) total_time = 0 # print('tubes: %s' % `self.tube_holder.summary()`) self.tube_queue.write(self.tube_holder.tubes.copy()) self.tube_holder.clear() print('TUBE: stopping...') self.cap.release() print('TUBE: ended')
def run(opt): # output dir if os.path.exists(opt.save_dir): shutil.rmtree(opt.save_dir) os.makedirs(opt.save_dir) # load dataset dataset = Dataloader(source=opt.source, imgsz=opt.img_size).dataset # load object detection model, and weights detector = Detector(detector_type=opt.detector_type, cfg_file=opt.detector_cfg_file) detector.run_through_once(opt.img_size) # 空跑一次 # load object tracking model tracker = Tracker(tracker_type=opt.tracker_type, cfg_file=opt.tracker_cfg_file) # load pose detection model poser = Poser(poser_type=opt.poser_type, cfg_file=opt.poser_cfg_file) # load classifier model clssifier = Classifier(classifier_type=opt.classifier_type, cfg_file=opt.classifier_cfg_file) print(detector.device, detector.cfg) filt_with_txt = False # 先分析一下status标注文件.txt,存在的才进行检测,这样能加快速度 if filt_with_txt: from classifier.data_analyse import anaylise_label label_ret = anaylise_label() label_stems = [x[0] for x in label_ret] for img_idx, (path, img, im0s, vid_cap) in enumerate(dataset): # print(type(img), type(im0s)) # print(type(im0s), im0s.shape) if dataset.is_camera: im0s = im0s[0] path = f'{path[0]}/{img_idx:0<6}.jpg' if filt_with_txt: fold_stem = path.split('/')[-2] idx = label_stems.index(fold_stem) # print(fold_stem, label_stems, idx) img_stem = Path(path).stem valid_stems = [Path(x).stem for x in label_ret[idx][-1]] in_it = f'track_{img_stem}' in valid_stems # print(path, in_it, label_ret[idx][-1][0]) if not in_it: continue # img: [3, w, h], preprocess, inference, NMS, det_ret = detector.detect( path, img, im0s) # detect result: nparray, [num_obj, 6] 6: xyxy,conf,cls # detector.imshow(im0s, det_ret) # track tra_ret = tracker.track( det_ret, im0s) # track result: list, [num_obj, 7], 7: xyxy, cls, tid, trace # print(tra_ret[:, 5]) # tracker.imshow(im0s, tra_ret, path) # pose detect pose_ret = poser.detect_pose(tra_ret, im0s, path, return_type='zzd') # zzd format: np.array(object): [num_obj, 10],10: xyxy cls tid trace keypoints kp_score proposal_score # print(pose_ret) poser.imshow(im0s, pose_ret, path, resize=(1280, 720)) # classifier if opt.feature_save_dir is not None: # 保存特征的 clssifier.build_and_save_feature(pose_ret, path, save_dir=opt.feature_save_dir) print(f'\rsaving features: [{img_idx + 1:>3}/{len(dataset)}] ', end='') continue # status_ret = clssifier.detect_status(pose_ret, path, is_camera=dataset.is_camera) # zzd format: np.array(object): [num_obj, 12], 12: 比10多了status_idx和status # clssifier.imshow(im0s, status_ret, show_name='x', resize=(1280, 720)) # print(status_ret) if img_idx == 10: if cv2.waitKeyEx(0) == ord('q'): raise StopIteration
patterns['s-blue'] = MapPattern(station_light_map, active_stations_func, TrackerColor(med, dark, med)) ## North-bound Blue line active_stations_func = dg.get_active_stations_func('901', dg.NORTH, blue_stations_coord_map) patterns['n-blue'] = MapPattern(station_light_map, active_stations_func, TrackerColor(dark, dark, med)) ## South-bound Red line active_stations_func = dg.get_active_stations_func('903', dg.SOUTH, red_stations_coord_map) patterns['s-red'] = MapPattern(station_light_map, active_stations_func, TrackerColor(med, 0.5 * med, dark)) ## North-bound Red line active_stations_func = dg.get_active_stations_func('903', dg.NORTH, red_stations_coord_map) patterns['n-red'] = MapPattern(station_light_map, active_stations_func, TrackerColor(med, dark, dark)) # Startup the tracker t = Tracker(patterns, StripController(strip)) t.start() while (True): continue
def run_epoch(self, phase, epoch, data_loader, rank): model_with_loss = self.model_with_loss if phase == 'train': model_with_loss.train() else: model_with_loss.eval() torch.cuda.empty_cache() results = {} data_time, batch_time = AverageMeter(), AverageMeter() avg_loss_stats = { l: AverageMeter() for l in self.loss_stats if l in ('tot', 'hm', 'wh', 'tracking') } num_iters = len( data_loader ) if self.args.num_iters[phase] < 0 else self.args.num_iters[phase] bar = Bar('{}'.format("tracking"), max=num_iters) end = time.time() for iter_id, batch in enumerate(data_loader): if iter_id >= num_iters: break data_time.update(time.time() - end) for k in batch: if k in ('fpath', 'prev_fpath'): continue if type(batch[k]) != list: batch[k] = batch[k].to(self.args.device, non_blocking=True) else: for i in range(len(batch[k])): batch[k][i] = batch[k][i].to(self.args.device, non_blocking=True) output, loss, loss_stats = model_with_loss(batch) loss = loss.mean() if phase == 'train': self.optimizer.zero_grad() loss.backward() torch.nn.utils.clip_grad_norm_(model_with_loss.parameters(), self.args.clip_value) self.optimizer.step() batch_time.update(time.time() - end) end = time.time() Bar.suffix = '{phase}: [{0}][{1}/{2}]| '.format(epoch, iter_id, num_iters, phase=phase) for l in avg_loss_stats: avg_loss_stats[l].update(loss_stats[l].mean().item(), batch['image'].size(0)) Bar.suffix = Bar.suffix + '|{} {:.4f} '.format( l, avg_loss_stats[l].avg) Bar.suffix = Bar.suffix + '|Data {dt.val:.3f}s({dt.avg:.3f}s) ' \ '|Net {bt.avg:.3f}s'.format(dt=data_time, bt=batch_time) if rank == 0 and phase == 'val' and self.args.write_mota_metrics and epoch in self.args.save_point: curr_name = None tracker = None for i in range(self.args.batch_size): try: fpath = batch['fpath'][i] except IndexError: break fpath = fpath.split('.')[0].split('/')[-1] name, num = fpath.split("_frame_") num = int(num) if num % self.args.val_select_frame != 0: continue if name != curr_name: curr_name = name tracker = Tracker(self.args) out = [x[i][None] for x in output] res = out dets = generic_decode( {k: res[t] for (t, k) in enumerate(self.args.heads)}, self.args.max_objs, self.args) for k in dets: dets[k] = dets[k].detach().cpu().numpy() if not tracker.init and len(dets) > 0: tracker.init_track(dets) elif len(dets) > 0: tracker.step(dets) with open(os.path.join(self.args.res_dir, fpath + '.txt'), "w") as f: for track in tracker.tracks: x1, y1, x2, y2 = track['bbox'] f.write("{} {} {} {} {} {}\n".format( track['score'], track['tracking_id'], x1, y1, x2, y2)) if rank == 0 and self.args.print_iter > 0: # If not using progress bar if iter_id % self.args.print_iter == 0: print('{}| {}'.format("tracking", Bar.suffix)) else: bar.next() del output, loss, loss_stats if rank == 0 and phase == 'val' and self.args.write_mota_metrics and epoch in self.args.save_point: self.compute_map(epoch) bar.finish() ret = {k: v.avg for k, v in avg_loss_stats.items()} ret['time'] = bar.elapsed_td.total_seconds() / 60. return ret, results