def main(args: argparse.Namespace): dataset = Path(args.dataset) dest = Path(args.dest) dest.mkdir(parents=True, exist_ok=True) with tqdm(total=len(list(dataset.iterdir()))) as task: for sequence in sorted( dataset.iterdir() if not args.no_sequence else [dataset]): task.set_description(sequence.stem) tracker = Tracker() loader = data.Dataset(str(sequence), data.get(args.type), args.jump) with open(str(dest.joinpath('{}.txt'.format(sequence.stem))), 'w') as file: for frame, (image, boxes, scores, image_name) in enumerate(tqdm(loader)): # Mask R-CNN Detection Support if args.support is not None: try: support = Path(args.support).joinpath( '{}.txt'.format(image_name)) support = pd.read_csv(str(support), header=None).values support_boxes = support[:, 2:6] support_boxes[:, 2:] -= support_boxes[:, :2] support_scores = support[:, 1] if args.support_only: boxes = support_boxes scores = support_scores else: boxes = np.concatenate([ boxes, support_boxes, ]) scores = np.concatenate([ scores, support_scores, ]) except pd.errors.EmptyDataError: boxes = np.zeros((0, 4)) scores = np.zeros(0) file.writelines( map( lambda t: ', '.join( map(str, [ frame, t.id, *t.to_tlwh, 1, -1, -1, -1, -1 ])) + '\n', tracker.update(image, boxes, scores))) task.update()
def append_box(self, label_name): if self.p0[0] - self.p1[0] >= 0 or self.p0[1] - self.p1[1] >= 0: self.p0,self.p1=(min(self.p0[0],self.p1[0]),min(self.p0[1],self.p1[1])),\ (max(self.p0[0],self.p1[0]),max(self.p0[1],self.p1[1])) self.boxes.append([self.p0, self.p1]) self.colors.append([255, 0, 255]) tracker = Tracker() tracker.start(self.video_im, self.p0, self.p1) self.trackers.append(tracker) self.labels.append(label_name)
def __init__(self, torrent): self.tracker = Tracker(torrent) # The list of potential peers is the work queue, consumed by the # PeerConnections self.available_peers = Queue() # The list of peers is the list of workers that *might* be connected # to a peer. Else they are waiting to consume new remote peers from # the `available_peers` queue. These are our workers! self.peers = [] # The piece manager implements the strategy on which pieces to # request, as well as the logic to persist received pieces to disk. self.piece_manager = PieceManager(torrent) self.abort = False
def __init__( self, data: bytes, proto: int, src: Ip4Address, dst: Ip4Address, ttl: int = config.IP4_DEFAULT_TTL, dscp: int = 0, ecn: int = 0, id: int = 0, flag_mf: bool = False, offset: int = 0, options: Optional[list[Ip4OptNop | Ip4OptEol]] = None, ): """Class constructor""" assert proto in {IP4_PROTO_ICMP4, IP4_PROTO_UDP, IP4_PROTO_TCP} self._tracker: Tracker = Tracker("TX") self._ver: int = 4 self._dscp: int = dscp self._ecn: int = ecn self._id: int = id self._flag_df: bool = False self._flag_mf: bool = flag_mf self._offset: int = offset self._ttl: int = ttl self._src: Ip4Address = src self._dst: Ip4Address = dst self._options: list[Ip4OptNop | Ip4OptEol] = [] if options is None else options self._data: bytes = data self._proto: int = proto self._hlen: int = IP4_HEADER_LEN + len(self._raw_options) self._plen: int = len(self)
def __init__(self, sport: int, dport: int, data: Optional[bytes] = None, echo_tracker: Optional[Tracker] = None) -> None: """Class constructor""" self._tracker: Tracker = Tracker("TX", echo_tracker) self._sport: int = sport self._dport: int = dport self._data: bytes = b"" if data is None else data self._plen: int = UDP_HEADER_LEN + len(self._data)
def __init__( self, sport: int, dport: int, seq: int = 0, ack: int = 0, flag_ns: bool = False, flag_crw: bool = False, flag_ece: bool = False, flag_urg: bool = False, flag_ack: bool = False, flag_psh: bool = False, flag_rst: bool = False, flag_syn: bool = False, flag_fin: bool = False, win: int = 0, urp: int = 0, options: Optional[list[TcpOptMss | TcpOptWscale | TcpOptSackPerm | TcpOptTimestamp | TcpOptEol | TcpOptNop]] = None, data: Optional[bytes] = None, echo_tracker: Optional[Tracker] = None, ) -> None: """Class constructor""" self._tracker: Tracker = Tracker("TX", echo_tracker) self._sport: int = sport self._dport: int = dport self._seq: int = seq self._ack: int = ack self._flag_ns: bool = flag_ns self._flag_crw: bool = flag_crw self._flag_ece: bool = flag_ece self._flag_urg: bool = flag_urg self._flag_ack: bool = flag_ack self._flag_psh: bool = flag_psh self._flag_rst: bool = flag_rst self._flag_syn: bool = flag_syn self._flag_fin: bool = flag_fin self._win: int = win self._urp: int = urp self._options: list[TcpOptMss | TcpOptWscale | TcpOptSackPerm | TcpOptTimestamp | TcpOptEol | TcpOptNop] = [] if options is None else options self._data: bytes = b"" if data is None else data self._hlen: int = TCP_HEADER_LEN + sum([len(_) for _ in self._options]) assert self._hlen % 4 == 0, f"TCP header len {self._hlen} is not multiplcation of 4 bytes, check options... {self._options}"
def __init__(self, frame: bytes) -> None: """Class constructor""" self.frame: memoryview = memoryview(frame) self.tracker: Tracker = Tracker("RX") self.parse_failed: str = "" self.ether: EtherParser self.arp: ArpParser self.ip: Union[Ip6Parser, Ip4Parser] self.ip4: Ip4Parser self.ip6: Ip6Parser self.ip6_ext_frag: Ip6ExtFragParser self.icmp4: Icmp4Parser self.icmp6: Icmp6Parser self.tcp: TcpParser self.udp: UdpParser
def __init__( self, sha: MacAddress, spa: Ip4Address, tpa: Ip4Address, tha: MacAddress = MacAddress(0), oper: int = ARP_OP_REQUEST, echo_tracker: Optional[Tracker] = None, ) -> None: """Class constructor""" self._tracker = Tracker("TX", echo_tracker) self._hrtype: int = 1 self._prtype: int = 0x0800 self._hrlen: int = 6 self._prlen: int = 4 self._oper: int = oper self._sha: MacAddress = sha self._spa: Ip4Address = spa self._tha: MacAddress = tha self._tpa: Ip4Address = tpa
def __init__( self, next: int, offset: int, flag_mf: bool, id: int, data: bytes, ): """Class constructor""" assert next in { IP6_NEXT_HEADER_ICMP6, IP6_NEXT_HEADER_UDP, IP6_NEXT_HEADER_TCP } self._tracker: Tracker = Tracker("TX") self._next: int = next self._offset: int = offset self._flag_mf: bool = flag_mf self._id: int = id self._dataa: bytes = data self._dlen: int = len(data) self._plen: int = len(self)
def __init__( self, type: int, code: int = 0, ec_id: Optional[int] = None, ec_seq: Optional[int] = None, ec_data: Optional[bytes] = None, un_data: Optional[bytes] = None, echo_tracker: Optional[Tracker] = None, ) -> None: """Class constructor""" assert type in { ICMP4_ECHO_REQUEST, ICMP4_UNREACHABLE, ICMP4_ECHO_REPLY } self._tracker: Tracker = Tracker("TX", echo_tracker) self._type: int = type self._code: int = code self._ec_id: int self._ec_seq: int self._ec_data: bytes self._un_data: bytes if self._type == ICMP4_ECHO_REPLY: self._ec_id = 0 if ec_id is None else ec_id self._ec_seq = 0 if ec_seq is None else ec_seq self._ec_data = b"" if ec_data is None else ec_data elif self._type == ICMP4_UNREACHABLE and self._code == ICMP4_UNREACHABLE__PORT: self._un_data = b"" if un_data is None else un_data[:520] elif self._type == ICMP4_ECHO_REQUEST: self._ec_id = 0 if ec_id is None else ec_id self._ec_seq = 0 if ec_id is None else ec_id self._ec_data = b"" if ec_data is None else ec_data
def process(self, interface, pkt, args): """Process packets coming from the sniffer.""" try: tgtMac, rtrmac, tgtIp, svrip, tgtPort, svrport, acknum, seqnum, request, TSVal, TSecr = self.proc_handler( pkt, args) exists = 0 for tgt in self.newTgts: if tgt.ip is not None and tgt.ip == tgtIp: exists = 1 for tgt in self.newTgts: if tgt.ip is not None: if tgt.ip == tgtIp: self.injector.inject(tgtMac, rtrmac, tgtIp, svrip, tgtPort, svrport, acknum, seqnum, tgt.get_injection(), TSVal, TSecr) if exists == 0: self.newTgts.append( Tracker(ip=tgtIp, mac=tgtMac, tParams=self.tParams)) except: return
def get_the_skeleton_data_to_save_to_disk(mulperson_skltn): skels_to_save = [] for human_id in mulperson_skltn.keys(): label = mulperson_label[human_id] skeleton = mulperson_skltn[human_id] skels_to_save.append([[human_id, label] + skeleton.tolist()]) return skels_to_save if __name__ == "__main__": skeleton_detector = SkeletonDetector(model, img_size) multiperson_tracker = Tracker() multiperson_classifier = MultiPersonClassifier(model_path, CLASSES) images_loader = select_images_loader(data_type, data_path) img_displayer = lib_images_io.ImageDisplayer() os.makedirs(folder, exist_ok=True) os.makedirs(folder + skltn_folder_name, exist_ok=True) video_writer = lib_images_io.VideoWriter(folder + video_name, video_fps) try: ith_img = -1 while images_loader.has_image():
def __init__( self, type: int, code: int = 0, un_data: Optional[bytes] = None, ec_id: Optional[int] = None, ec_seq: Optional[int] = None, ec_data: Optional[bytes] = None, ra_hop: Optional[int] = None, ra_flag_m: Optional[bool] = None, ra_flag_o: Optional[bool] = None, ra_router_lifetime: Optional[int] = None, ra_reachable_time: Optional[int] = None, ra_retrans_timer: Optional[int] = None, ns_target_address: Optional[Ip6Address] = None, na_flag_r: Optional[bool] = None, na_flag_s: Optional[bool] = None, na_flag_o: Optional[bool] = None, na_target_address: Optional[Ip6Address] = None, nd_options: Optional[list[Icmp6NdOptSLLA | Icmp6NdOptTLLA | Icmp6NdOptPI]] = None, mlr2_multicast_address_record: Optional[ list[Icmp6MulticastAddressRecord]] = None, echo_tracker: Optional[Tracker] = None, ) -> None: """Class constructor""" self._tracker = Tracker("TX", echo_tracker) self._type = type self._code = code self._nd_options: list[ Icmp6NdOptSLLA | Icmp6NdOptTLLA | Icmp6NdOptPI] = [] if nd_options is None else nd_options self._un_reserved: int self._un_data: bytes self._ec_id: int self._ec_seq: int self._ec_data: bytes self._rs_reserved: int self._ra_hop: int self._ra_flag_m: bool self._ra_flag_o: bool self._ra_router_lifetime: int self._ra_reachable_time: int self._ra_retrans_timer: int self._ns_reserved: int self._ns_target_address: Ip6Address self._na_flag_r: bool self._na_flag_s: bool self._na_flag_o: bool self._na_reserved: int self._na_target_address: Ip6Address self._mlr2_reserved: int self._mlr2_multicast_address_record: list[Icmp6MulticastAddressRecord] self._mlr2_number_of_multicast_address_records: int if self._type == ICMP6_UNREACHABLE: self._un_reserved = 0 self._un_data = b"" if un_data is None else un_data[:520] elif self._type == ICMP6_ECHO_REQUEST: self._ec_id = 0 if ec_id is None else ec_id self._ec_seq = 0 if ec_seq is None else ec_seq self._ec_data = b"" if ec_data is None else ec_data elif self._type == ICMP6_ECHO_REPLY: self._ec_id = 0 if ec_id is None else ec_id self._ec_seq = 0 if ec_seq is None else ec_seq self._ec_data = b"" if ec_data is None else ec_data elif self._type == ICMP6_ROUTER_SOLICITATION: self._rs_reserved = 0 elif self._type == ICMP6_ROUTER_ADVERTISEMENT: self._ra_hop = 0 if ra_hop is None else ra_hop self._ra_flag_m = False if ra_flag_m is None else ra_flag_m self._ra_flag_o = False if ra_flag_o is None else ra_flag_o self._ra_router_lifetime = 0 if ra_router_lifetime is None else ra_router_lifetime self._ra_reachable_time = 0 if ra_reachable_time is None else ra_reachable_time self._ra_retrans_timer = 0 if ra_retrans_timer is None else ra_retrans_timer elif self._type == ICMP6_NEIGHBOR_SOLICITATION: self._ns_reserved = 0 self._ns_target_address = Ip6Address( 0) if ns_target_address is None else ns_target_address elif self._type == ICMP6_NEIGHBOR_ADVERTISEMENT: self._na_flag_r = False if na_flag_r is None else na_flag_r self._na_flag_s = False if na_flag_s is None else na_flag_s self._na_flag_o = False if na_flag_o is None else na_flag_o self._na_reserved = 0 self._na_target_address = Ip6Address( 0) if na_target_address is None else na_target_address elif self._type == ICMP6_MLD2_REPORT: self._mlr2_reserved = 0 self._mlr2_multicast_address_record = [] if mlr2_multicast_address_record is None else mlr2_multicast_address_record self._mlr2_number_of_multicast_address_records = len( self._mlr2_multicast_address_record)
class ObjectDetection(QMainWindow): def __init__(self, *args, **kwargs): super(ObjectDetection, self).__init__(*args, **kwargs) self.DATA_FILE='data/DATA.bin' self.CONFIG_FILE='data/CONFIG.json' self.running=True self.opened_settings=False self.crowd_list={} self.alarm_time=1 # 1 second self.alarm_list=set() self.alarm_on=False self.t1=time.time() self.t2=time.time() self.t3=time.time() # Load records if os.path.exists(self.DATA_FILE): f = open(self.DATA_FILE, "rb") if True: self.DATA = pickle.load(f) if self.DATA!={}: last=datetime.datetime.utcfromtimestamp(list(self.DATA.keys())[-1]) now=datetime.datetime.now() tmp=[now.year,now.month,now.day,now.hour] tmp2=[last.year,last.month,last.day,last.hour] new=last while tmp2!=tmp: new= new + datetime.timedelta(seconds = 3600) tmp2=[new.year,new.month,new.day,new.hour] timestamp=new.timestamp() timestamp=round(timestamp,6) self.DATA[timestamp]={"NM":[],"M":[]} else: self.DATA={} f.close() else: self.DATA={} # Load settings with open(self.CONFIG_FILE) as json_file: self.CONFIGS = json.load(json_file) # Import settings from configuration file self.maxAbsences=self.CONFIGS["maxAbsences"] self.categories =self.CONFIGS["categories"] self.colors =[tuple(x) for x in self.CONFIGS["colors"]] self.min_scores=self.CONFIGS["min_score"] self.border_pxl=self.CONFIGS["border"] self.models_path=self.CONFIGS["models_path"] self.models=os.listdir(self.models_path) self.models=['.'.join(x.split('.')[:-1]) for x in self.models] self.default_model=self.CONFIGS["default_model"] self.min_score=self.min_scores[self.default_model] self.path_to_ckpt = self.models_path+'\\'+self.default_model+'.pb' self.show_scores=bool(self.CONFIGS["show_scores"]) self.show_IDs=bool(self.CONFIGS["show_IDs"]) # Load counts from temp directory self.tmppath = 'C:\\Users\\{}\\AppData\\Local\\Temp'.format(os.getlogin()) + '\\COVIDEO_cnts.txt' if os.path.exists(self.tmppath): with open(self.tmppath, 'r') as file: data = file.readline().split(',') self.cntMTot = int(data[0]) self.cntVTot = int(data[1]) else: with open(self.tmppath, 'w+') as file: self.cntMTot=0 self.cntVTot=0 file.write('%d,%d' %(self.cntMTot, self.cntVTot)) # Init an istance of a tracker for each class self.masked_tracker=Tracker(maxAbsences=self.maxAbsences, startID=(self.cntMTot+1)) self.unmasked_tracker=Tracker(maxAbsences=self.maxAbsences, startID=(self.cntVTot+1)) self.font = cv2.FONT_HERSHEY_SIMPLEX self.setWindowTitle('COVIDEO v3') self.setWindowIcon(QIcon('img\\Icon.jpg')) self.setGeometry(100, 100, 1280, 720) self.setStyleSheet("background-color:white") self.setMinimumWidth(1280) self.setMaximumWidth(1280) self.setMaximumHeight(720) self.setMinimumHeight(720) self.pic = QLabel(self) self.pic.setGeometry(0, 0, 1280, 720) self.logo = QLabel(self) self.logo.setGeometry(0, 690, 180, 30) self.logo.setStyleSheet("background-color:transparent;") self.logo.setPixmap(QPixmap('img\\logo_white.png')) self.logo.setScaledContents(True) self.textCM = QPushButton(self) self.textCM.setStyleSheet("background-color:black; color:"+('#%02x%02x%02x' % self.colors[1])+"; font:bold; border-style:outset;\ border-width:1px; border-radius:5px") self.textCM.setText('Current Number of People '+self.categories[1]+': 0') self.textCM.setGeometry(1030, 5, 250, 15) self.textCV = QPushButton(self) self.textCV.setStyleSheet("background-color:black; color:"+('#%02x%02x%02x' % self.colors[0])+"; font:bold; border-style:outset;\ border-width:1px; border-radius:5px") self.textCV.setText('Current Number of People '+self.categories[0]+': 0') self.textCV.setGeometry(1030, 22.5, 250, 15) self.textTM = QPushButton(self) self.textTM.setStyleSheet("background-color:black; color:"+('#%02x%02x%02x' % self.colors[1])+"; font:bold; border-style:outset;\ border-width:1px; border-radius:5px") self.textTM.setText('Total Number of People '+self.categories[1]+': 0') self.textTM.setGeometry(1030, 40, 250, 15) self.textTV = QPushButton(self) self.textTV.setStyleSheet("background-color:black; color:"+('#%02x%02x%02x' % self.colors[0])+"; font:bold; border-style:outset;\ border-width:1px; border-radius:5px") self.textTV.setText('Total Number of People '+self.categories[0]+': 0') self.textTV.setGeometry(1030, 57.5, 250, 15) self.b1 = QPushButton(self) self.b1.setStyleSheet("QPushButton{background-color:black; color:red; font:bold; border-style:outset;\ border-width:2px; border-radius:10px}"\ "QPushButton:hover{background-color:red; color:black; font:bold; border-style:outset;\ border-width:2px; border-radius:10px}"\ "QPushButton:pressed{background-color:black; color:red; font:bold; border-style:outset;\ border-width:2px; border-radius:10px}") self.b1.clicked.connect(self.reset_cnts) self.b1.setText('Reset Totals') self.b1.setGeometry(1175, 685, 100, 30) self.b2 = QPushButton(self) self.b2.setStyleSheet("QPushButton{background-color:black; color:white; font:bold; border-style:outset;\ border-width:2px; border-radius:10px}"\ "QPushButton:hover{background-color:white; color:black; font:bold; border-style:outset;\ border-width:2px; border-radius:10px}"\ "QPushButton:pressed{background-color:black; color:white; font:bold; border-style:outset;\ border-width:2px; border-radius:10px}") self.b2.clicked.connect(self.change_settings) self.b2.setText('Settings') self.b2.setGeometry(1175, 650, 100, 30) self.b3 = QPushButton(self) self.b3.setStyleSheet("QPushButton{background-color:black; color:green; font:bold; border-style:outset;\ border-width:2px; border-radius:10px}"\ "QPushButton:hover{background-color:green; color:black; font:bold; border-style:outset;\ border-width:2px; border-radius:10px}"\ "QPushButton:pressed{background-color:black; color:green; font:bold; border-style:outset;\ border-width:2px; border-radius:10px}") self.b3.clicked.connect(self.export) self.b3.setText('Export') self.b3.setGeometry(1175, 615, 100, 30) #Load categories self.category_index={1: {'id': 1, 'name': self.categories[0]}, 2: {'id': 2, 'name': self.categories[1]}} # Run main functions self.load_model() self.define_io_tensors() self.video_setting() self.show() self.start() def closeEvent(self, event): # close app close = QMessageBox.question(self,"QUIT","Are you sure you want to stop the process?",QMessageBox.Yes | QMessageBox.No) if close == QMessageBox.Yes: self.save_data() self.video.release() cv2.destroyAllWindows() event.accept() else: event.ignore() def reset_cnts(self): # Reset data self.running=False ans = QMessageBox.question(self,"RESET","Are you sure you want to reset the total counts?",QMessageBox.Yes | QMessageBox.No) if ans == QMessageBox.Yes: self.masked_tracker.reset() self.unmasked_tracker.reset() self.cntMTot=0 self.cntVTot=0 f=open(self.DATA_FILE, 'wb') f.close() self.DATA={} else: pass self.running=True self.start() def selectionchange(self): selected=self.comboBox.currentText() self.minscoreEdit.setText(str(self.min_scores[selected]*100)) def change_settings(self): # Graphical interface for settings self.win = QWidget() self.win.setWindowIcon(QIcon('img\\Icon.jpg')) self.maxabsLabel = QLabel("Maximum number of absences:") self.maxabsEdit = QLineEdit() self.maxabsEdit.setText(str(self.maxAbsences)) self.minscoreLabel = QLabel("Minimum score (%):") self.minscoreEdit = QLineEdit() self.minscoreEdit.setText(str(self.min_score*100)) self.borderLabel = QLabel("Pixels of border:") self.borderEdit = QLineEdit() self.borderEdit.setText(str(self.border_pxl)) self.modelLabel = QLabel("Model:") self.comboBox = QComboBox() self.comboBox.addItems(self.models) self.comboBox.setCurrentIndex(self.models.index(self.default_model)) self.comboBox.currentIndexChanged.connect(self.selectionchange) self.colorLabe0 = QLabel(self.categories[0]+" color:") self.color0_button = QPushButton() self.color0_button.clicked.connect(lambda: self.get_color(0)) self.color0_button.setStyleSheet("background-color:rgb"+str(self.colors[0])) self.colorLabel1 = QLabel(self.categories[1]+" color:") self.color1_button = QPushButton() self.color1_button.clicked.connect(lambda: self.get_color(1)) self.color1_button.setStyleSheet("background-color:rgb"+str(self.colors[1])) self.checkbox1 = QCheckBox("Show scores") self.checkbox1.setChecked(self.show_scores) self.checkbox2 = QCheckBox("Show IDs") self.checkbox2.setChecked(self.show_IDs) self.ok = QPushButton() self.ok.setText('Save') self.ok.clicked.connect(self.restart) self.Label1 = QLabel("- OBJECT DETECTION:") self.Label1.setStyleSheet("font-weight: bold") self.Label2 = QLabel("- TRACKING:") self.Label2.setStyleSheet("font-weight: bold") self.Label3 = QLabel("- DESIGN:") self.Label3.setStyleSheet("font-weight: bold") self.Label4 = QLabel("") # Put the widgets in a layout (now they start to appear): self.layout = QGridLayout() self.layout.addWidget(self.Label1, 0, 0) self.layout.addWidget(self.minscoreLabel, 1, 0) self.layout.addWidget(self.minscoreEdit, 1, 1) self.layout.addWidget(self.modelLabel, 2, 0) self.layout.addWidget(self.comboBox, 2, 1) self.layout.addWidget(self.Label2, 3, 0) self.layout.addWidget(self.maxabsLabel, 4, 0) self.layout.addWidget(self.maxabsEdit, 4, 1) self.layout.addWidget(self.borderLabel, 5, 0) self.layout.addWidget(self.borderEdit, 5, 1) self.layout.addWidget(self.Label3, 6, 0) self.layout.addWidget(self.colorLabe0, 7, 0) self.layout.addWidget(self.color0_button, 7, 1) self.layout.addWidget(self.colorLabel1, 8, 0) self.layout.addWidget(self.color1_button, 8, 1) self.layout.addWidget(self.checkbox1, 9, 0) self.layout.addWidget(self.checkbox2, 9, 1) self.layout.addWidget(self.Label4, 10, 0) self.layout.addWidget(self.ok, 11, 1) self.win.setLayout(self.layout) self.win.setGeometry(100,100,300,300) self.win.setWindowTitle("Settings") self.tmp_colors=[deepcopy(x) for x in self.colors] self.win.show() def get_color(self,i): self.tmp_colors[i] = QColorDialog.getColor().getRgb() if i ==0: self.color0_button.setStyleSheet("background-color:rgb"+str(self.tmp_colors[i])) else: self.color1_button.setStyleSheet("background-color:rgb"+str(self.tmp_colors[i])) def restart(self): self.running=False try: tmp=int(self.maxabsEdit.text()) if tmp>=0: self.maxAbsences=tmp self.masked_tracker.maxAbsences=self.maxAbsences self.unmasked_tracker.maxAbsences=self.maxAbsences except: self.maxabsEdit.setText(str(self.maxAbsences)) try: tmp=float(self.minscoreEdit.text()) if tmp>=0 and tmp<=100: self.min_score=tmp/100 except: self.minscoreEdit.setText(str(self.min_score*100)) try: tmp=int(self.borderEdit.text()) if tmp>=0: self.border_pxl=tmp except: self.maxabsEdit.setText(str(self.border_pxl)) self.border_pxl=int(self.borderEdit.text()) self.colors=[tuple(list(x)[:3]) for x in self.tmp_colors] self.textCM.setStyleSheet("background-color:black; color:"+('#%02x%02x%02x' % self.colors[1])+"; font:bold; border-style:outset;\ border-width:1px; border-radius:5px") self.textCV.setStyleSheet("background-color:black; color:"+('#%02x%02x%02x' % self.colors[0])+"; font:bold; border-style:outset;\ border-width:1px; border-radius:5px") self.textTM.setStyleSheet("background-color:black; color:"+('#%02x%02x%02x' % self.colors[1])+"; font:bold; border-style:outset;\ border-width:1px; border-radius:5px") self.textTV.setStyleSheet("background-color:black; color:"+('#%02x%02x%02x' % self.colors[0])+"; font:bold; border-style:outset;\ border-width:1px; border-radius:5px") if self.checkbox1.isChecked(): self.show_scores=True else: self.show_scores=False if self.checkbox2.isChecked(): self.show_IDs=True else: self.show_IDs=False if self.default_model!=self.comboBox.currentText(): self.default_model=self.comboBox.currentText() self.path_to_ckpt = self.models_path+'\\'+self.default_model+'.pb' self.load_model() self.define_io_tensors() self.running=True self.start() def is_valid_filename(self,filename): invalid=['\\', '/', ':', '*', '?', '"', '<', '>', '|'] for i in invalid: if i in filename: return False return True def export(self): # Generate and export statistics date=datetime.datetime.now() name = QFileDialog.getSaveFileName(self, 'Save File', str(date.strftime("%Y-%m-%d_%H-%M-%S")), "XLSX (*.xlsx)") if name[0]=='' or self.DATA=={}: pass elif self.is_valid_filename(name[0].split('/')[-1]): export_records(name[0], self.DATA) else: self.export() def load_model(self): # Load the Tensorflow model into memory. self.detection_graph = tf.Graph() with self.detection_graph.as_default(): od_graph_def = tf.compat.v1.GraphDef() with tf.io.gfile.GFile(self.path_to_ckpt, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') self.sess = tf.compat.v1.Session(graph=self.detection_graph) def define_io_tensors(self): # Define input and output tensors (i.e. data) for the object detection classifier # Input tensor is the image self.image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0') # Output tensors are the detection boxes, scores, and classes # Each box represents a part of the image where a particular object was detected self.detection_boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represents level of confidence for each of the objects. # The score is shown on the result image, together with the class label. self.detection_scores = self.detection_graph.get_tensor_by_name('detection_scores:0') self.detection_classes = self.detection_graph.get_tensor_by_name('detection_classes:0') # Number of objects detected self.num_detections = self.detection_graph.get_tensor_by_name('num_detections:0') def video_setting(self): # Initialize webcam feed self.video = cv2.VideoCapture(0,cv2.CAP_DSHOW) self.ret = self.video.set(3, 1280) self.ret = self.video.set(4, 720) def save_data(self): # Save data f=open(self.DATA_FILE, 'wb') pickle.dump(self.DATA,f) f.close() with open(self.tmppath, 'w+') as f: f.write('%d,%d' %(self.cntMTot, self.cntVTot)) def start(self): time.sleep(2) while(self.running): try: # Acquire frame and expand frame dimensions to have shape: [1, None, None, 3] # i.e. a single-column array, where each item in the column has the pixel RGB value ret, frame = self.video.read() frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame_expanded = np.expand_dims(frame_rgb, axis=0) # Perform the actual detection by running the model with the image as input (boxes, scores, classes, num) = self.sess.run( [self.detection_boxes, self.detection_scores, self.detection_classes, self.num_detections], feed_dict={self.image_tensor: frame_expanded}) faces=[] labels=[] for i,score in enumerate(scores[0]): if score>self.min_score: ymin=int(boxes[0][i][0]*frame.shape[0]) xmin=int(boxes[0][i][1]*frame.shape[1]) ymax=int(boxes[0][i][2]*frame.shape[0]) xmax=int(boxes[0][i][3]*frame.shape[1]) lab=self.categories[int(classes[0][i])-1] faces.append([xmin,xmax,ymin,ymax]) labels.append(lab) ind=int(classes[0][i])-1 # Draw the results of the detection cv2.rectangle(frame, (xmin, ymin), (xmax, ymax),tuple((list(self.colors[ind])[:3])[::-1]), 2) if self.show_scores: text=lab+': '+str(int(score*100))+'%' font_scale = (xmax-xmin)/frame.shape[1]*3 (text_width, text_height) = cv2.getTextSize(text, self.font, fontScale=font_scale, thickness=2)[0] text_offset_x = xmin text_offset_y = ymin box_coords = ((text_offset_x, text_offset_y), (text_offset_x + text_width + 2, text_offset_y - text_height - 2)) cv2.rectangle(frame, box_coords[0], box_coords[1], tuple((list(self.colors[ind])[:3])[::-1]), cv2.FILLED) cv2.putText(frame, text, (text_offset_x, text_offset_y), self.font, fontScale=font_scale, color=(0, 0, 0), thickness=2,lineType=2) # Get the list of all masked faces masked_faces=[faces[i] for i, x in enumerate(labels) if x == self.categories[1]] # Get the list of all not masked faces unmasked_faces=[faces[i] for i, x in enumerate(labels) if x == self.categories[0]] # Tracking masked_people=self.masked_tracker.refresh(masked_faces,[frame.shape[0],frame.shape[1]],border=self.border_pxl) unmasked_people=self.unmasked_tracker.refresh(unmasked_faces,[frame.shape[0],frame.shape[1]],border=self.border_pxl) # Check proximity between people result=proximity_detector(masked_people, unmasked_people) # if near people are detected, results are reported and sound and graphical alarms are activated for r in result: if r in list(self.crowd_list.keys()): if (time.time()-self.crowd_list[r])>self.alarm_time: self.alarm_list.add(r) else: self.crowd_list[r]=time.time() tmp=deepcopy(self.crowd_list) for k in list(tmp.keys()): if k not in result: del self.crowd_list[k] if k in self.alarm_list: self.alarm_list.remove(k) # run sound alarm if len(self.alarm_list)>0 and not self.alarm_on: thread1 = threading.Thread(target = self.alarm) thread1.start() # loop over the tracked masked people for (objectID, box) in masked_people.items(): # draw both the ID of the object and the centroid of the # object on the output frame if self.show_IDs: xmin,xmax,ymin,ymax=box text = "M{}".format(objectID) font_scale = (xmax-xmin)/frame.shape[1]*3 (text_width, text_height) = cv2.getTextSize(text, self.font, fontScale=font_scale, thickness=2)[0] text_offset_x = xmin text_offset_y = ymax box_coords = ((text_offset_x, text_offset_y), (text_offset_x + text_width + 2, text_offset_y - text_height - 2)) cv2.rectangle(frame, box_coords[0], box_coords[1], tuple((list(self.colors[1])[:3])[::-1]), cv2.FILLED) cv2.putText(frame, text, (text_offset_x, text_offset_y), self.font, fontScale=font_scale, color=(0, 0, 0), thickness=2,lineType=2) # if people are too near, a red rectangle is drawn for alarm in self.alarm_list: if alarm[0]==text or alarm[1]==text: cv2.rectangle(frame, (xmin,ymin), (xmax,ymax), (0,0,255), thickness = 5) #update total number of masked if objectID>self.cntMTot: self.cntMTot=objectID # loop over the tracked unmasked people for (objectID, box) in unmasked_people.items(): # draw both the ID of the object and the centroid of the # object on the output frame if self.show_IDs: xmin,xmax,ymin,ymax=box text = "NM{}".format(objectID) font_scale = (xmax-xmin)/frame.shape[1]*3 (text_width, text_height) = cv2.getTextSize(text, self.font, fontScale=font_scale, thickness=2)[0] text_offset_x = xmin text_offset_y = ymax box_coords = ((text_offset_x, text_offset_y), (text_offset_x + text_width + 2, text_offset_y - text_height - 2)) cv2.rectangle(frame, box_coords[0], box_coords[1], tuple((list(self.colors[0])[:3])[::-1]), cv2.FILLED) cv2.putText(frame, text, (text_offset_x, text_offset_y), self.font, fontScale=font_scale, color=(0, 0, 0), thickness=2,lineType=2) # if people are too near, a red rectangle is drawn for alarm in self.alarm_list: if alarm[0]==text or alarm[1]==text: cv2.rectangle(frame, (xmin,ymin), (xmax,ymax), (0,0,255), thickness = 5) # update total number of unmasked if objectID>self.cntVTot: self.cntVTot=objectID # Update graphical statistics self.cntM = labels.count('With Mask') self.cntV = labels.count('Without Mask') self.textCM.setText('Current Number of People '+self.categories[1]+': %d' %self.cntM) self.textCV.setText('Current Number of People '+self.categories[0]+': %d' %self.cntV) self.textTM.setText('Total Number of People '+self.categories[1]+': %d' %self.cntMTot) self.textTV.setText('Total Number of People '+self.categories[0]+': %d' %self.cntVTot) self.timestamp=time.time() # Save samples each second if self.timestamp-self.t1>1: self.DATA[round(self.timestamp,6)]={"NM":list(unmasked_people.keys()),"M":list(masked_people.keys())} self.t1=self.timestamp # Write data to file every 60 seconds if self.timestamp-self.t2>60: self.save_data() self.t2=self.timestamp if not self.isVisible(): exit() # All the results have been drawn on the frame, so it's time to display it. height, width, channel = frame.shape bytesPerLine = 3 * width self.qImg = QImage(frame.data, width, height, bytesPerLine, QImage.Format_RGB888).rgbSwapped() self.pic.setPixmap(QPixmap(self.qImg)) if cv2.waitKey(1) == ord('q'): break except: with open(self.tmppath, 'w+') as file: file.write('%d,%d' %(self.cntMTot, self.cntVTot)) exit() def alarm(self): self.alarm_on=True playsound('data/beep.mp3') self.alarm_on=False
class TorrentClient: """ The torrent client is the local peer that holds peer-to-peer connections to download and upload pieces for a given torrent. Once started, the client makes periodic announce calls to the tracker registered in the torrent meta-data. These calls results in a list of peers that should be tried in order to exchange pieces. Each received peer is kept in a queue that a pool of PeerConnection objects consume. There is a fix number of PeerConnections that can have a connection open to a peer. Since we are not creating expensive threads (or worse yet processes) we can create them all at once and they will be waiting until there is a peer to consume in the queue. """ def __init__(self, torrent): self.tracker = Tracker(torrent) # The list of potential peers is the work queue, consumed by the # PeerConnections self.available_peers = Queue() # The list of peers is the list of workers that *might* be connected # to a peer. Else they are waiting to consume new remote peers from # the `available_peers` queue. These are our workers! self.peers = [] # The piece manager implements the strategy on which pieces to # request, as well as the logic to persist received pieces to disk. self.piece_manager = PieceManager(torrent) self.abort = False async def start(self): """ Start downloading the torrent held by this client. This results in connecting to the tracker to retrieve the list of peers to communicate with. Once the torrent is fully downloaded or if the download is aborted this method will complete. """ self.peers = [ PeerConnection(self.available_peers, self.tracker.torrent.info_hash, self.tracker.peer_id, self.piece_manager, self._on_block_retrieved) for _ in range(MAX_PEER_CONNECTIONS) ] # The time we last made an announce call (timestamp) previous = None # Default interval between announce calls (in seconds) interval = 30 * 60 while True: if self.piece_manager.complete: logging.info('Torrent fully downloaded!') break if self.abort: logging.info('Aborting download...') break current = time.time() if (not previous) or (previous + interval < current): response = await self.tracker.connect( first=previous if previous else False, uploaded=self.piece_manager.bytes_uploaded, downloaded=self.piece_manager.bytes_downloaded) if response: previous = current interval = response.interval self._empty_queue() for peer in response.peers: self.available_peers.put_nowait(peer) else: await asyncio.sleep(5) self.stop() def _empty_queue(self): while not self.available_peers.empty(): self.available_peers.get_nowait() def stop(self): """ Stop the download or seeding process. """ self.abort = True for peer in self.peers: peer.stop() self.piece_manager.close() self.tracker.close() def _on_block_retrieved(self, peer_id, piece_index, block_offset, data): """ Callback function called by the `PeerConnection` when a block is retrieved from a peer. :param peer_id: The id of thelf.available_peerse peer the block was retrieved from :param piece_index: The piece index this block is a part of :param block_offset: The block offset within its piece :param data: The binary data retrieved """ self.piece_manager.block_received(peer_id=peer_id, piece_index=piece_index, block_offset=block_offset, data=data)
def __init__(self, *args, **kwargs): super(ObjectDetection, self).__init__(*args, **kwargs) self.DATA_FILE='data/DATA.bin' self.CONFIG_FILE='data/CONFIG.json' self.running=True self.opened_settings=False self.crowd_list={} self.alarm_time=1 # 1 second self.alarm_list=set() self.alarm_on=False self.t1=time.time() self.t2=time.time() self.t3=time.time() # Load records if os.path.exists(self.DATA_FILE): f = open(self.DATA_FILE, "rb") if True: self.DATA = pickle.load(f) if self.DATA!={}: last=datetime.datetime.utcfromtimestamp(list(self.DATA.keys())[-1]) now=datetime.datetime.now() tmp=[now.year,now.month,now.day,now.hour] tmp2=[last.year,last.month,last.day,last.hour] new=last while tmp2!=tmp: new= new + datetime.timedelta(seconds = 3600) tmp2=[new.year,new.month,new.day,new.hour] timestamp=new.timestamp() timestamp=round(timestamp,6) self.DATA[timestamp]={"NM":[],"M":[]} else: self.DATA={} f.close() else: self.DATA={} # Load settings with open(self.CONFIG_FILE) as json_file: self.CONFIGS = json.load(json_file) # Import settings from configuration file self.maxAbsences=self.CONFIGS["maxAbsences"] self.categories =self.CONFIGS["categories"] self.colors =[tuple(x) for x in self.CONFIGS["colors"]] self.min_scores=self.CONFIGS["min_score"] self.border_pxl=self.CONFIGS["border"] self.models_path=self.CONFIGS["models_path"] self.models=os.listdir(self.models_path) self.models=['.'.join(x.split('.')[:-1]) for x in self.models] self.default_model=self.CONFIGS["default_model"] self.min_score=self.min_scores[self.default_model] self.path_to_ckpt = self.models_path+'\\'+self.default_model+'.pb' self.show_scores=bool(self.CONFIGS["show_scores"]) self.show_IDs=bool(self.CONFIGS["show_IDs"]) # Load counts from temp directory self.tmppath = 'C:\\Users\\{}\\AppData\\Local\\Temp'.format(os.getlogin()) + '\\COVIDEO_cnts.txt' if os.path.exists(self.tmppath): with open(self.tmppath, 'r') as file: data = file.readline().split(',') self.cntMTot = int(data[0]) self.cntVTot = int(data[1]) else: with open(self.tmppath, 'w+') as file: self.cntMTot=0 self.cntVTot=0 file.write('%d,%d' %(self.cntMTot, self.cntVTot)) # Init an istance of a tracker for each class self.masked_tracker=Tracker(maxAbsences=self.maxAbsences, startID=(self.cntMTot+1)) self.unmasked_tracker=Tracker(maxAbsences=self.maxAbsences, startID=(self.cntVTot+1)) self.font = cv2.FONT_HERSHEY_SIMPLEX self.setWindowTitle('COVIDEO v3') self.setWindowIcon(QIcon('img\\Icon.jpg')) self.setGeometry(100, 100, 1280, 720) self.setStyleSheet("background-color:white") self.setMinimumWidth(1280) self.setMaximumWidth(1280) self.setMaximumHeight(720) self.setMinimumHeight(720) self.pic = QLabel(self) self.pic.setGeometry(0, 0, 1280, 720) self.logo = QLabel(self) self.logo.setGeometry(0, 690, 180, 30) self.logo.setStyleSheet("background-color:transparent;") self.logo.setPixmap(QPixmap('img\\logo_white.png')) self.logo.setScaledContents(True) self.textCM = QPushButton(self) self.textCM.setStyleSheet("background-color:black; color:"+('#%02x%02x%02x' % self.colors[1])+"; font:bold; border-style:outset;\ border-width:1px; border-radius:5px") self.textCM.setText('Current Number of People '+self.categories[1]+': 0') self.textCM.setGeometry(1030, 5, 250, 15) self.textCV = QPushButton(self) self.textCV.setStyleSheet("background-color:black; color:"+('#%02x%02x%02x' % self.colors[0])+"; font:bold; border-style:outset;\ border-width:1px; border-radius:5px") self.textCV.setText('Current Number of People '+self.categories[0]+': 0') self.textCV.setGeometry(1030, 22.5, 250, 15) self.textTM = QPushButton(self) self.textTM.setStyleSheet("background-color:black; color:"+('#%02x%02x%02x' % self.colors[1])+"; font:bold; border-style:outset;\ border-width:1px; border-radius:5px") self.textTM.setText('Total Number of People '+self.categories[1]+': 0') self.textTM.setGeometry(1030, 40, 250, 15) self.textTV = QPushButton(self) self.textTV.setStyleSheet("background-color:black; color:"+('#%02x%02x%02x' % self.colors[0])+"; font:bold; border-style:outset;\ border-width:1px; border-radius:5px") self.textTV.setText('Total Number of People '+self.categories[0]+': 0') self.textTV.setGeometry(1030, 57.5, 250, 15) self.b1 = QPushButton(self) self.b1.setStyleSheet("QPushButton{background-color:black; color:red; font:bold; border-style:outset;\ border-width:2px; border-radius:10px}"\ "QPushButton:hover{background-color:red; color:black; font:bold; border-style:outset;\ border-width:2px; border-radius:10px}"\ "QPushButton:pressed{background-color:black; color:red; font:bold; border-style:outset;\ border-width:2px; border-radius:10px}") self.b1.clicked.connect(self.reset_cnts) self.b1.setText('Reset Totals') self.b1.setGeometry(1175, 685, 100, 30) self.b2 = QPushButton(self) self.b2.setStyleSheet("QPushButton{background-color:black; color:white; font:bold; border-style:outset;\ border-width:2px; border-radius:10px}"\ "QPushButton:hover{background-color:white; color:black; font:bold; border-style:outset;\ border-width:2px; border-radius:10px}"\ "QPushButton:pressed{background-color:black; color:white; font:bold; border-style:outset;\ border-width:2px; border-radius:10px}") self.b2.clicked.connect(self.change_settings) self.b2.setText('Settings') self.b2.setGeometry(1175, 650, 100, 30) self.b3 = QPushButton(self) self.b3.setStyleSheet("QPushButton{background-color:black; color:green; font:bold; border-style:outset;\ border-width:2px; border-radius:10px}"\ "QPushButton:hover{background-color:green; color:black; font:bold; border-style:outset;\ border-width:2px; border-radius:10px}"\ "QPushButton:pressed{background-color:black; color:green; font:bold; border-style:outset;\ border-width:2px; border-radius:10px}") self.b3.clicked.connect(self.export) self.b3.setText('Export') self.b3.setGeometry(1175, 615, 100, 30) #Load categories self.category_index={1: {'id': 1, 'name': self.categories[0]}, 2: {'id': 2, 'name': self.categories[1]}} # Run main functions self.load_model() self.define_io_tensors() self.video_setting() self.show() self.start()
def main(): # get filename from the command line argument parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('-f', '--file', required=True, dest = 'file', type = argparse.FileType('r')) args = parser.parse_args() filename = os.path.abspath(args.file.name) # get torrent file data torrentfile = TorrentFile(filename) url = torrentfile.get_tracker_request_url() downloading_file = os.path.abspath('../related_assets/downloads/%s' % torrentfile.filename) file = open(downloading_file, 'wb') # client_handshake client_handshake = HandShake() client_handshake.set_default_values(torrentfile.info_hash) # tracker tracker = Tracker(url, str(client_handshake)) tracker.send_request() # add peers to the tracker peers collection peers_list = tracker.get_peers_list() tracker.add_peers(peers_list) """ TODO -- remove the lines below """ peer = tracker.get_peer_by_ip_port('96.126.104.219', 65373) peer.connection.open() peer.connection.send_data(str(client_handshake)) # create peer handshake instance peer_handshake_string = peer.connection.recv_data() peer_handshake = HandShake() peer_handshake.set_handshake_data_from_string(peer_handshake_string) data = peer.connection.recv_data() peer.append_to_buffer(data) peer.consume_messages() msg = peer.get_interested_message() peer.connection.send_data(msg) data = peer.connection.recv_data() peer.append_to_buffer(data) peer.consume_messages() requested_length = int(math.pow(2,14)) for i in range(0, 78): msg = peer.get_request_piece_message(i, 0, requested_length) peer.connection.send_data(msg) data = peer.connection.recv_data() data_length = peer.get_4_byte_to_decimal(data[0:4]) # keep receiving data until you have the entire block while len(data) < data_length + 4: data += peer.connection.recv_data() peer.append_to_buffer(data) peer.consume_messages() # get last piece (which is smaller than the rest) msg = peer.get_request_piece_message(78, 0, 35) peer.connection.send_data(msg) data = peer.connection.recv_data() data_length = peer.get_4_byte_to_decimal(data[0:4]) # keep receiving data until you have the entire block while len(data) < data_length + 4: data += peer.connection.recv_data() peer.append_to_buffer(data) peer.consume_messages()