def __init__( self, model, step=3, fourcc='avc1', thre=0.5): """视频处理对象 Args: model (torch.Moudle): 目标探测模型 step (int, optional): 跳帧探测步数,相当于加速(step-1)倍. Defaults to 3. fourcc (str, optional): 本地视频保存编码. Defaults to 'avc1'. thre (float, optional): 目标探测阈值. Defaults to 0.5. """ self.model = model self.step = step self.fourcc = fourcc self.thre = thre self.hat_color = 'green' self.person_color = 'red' self.psn_tracker = Tracker() self.hat_tracker = Tracker() self.last_frame_bbox = None # 用于保存每次调用模型前传获的bbox,避免下一次重复使用 super().__init__()
def p_simple_declaration(p): """ simple_declaration : type ID """ var_name = p[2] symbols = Tracker().get_symbols() variable = ValVariable(var_name) variable.set_value("s{}".format(Tracker().get_var_num())) symbols.declare_variable(variable) Tracker().set_symbols(symbols) p[0] = variable.get_value()
def generate_bad_code_from_string(input_): Tracker() try: lexer = lex.lex() parser = yacc.yacc() program = parser.parse(input_, lexer=lexer) output = [] program.generate_bad_code(output) except: Tracker().reset() raise Tracker().reset() return "\n".join(output) + "\n"
def track_everything(video_name=None, max_disappear=10): """ This function tries to track every object appeared in a video file """ if video_name is None: video_stream = cv2.VideoCapture(0) else: video_stream = cv2.VideoCapture(video_name) tracker = Tracker(dis_count=max_disappear) while cv2.waitKey(1) < 0: has_frame, current_frame = video_stream.read() if has_frame: current_frame = cv2.rotate(current_frame, cv2.ROTATE_90_CLOCKWISE) start_time = time.perf_counter() predictions = detect(yolo, current_frame, classes) boxes, names = get_boxes(predictions) tracker.update(boxes, names) for label in tracker.registered_ids: x, y, w, h = tracker.registered_ids[label] c = tracker.colors[label] cv2.rectangle(current_frame, (int(x - w / 2), int(y - h / 2)), (int(x + w / 2), int(y + h / 2)), c, 2) cv2.putText(current_frame, label, (x, y - 2), cv2.FONT_HERSHEY_SIMPLEX, 0.75, c, 2) time_spent = time.perf_counter() - start_time label = 'Current FPS is: %.2f' % (1 / time_spent) cv2.putText(current_frame, label, (0, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 2) cv2.imshow("", current_frame) else: print('End of the video reached!') cv2.waitKey(100) break
def main(): input_video_name = 'MVI_40855.mp4' input_video_folder = './unbox_test/input/' output_folder = './unbox_test/output/' loader = Loader(input_video_name, input_video_folder) tracker = Tracker(input_video_name, fps=loader.video.fps) loader_iter = loader.read_iter(batch_size=1) frames_count = int(loader.video.fps * loader.video.duration) detector = Detector(gpu_id=0) v1 = Visualizer() for i in range(frames_count): images, image_ids = next(loader_iter) frame = detector.detect(images, image_ids)[0] frame = tracker.track(frame) img_bgr = v1.draw_scene(frame) result_image_name = output_folder + str(i) + '.png' img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) cv2.imwrite(result_image_name, img_rgb) print('[{0}/{1}] - {2}'.format(i, frames_count, result_image_name)) pass print('done.')
def main(): """ Robot will use two corners on one side of the wall in the arena. It will try to put all 4 tokens into slots. This gives us 9 points. """ option = 2 robot = Robot() reset_log(robot) robot.sound = Sound(robot, USING_SOUND) robot.sound.play('R2D2') robot.position = Tracker(robot.zone) set_pins(robot) slots_x = 2.91 if robot.zone in [0, 3] else 5.09 target_theta = pi / 2 if robot.zone in [0, 3] else 1.5 * pi if robot.zone in [0, 1]: dy = 0.9 slot_y_0 = 2.65 else: dy = -0.9 slot_y_0 = 5.65 while 1: try: if option == 1: put_down(robot) grab(robot) token_to_slot(robot, robot.zone) for i in range(4): zone = robot.zone if i < 2 else 3 - robot.zone has_token = get_token_from_corner(robot, zone) if has_token: token_to_slot(robot, zone) elif option == 2: put_down(robot) grab(robot) for i in range(4): zone = robot.zone if i < 2 else 3 - robot.zone if i == 0: move_to_point(robot, slots_x, slot_y_0 + 0.9, target_theta) token_to_slot_2(robot) elif i == 1: move_to_point(robot, 2, 2) get_token_from_corner(robot, zone) move_to_point(robot, slots_x, slot_y_0, target_theta) token_to_slot_2(robot) else: move_to_point(robot, 2, 2) get_token_from_corner(robot, zone) slot_y = slot_y_0 + dy * i move_to_point(robot, slots_x, slot_y, target_theta) token_to_slot_2(robot) except: print_exc() restart(robot)
def test_tag(): t = Tracker(Board(5, 500, 500, 500, othelloAI())) t.bd.generate_board() t.bd.disks[1][1].halo_tag = True t.tag() assert t.tag_count == 1 assert t.computer_moves == [t.bd.disks[1][1]]
def identify_human_tracking(self, last_dict_humans, new_humans, \ frame, viz=True): print(frame.shape) h, w, _ = frame.shape new_humans_box = [] for human in new_humans: box = self._get_box_from_human_pose(human, w, h) new_humans_box.append(box) deleted_keys = [] # update human dict for key in last_dict_humans.keys(): human = last_dict_humans[key] ok, box = human["tracker"].get_update(frame) if viz: f = cv2.rectangle(frame, box[0], box[1], (255, 0, 0), 1) cv2.imshow("vizualize tracking", f) cv2.waitKey(1) if ok: ious = [] for box_ in new_humans_box: iou = self._compute_iou(box_, box) ious.append(iou) if len(ious) == 0: deleted_keys.append(key) continue index_matched = np.argmax(ious) if ious[index_matched] == 0: deleted_keys.append(key) continue last_dict_humans[key]["pose"] = copy.deepcopy( new_humans[index_matched]) last_dict_humans[key]["box"] = copy.deepcopy( new_humans_box[index_matched]) del new_humans[index_matched] del new_humans_box[index_matched] else: deleted_keys.append(key) for key in deleted_keys: del last_dict_humans[key] for i, human in enumerate(new_humans): key = "{}".format(self.id_human) last_dict_humans[key] = dict() last_dict_humans[key]["pose"] = human last_dict_humans[key]["box"] = new_humans_box[i] tracker = Tracker(self.tracktype) tracker.init(new_humans_box[i], frame) last_dict_humans[key]["tracker"] = tracker self.id_human += 1 return last_dict_humans
def __init__(self, detection_size=(96, 96)): self.interpreter = MNN.Interpreter( "pretrained_weights/slim_96_latest.mnn") self.session = self.interpreter.createSession() self.input_tensor = self.interpreter.getSessionInput(self.session) self.detection_size = detection_size self.tracker = Tracker()
def translate(self, readline, result=None, no_imports=None): # Tracker to keep track of information as the file is processed self.tokens = Tokens(self.default_kls) self.tracker = Tracker(result, self.tokens, self.wrapped_setup) # Add import stuff at the top of the file if self.import_tokens and no_imports is not True: self.tracker.add_tokens(self.import_tokens) # Looking at all the tokens with self.tracker.add_phase() as tracker: for tokenum, value, (_, scol), _, _ in generate_tokens(readline): self.tracker.next_token(tokenum, value, scol) # Add attributes to our Describes so that the plugin can handle some nesting issues # Where we have tests in upper level describes being run in lower level describes if self.with_describe_attrs: self.tracker.add_tokens(self.tracker.make_describe_attrs()) # If setups should be wrapped, then do this at the bottom if self.wrapped_setup: self.tracker.add_tokens(self.tracker.wrapped_setups()) # Add lines to bottom of file to add __testname__ attributes self.tracker.add_tokens(self.tracker.make_method_names()) # Return translated list of tokens return self.tracker.result
def generate_bin_lane_warp(image, binary_warped, Minv): #images = glob.glob('output_images/binary_lanes/*.jpg') # print(images) #for fname in images: #binary_warped = mpimg.imread(fname) genpolyline = Tracker(True) lane_on_warped_blank_img, left_fitx, right_fitx, ploty = genpolyline.search_around_poly(binary_warped) os.makedirs(os.path.dirname(os.path.join(out_dir_name_lane_tracker, '')), exist_ok=True) full_name = os.path.join(out_dir_name_lane_tracker, os.path.basename(fname)) # print(full_name) cv2.imwrite(full_name, lane_on_warped_blank_img) # Create an image to draw the lines on warp_zero = np.zeros_like(binary_warped).astype(np.uint8) color_warp = np.dstack((warp_zero, warp_zero, warp_zero)) # Recast the x and y points into usable format for cv2.fillPoly() pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))]) pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))]) pts = np.hstack((pts_left, pts_right)) # Draw the lane onto the warped blank image cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0)) # Warp the blank back to original image space using inverse perspective matrix (Minv) newwarp = cv2.warpPerspective(color_warp, Minv, (image.shape[1], image.shape[0])) # Combine the result with the original image result = cv2.addWeighted(image, 1, newwarp, 0.3, 0) #plt.imshow(result) os.makedirs(os.path.dirname(os.path.join(out_dir_name_draw_lane, '')), exist_ok=True) full_name = os.path.join(out_dir_name_draw_lane, os.path.basename(fname)) cv2.imwrite(full_name, result)
async def main(): # torrent = Torrent('Dua Lipa - Future Nostalgia (2020) MP3 [320 kbps]-[rarbg.to].torrent') # torrent = Torrent('flagfromserver.torrent') torrent = Torrent('ubuntu-19.10-desktop-amd64.iso.torrent') tracker = Tracker(torrent) await tracker.send_announce_request(0, 0, 'started') await tracker.close()
def track(id): details = Tracker().track(id) if details is not None: response.set_header('Content-Type', 'application/json') return json.dumps(details, cls=DateTimeEncoder, sort_keys=True, indent=4, separators=(',', ': ')) else: abort(404, 'Consignment details not Found')
def test_delete_event(): tracker = Tracker() tracker.add_event('Buy toothpaste', 1900) tracker.add_event('Go to the gym', 2000) tracker.delete_event('Go to the gym') assert tracker.get_event_time('Go to the gym') == None assert tracker.get_event_time('Buy toothpaste') == 1900
def __init__(self, torrent): self.torrent = torrent self.tracker = Tracker(self.torrent.announce, self.torrent.get_params()) self.peers = self.create_peers() self.message_handler = MessageHandler(self.torrent, self) self.io_loop = get_event_loop() self.visualizer = Visualizer()
def test_scanner(): t = Tracker(Board(5, 500, 500, 500, othelloAI())) t.bd.generate_board() t.scanner() assert t.white_disks == 2 assert t.black_disks == 2 assert t.disks_on_board == 4
def print_trace_table(request): def temp(): exec(request["code"]) tracker = Tracker(**request["parameters"]) targets = request["variables"] def tracer(frame, event, arg=None): code = frame.f_code line_no = frame.f_lineno #tracker.onchange("_line_number", line_no) for v in targets: if len(tracker.values.get(v, {}).keys()) > 0: if tracker.values[v][max( tracker.values[v].keys())] == frame.f_locals.get(v): continue if v in frame.f_locals.keys(): tracker.onchange(v, frame.f_locals.get(v)) return tracer sys.settrace(tracer) temp() sys.settrace(None) print(tracker.displayTraceTable())
def __init__(self, raw_packet=None, ether_src="00:00:00:00:00:00", ether_dst="00:00:00:00:00:00", child_packet=None): """ Class constructor """ # Packet parsing if raw_packet: self.tracker = Tracker("RX") raw_header = raw_packet[:ETHER_HEADER_LEN] self.raw_data = raw_packet[ETHER_HEADER_LEN:] self.ether_dst = ":".join([f"{_:0>2x}" for _ in raw_header[0:6]]) self.ether_src = ":".join([f"{_:0>2x}" for _ in raw_header[6:12]]) self.ether_type = struct.unpack("!H", raw_header[12:14])[0] # Packet building else: self.tracker = child_packet.tracker self.ether_dst = ether_dst self.ether_src = ether_src assert child_packet.protocol in {"IPv6", "IPv4", "ARP"}, f"Not supported protocol: {child_packet.protocol}" if child_packet.protocol == "IPv6": self.ether_type = ETHER_TYPE_IP6 if child_packet.protocol == "IPv4": self.ether_type = ETHER_TYPE_IP4 if child_packet.protocol == "ARP": self.ether_type = ETHER_TYPE_ARP self.raw_data = child_packet.get_raw_packet()
def peer_client_connector(self, client_port_to_bind, peer_ip_address, peer_port=5000): print("\npeer_client_connector") client = Client() tracker = Tracker(self.server) # print(client_port_to_bind) # print(peer_ip_address) try: # binds the client to the ip address assigned by LAN client.bind( '0.0.0.0', client_port_to_bind ) # note: when you bind, the port bound will be the client id print("successfully bound to 0.0.0.0 " + str(client_port_to_bind)) self.clienthander_list.append(client) thread.Thread(target=client.connect, args=(peer_ip_address, peer_port)).start() # threads server tracker.broadcast_not_send() return True except Exception as error: print(error) client.close() return False
def __init__(self, parent_packet=None, udp_sport=None, udp_dport=None, raw_data=None, echo_tracker=None): """ Class constructor """ # Packet parsing if parent_packet: self.tracker = parent_packet.tracker raw_packet = parent_packet.raw_data raw_header = raw_packet[:UDP_HEADER_LEN] self.raw_data = raw_packet[UDP_HEADER_LEN:struct. unpack("!H", raw_header[4:6])[0]] self.ip_pseudo_header = parent_packet.ip_pseudo_header self.udp_sport = struct.unpack("!H", raw_header[0:2])[0] self.udp_dport = struct.unpack("!H", raw_header[2:4])[0] self.udp_plen = struct.unpack("!H", raw_header[4:6])[0] self.udp_cksum = struct.unpack("!H", raw_header[6:8])[0] # Packet building else: self.tracker = Tracker("TX", echo_tracker) self.udp_sport = udp_sport self.udp_dport = udp_dport self.udp_plen = UDP_HEADER_LEN + len(raw_data) self.udp_cksum = 0 self.raw_data = raw_data
def create_first_tracking(self, dict_humans, frame): for key in dict_humans.keys(): human = dict_humans[key] tracker = Tracker(self.tracktype) tracker.init(human["box"], frame) human["tracker"] = tracker
def __init__(self): self.prev_flight_data = None self.record = False self.tracking = False self.keydown = False self.date_fmt = '%Y-%m-%d_%H%M%S' self.speed = 50 self.go_speed = 80 self.drone = Tello() self.init_drone() self.init_controls() self.battery = self.drone.get_battery() self.frame_read = self.drone.get_frame_read() self.forward_time = 0 self.forward_flag = True self.takeoff_time = 0 self.command_time = 0 self.command_flag = False # trackingimport libh264decoder a color #green_lower = (30, 50, 50) #green_upper = (80, 255, 255) #red_lower = (0, 50, 50) #red_upper = (20, 255, 255) blue_lower = np.array([0, 0, 0]) upper_blue = np.array([255, 255, 180]) bh_lower = (180, 30, 100) bh_upper = (275, 50, 100) self.track_cmd = "" self.tracker = Tracker(960, 720, blue_lower, upper_blue) self.speed_list = [5, 10, 15, 20, 25] self.frame_center = 480, 360 self.error = 60
def main(): print("1.5D Ideal Gas in a Box Simmulation...") dt = 0.1 box = simBox(0, 10, 0, 10, dt) N = 200 box.make_N_particles(N) print("kp: ", round(box.kinetic_pressure(), 2)) h = 400 w = 400 win = GraphWin("1.5D Box of Gas Sim.", w, h) win.setCoords(-0.1, -0.1, 10.1, 10.1) pTrList = [] for p in box.pList: tp = Tracker(win, p) pTrList.append(tp) timeSteps = 10000 for n in range(timeSteps): box.move_particles() for p in pTrList: p.update() #time.sleep(.0001*dt) print("pave: ", round((box.pLave + box.pRave) / 2, 2)) print("kp: ", round(box.kinetic_pressure(), 2))
def set_parts(self, parts): self.parts = parts self.trackers = {} for part in parts: self.trackers[part] = Tracker( max_age=self.max_age, min_hits=self.min_hits, iou_threshold=self.iou_threshold )
def main(): # Read in data and extract data arrays #logging.info("Reading input files.") dbh = DBHandler(options.db_config_filename, options.db_config_name) ssh = SmartMetHandler(options.smartmet_config_filename, options.smartmet_config_name, sleep_time=options.requests_throttle_time) fh = FileHandler(s3_bucket='fmi-sasse-classification-dataset') tracker = Tracker(dbh, ssh) starttime = dt.datetime.strptime(options.starttime, "%Y-%m-%dT%H:%M:%S") endtime = dt.datetime.strptime(options.endtime, "%Y-%m-%dT%H:%M:%S") d = starttime ymd = '{}{}{}'.format(d.year, d.month, d.day) while d <= endtime: logging.info('Processing time: {}'.format(d)) tracker.run(d) d += timedelta(hours=1) if ymd != '{}{}{}'.format(d.year, d.month, d.day): save_dataset(tracker, d, fh=fh, db=dbh) ymd = '{}{}{}'.format(d.year, d.month, d.day) #if tracker.dataset is not None and len(tracker.dataset) > 0: save_dataset(tracker, d, fh=fh, db=dbh)
def main(args): # House builds table and establishes rules table_rules = TableConfig(args) table = CrapsTable(table_rules, args) tracker = Tracker() for k in range(args.series): # New Player enters the game player = Player(args) tracker.new_series(player) for i in range(args.rounds): playing = table.play_round(player) tracker.log_round(player) if not playing: if args.v: cprint('Exit at round {}'.format(i), 'yellow') break tracker.end_series(player) if args.v: if player.broke: cprint('~*~*~*~*~*~*~*~*~*~*~*~', 'red') else: cprint('~*~*~*~*~*~*~*~*~*~*~*~', 'green') cprint('Peak $$$: {}'.format(player.max), 'cyan') cprint('Low $$$: {}'.format(player.min), 'magenta') if not args.v: printProgressBar(k, args.series) tracker.summarize(player)
def __init__(self): self.prev_flight_data = None self.record = False self.tracking = False self.keydown = False self.date_fmt = '%Y-%m-%d_%H%M%S' self.speed = 50 self.drone = tellopy.Tello() self.init_drone() self.init_controls() # container for processing the packets into frames self.container = av.open(self.drone.get_video_stream()) self.vid_stream = self.container.streams.video[0] self.out_file = None self.out_stream = None self.out_name = None self.start_time = time.time() # tracking a color green_lower = (30, 50, 50) green_upper = (80, 255, 255) #red_lower = (0, 50, 50) # red_upper = (20, 255, 255) # blue_lower = (110, 50, 50) # upper_blue = (130, 255, 255) self.track_cmd = "" self.tracker = Tracker(self.vid_stream.height, self.vid_stream.width, green_lower, green_upper)
def __init__(self, input_video_path='../input/project_video.mp4', output_video_path=None): self.input_video_path = input_video_path image_height, image_width, _ = VideoFileClip( self.input_video_path).get_frame(0).shape self.drawer = Drawer(bbox_settings=BBoxSettings(color=StaticColor(), border_thickness=2, alpha_border=0.95, alpha_fill=0.3), inplace=False) if output_video_path is None: show_display = True else: show_display = False self.grid_generator = GridGenerators(image_height, image_width) self.classifier = Classifier(self.grid_generator, force_train=False, use_cache=True, show_display=show_display) self.cluster = Cluster(image_height, image_width, show_display=show_display) self.tracker = Tracker(show_display=show_display) with open(camera_calibration_path, 'rb') as fid: self.calibration = pickle.load(fid) if output_video_path is None: self.player() else: self.create_video(output_video_path=output_video_path)
def __init__(self, torr_dir="c:/torrent", data_dir="c:/torrent/files", tracker_ip="10.0.0.1:8000", callback=lambda: ".", session_dir="c:/torrent", db_name="torrent.db", ext=".torrent"): """ Intialize class. Parameters torr_dir: Location for torrent meta data files data_dir: Location for data files tracker_ip: IP:PORT string of tracker callback: option function which will be called while attempting to seed torrents. torr_db: Name of anydbm database where we save what we're serving. """ self.callback = callback self.data_dir = data_dir self.torr_dir = torr_dir self.ext = ext self.torr_db = os.path.join(session_dir, db_name) self.db = None # pointer to our torrent DB self.my_tracker = Tracker(tracker_ip) self.session = Session(session_dir, db_name) self.session.register(self.callback)
def main(): # Extract arguments ap = argparse.ArgumentParser() ap.add_argument("data", help="Data file containing bugs") ap.add_argument("vocabulary", help="Vocabulary file") ap.add_argument("-s", "--suffix", help="Model and log-file suffix") args = ap.parse_args() data = DataReader(config["data"], data_file=args.data, vocab_path=args.vocabulary) model = TransformerPatchingModel(config["transformer"], data.vocabulary.vocab_dim, is_pointer=config["data"]["edits"]) # Restore model after a simple init tracker = Tracker(model, suffix=args.suffix) model(tf.zeros((1, 2), 'int32'), tf.zeros((1, 2), 'int32'), tf.zeros((1, 2), 'int32'), tf.zeros((0, 0), 'int32'), True) tracker.restore(best_only=True) with open( "results" + ("" if args.suffix is None else "-" + args.suffix) + ".txt", "w") as f_out: for batch in data.batcher(mode="test", optimize_packing=False): pre, pre_locs = batch[:2] preds = model.predict(data.vocabulary, pre, pre_locs, config["data"]["beam_size"], config["data"]["max_bug_length"]) write_completions(f_out, data.vocabulary, pre.numpy(), pre_locs.numpy(), preds)