def __max_move(self, game, level, alpha, beta): # return the pos and best(max) value # alpha is the best_value for now in a max_move # beta is the best_value for now in a min_move best_pos = None best_value = self.__MIN_VAL if game.game_status != GameStatus.UNDERGOING or abs( level) > self.__MAX_DEPTH: return best_pos, self.__evaluate.evaluate( game=game, eval_side=self.__eval_side) moves = game.board.nearby_availables if level == 0: common.dprint( 'avl moves: ' + ' '.join([common.pos2h(p, game.board.width) for p in moves])) for pos in moves: if level == 0: common.dprint(common.pos2h(pos, game.board.width) + ' ', False) game.move(pos) min_value = self.__min_move(game, level - 1, alpha, beta) game.undo_move() if min_value > best_value: best_pos = pos best_value = min_value alpha = max(best_value, alpha) if alpha >= beta: break return best_pos, best_value
def search_best_move(self, game, eval_side): self.__eval_side = eval_side res = self.__max_move(game, level=0, alpha=self.__MIN_VAL, beta=self.__MAX_VAL) common.dprint(str(res)) return res
def choose_best_move(self, game, *args): common.dprint('considering...') pos, value = self.__search.search_best_move(game, eval_side=self.PLAYER) common.dprint('\t'.join( ['my move:', common.pos2h(pos, game.board.width), str(value)])) return pos, value
def send_request_udp(pkt, host, port, family, itimeout, retries): response, responder = b"", ("", 0) s = socket.socket(family, socket.SOCK_DGRAM) if options["srcip"]: s.bind((options["srcip"], 0)) if is_multicast(host) and (host.find('.') != -1): s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, \ socket.inet_aton(options["srcip"])) timeout = itimeout while retries > 0: s.settimeout(timeout) try: s.sendto(pkt, (host, port)) (response, responder) = s.recvfrom(BUFSIZE) break except socket.timeout: timeout = timeout * 2 dprint("Request timed out with no answer") retries -= 1 s.close() return (response, responder)
def delete_tickets(args, ids, scrub=False): """Deletes the tickets specified in the search results JSON. Args: args (`dict`): The list of arguments received in the `_main function: * subdomain * username * password * auth_type ids (List[int]): A list of IDs of tickets to delete. scrub (Optioanl[bool]): Indicates whether to do a delete operation or a ticket scrub operation. Default: delete (False) The bulk delete API operation can only delete up to 100 tickets at a time: https://developer.zendesk.com/rest_api/docs/core/tickets#bulk-delete-tickets """ while len(ids) > 0: bulk_ids = ids[:100] ids = ids[100:] delete_url = "" if scrub: delete_url = get_scrub_delete_url(args['subdomain'], bulk_ids) else: delete_url = get_bulk_delete_url(args['subdomain'], bulk_ids) dprint(delete_url) #delete_req = RequestWithMethod(url=delete_url, method='DELETE') #set_auth(delete_req, args['username'], args['password'], # args['auth_type']) #http.fetch_request(delete_req) resp = http.get_reponse(url=delete_url, username=args['username'], password=args['password'], auth_type=args['auth_type'], is_delete=True, http_method=http.const.CURL) dprint(resp)
def Update(self, detections): """Update tracks vector using following steps: - Create tracks if no tracks vector found - Calculate cost using sum of square distance between predicted vs detected centroids - Using Hungarian Algorithm assign the correct detected measurements to predicted tracks https://en.wikipedia.org/wiki/Hungarian_algorithm - Identify tracks with no assignment, if any - If tracks are not detected for long time, remove them - Now look for un_assigned detects - Start new tracks - Update KalmanFilter state, lastResults and tracks trace Args: detections: detected centroids of object to be tracked Return: None """ # Create tracks if no tracks vector found if (len(self.tracks) == 0): for i in range(len(detections)): track = Track(detections[i], self.trackIdCount) self.trackIdCount += 1 self.tracks.append(track) # Calculate cost using sum of square distance between # predicted vs detected centroids N = len(self.tracks) M = len(detections) cost = np.zeros(shape=(N, M)) # Cost matrix for i in range(len(self.tracks)): for j in range(len(detections)): try: diff = self.tracks[i].prediction - detections[j][0] distance = np.sqrt(diff[0][0] * diff[0][0] + diff[1][0] * diff[1][0]) d_angle = self.tracks[i].angles[-1] - detections[j][1] diff_angle = min(d_angle, d_angle + 360, d_angle - 360, key=abs) cost[i][j] = distance + abs(diff_angle) / 2 except: pass # Let's average the squared ERROR cost = (0.5) * cost # Using Hungarian Algorithm assign the correct detected measurements # to predicted tracks assignment = [] for _ in range(N): assignment.append(-1) row_ind, col_ind = linear_sum_assignment(cost) for i in range(len(row_ind)): assignment[row_ind[i]] = col_ind[i] # Identify tracks with no assignment, if any un_assigned_tracks = [] for i in range(len(assignment)): if (assignment[i] != -1): # check for cost distance threshold. # If cost is very high then un_assign (delete) the track if (cost[i][assignment[i]] > self.dist_thresh): assignment[i] = -1 un_assigned_tracks.append(i) pass else: self.tracks[i].skipped_frames += 1 # If tracks are not detected for long time, remove them del_tracks = [] for i in range(len(self.tracks)): if (self.tracks[i].skipped_frames > self.max_frames_to_skip): del_tracks.append(i) if len(del_tracks) > 0: # only when skipped frame exceeds max for id in del_tracks: if id < len(self.tracks): del self.tracks[id] del assignment[id] else: dprint("ERROR: id is greater than length of tracks") # Now look for un_assigned detects un_assigned_detects = [] for i in range(len(detections)): if i not in assignment: un_assigned_detects.append(i) # Start new tracks if (len(un_assigned_detects) != 0): for i in range(len(un_assigned_detects)): track = Track(detections[un_assigned_detects[i]], self.trackIdCount) self.trackIdCount += 1 self.tracks.append(track) # Update KalmanFilter state, lastResults and tracks trace for i in range(len(assignment)): self.tracks[i].KF.predict() if (assignment[i] != -1): self.tracks[i].skipped_frames = 0 self.tracks[i].prediction = self.tracks[i].KF.correct( detections[assignment[i]][0], 1)[0:2] self.tracks[i].trace_save.append(detections[assignment[i]][0]) else: self.tracks[i].prediction = self.tracks[i].KF.correct( np.array([[0], [0]]), 0)[0:2] self.tracks[i].trace_save.append(self.tracks[i].prediction) self.tracks[i].angles.append(detections[assignment[i]][1]) self.tracks[i].states.append(detections[assignment[i]][2]) if (len(self.tracks[i].trace) > self.max_trace_length): for j in range( len(self.tracks[i].trace) - self.max_trace_length): del self.tracks[i].trace[j] # if (len(self.tracks[i].prediction[0]) > 1): # temp = np.zeros((2, 1)) # temp[0] = self.tracks[i].prediction[0][0] # temp[1] = self.tracks[i].prediction[0][1] # self.tracks[i].trace.append(temp) # self.tracks[i].KF.lastResult = temp # self.tracks[i].trace_save.append(temp) # else: self.tracks[i].trace.append(self.tracks[i].prediction) self.tracks[i].KF.lastResult = self.tracks[i].prediction
def Update(self, detections, rectw_h, key_frame): """Update tracks vector using following steps: - Create tracks if no tracks vector found - Calculate cost using sum of square distance between predicted vs detected centroids - Using Hungarian Algorithm assign the correct detected measurements to predicted tracks https://en.wikipedia.org/wiki/Hungarian_algorithm - Identify tracks with no assignment, if any - If tracks are not detected for long time, remove them - Now look for un_assigned detects - Start new tracks - Update KalmanFilter state, lastResults and tracks trace Args: detections: detected centroids of object to be tracked Return: None """ #initializer self.predict_center = [] rect_w, rect_h = rectw_h[:, 0], rectw_h[:, 1] #detect_box_num = len(rectw_h) # Create tracks if no tracks vector found if config.Debug: print("-----------------traker begin") if (len(self.tracks) == 0): for i in range(len(detections)): track = Track(detections[i], self.trackIdCount) if config.Debug: print("tracker init,ID: ", self.trackIdCount) self.trackIdCount += 1 self.tracks.append(track) # Calculate cost using sum of square distance between # predicted vs detected centroids N = len(self.tracks) M = len(detections) if config.Debug: #print("-----------------traker begin") print("traker and detect ", N, M) cost = np.zeros(shape=(N, M)) # Cost matrix for i in range(len(self.tracks)): for j in range(len(detections)): try: diff = self.tracks[i].prediction - detections[j] distance = np.sqrt(diff[0][0] * diff[0][0] + diff[1][0] * diff[1][0]) cost[i][j] = distance except: pass # Let's average the squared ERROR cost = (0.5) * cost if key_frame: # Using Hungarian Algorithm assign the correct detected measurements # to predicted tracks self.assignment = [] for _ in range(N): self.assignment.append(-1) row_ind, col_ind = linear_sum_assignment(cost) for i in range(len(row_ind)): self.assignment[row_ind[i]] = col_ind[i] if config.Debug: print("row_id ", row_ind) print("col_id ", col_ind) print("assignment ", self.assignment) # Identify tracks with no assignment, if any un_assigned_tracks = [] del_key_tracks = [] for i in range(len(self.assignment)): if (self.assignment[i] != -1): # check for cost distance threshold. # If cost is very high then un_assign (delete) the track ''' left = 1 if self.tracks[i].prediction[0][0] - rect_w[i]/2 <0 else 0 right = 1 if self.tracks[i].prediction[0][0] + rect_w[i]/2 >= self.width else 0 top = 1 if self.tracks[i].prediction[1][0] - rect_h[i]/2 <0 else 0 bottom = 1 if self.tracks[i].prediction[1][0] + rect_h[i]/2 >= self.height else 0 ''' #if (cost[i][assignment[i]] > self.dist_thresh or left or right or top or bottom): if (cost[i][self.assignment[i]] > self.dist_thresh): #print("-------------,cost[i][assignment[i]],left,right,top,bottom",cost[i][assignment[i]],left,right,top,bottom) print("-------------,cost[i][assignment[i]]", cost[i][self.assignment[i]]) self.assignment[i] = -1 un_assigned_tracks.append(i) self.tracks[i].skipped_frames += 1 ''' if key_frame: del assignment[i] del self.tracks[i] ''' pass elif key_frame: ''' del assignment[i] del self.tracks[i] if config.Debug: print("after key_frame del assignment ", assignment) ''' del_key_tracks.append(i) self.tracks[i].skipped_frames += 1 else: self.tracks[i].skipped_frames += 1 if config.Debug: print("-1 key_frame", key_frame) ''' if len(un_assigned_tracks) and len(del_key_tracks): sort_tmp = np.array([un_assigned_tracks[:],del_key_tracks[:]]) sort_tmp = np.sort(sort_tmp,axis=None)[::-1] for j in sort_tmp: del assignment[j] del self.tracks[j] if config.Debug: print("key and always del assignment ", assignment) elif len(un_assigned_tracks): sort_tmp = np.sort(un_assigned_tracks)[::-1] for j in sort_tmp: del assignment[j] del self.tracks[j] if config.Debug: print("always del assignment ", assignment) elif len(del_key_tracks): sort_tmp = np.sort(del_key_tracks)[::-1] for j in sort_tmp: del assignment[j] del self.tracks[j] if config.Debug: print("key del assignment ", assignment) ''' # If tracks are not detected for long time, remove them self.del_tracks = [] for i in range(len(self.tracks)): if (self.tracks[i].skipped_frames > self.max_frames_to_skip): self.del_tracks.append(i) if len(self.del_tracks) > 0: # only when skipped frame exceeds max sort_tmp = np.sort(self.del_tracks)[::-1] for id in sort_tmp: if id < len(self.tracks): del self.tracks[id] del self.assignment[id] print("-----------del a face") else: dprint("ERROR: id is greater than length of tracks") # Now look for un_assigned detects un_assigned_detects = [] for i in range(len(detections)): if i not in self.assignment and key_frame: if config.Debug: print( " new track will: tracker_num,det_num and i ,key_frame", len(self.tracks), len(detections), i, key_frame, self.assignment) un_assigned_detects.append(i) # Start new tracks if (len(un_assigned_detects) != 0): print("start new track") for i in range(len(un_assigned_detects)): track = Track(detections[un_assigned_detects[i]], self.trackIdCount) if config.Debug: print("assign Id: ", self.trackIdCount) self.trackIdCount += 1 self.tracks.append(track) if key_frame: self.assignment.append(un_assigned_detects[i]) # Update KalmanFilter state, lastResults and tracks trace #for i in range(len(assignment)): for i in range(len(detections)): self.tracks[i].KF.predict() #if(assignment[i] != -1): if i in self.assignment: self.tracks[i].skipped_frames = 0 if config.tracker_cv: pos = self.tracks[i].KF.correct( detections[self.assignment[i]]) c_x = pos[0] c_y = pos[1] w = detections[self.assignment[i]][2] h = detections[self.assignment[i]][3] self.tracks[i].prediction = [c_x, c_y, w, h] else: self.tracks[i].prediction = self.tracks[i].KF.correct( detections[self.assignment[i]], 1) else: self.tracks[i].prediction = self.tracks[i].KF.correct( detections[i], 1) #self.tracks[i].prediction = self.tracks[i].prediction if (len(self.tracks[i].trace) > self.max_trace_length): for j in range( len(self.tracks[i].trace) - self.max_trace_length): del self.tracks[i].trace[j] if config.tracker_cv: self.tracks[i].trace.append(self.tracks[i].prediction[:2]) else: self.tracks[i].trace.append(self.tracks[i].prediction) if config.tracker_cv: self.predict_center.append(self.tracks[i].prediction) else: self.tracks[i].KF.lastResult = self.tracks[i].prediction x = self.tracks[i].prediction[0][0] y = self.tracks[i].prediction[1][0] self.predict_center.append(np.array([[x], [y]], dtype=np.int)) self.assign_out = self.assignment if config.Debug: print("---------------trackor over ", len(self.tracks))
def Update(self, detections, flag): """Update tracks vector using following steps: - Create tracks if no tracks vector found - Calculate cost using sum of square distance between predicted vs detected centroids - Using Hungarian Algorithm assign the correct detected measurements to predicted tracks https://en.wikipedia.org/wiki/Hungarian_algorithm - Identify tracks with no assignment, if any - If tracks are not detected for long time, remove them - Now look for un_assigned detects - Start new tracks - Update KalmanFilter state, lastResults and tracks trace Args: detections: detected centroids of object to be tracked Return: None """ assignment = [] if flag == 1: # Create tracks if no tracks vector found if (len(self.tracks) == 0): for i in range(len(detections)): print('detections : ', detections) track = Track(detections[i], self.trackIdCount) self.trackIdCount += 1 self.tracks.append(track) # Calculate cost using sum of square distance between # predicted vs detected centroids N = len(self.tracks) M = len(detections) cost = np.zeros(shape=(N, M)) # Cost matrix print('N: ', N) print('M: ', M) for i in range(len(self.tracks)): for j in range(len(detections)): try: diff1 = np.subtract(self.tracks[i].prediction[0], detections[j][0]) diff2 = np.subtract(self.tracks[i].prediction[1], detections[j][1]) diff = np.array([[diff1], [diff2]]) distance = np.sqrt(diff[0][0] * diff[0][0] + diff[1][0] * diff[1][0]) cost[i][j] = distance #print("differece: ",diff,"prediction: ",self.tracks[i].prediction,"detections: ",detections[j]) #print("cost: i: ",i," j: ",j,": ",cost[i][j]) except: pass # Let's average the squared ERROR cost = (0.5) * cost # Using Hungarian Algorithm assign the correct detected measurements # to predicted tracks for _ in range(N): assignment.append(-1) row_ind, col_ind = linear_sum_assignment(cost) for i in range(len(row_ind)): assignment[row_ind[i]] = col_ind[i] # Identify tracks with no assignment, if any un_assigned_tracks = [] for i in range(len(assignment)): if (assignment[i] != -1): # check for cost distance threshold. # If cost is very high then un_assign (delete) the track if (cost[i][assignment[i]] > self.dist_thresh): assignment[i] = -1 un_assigned_tracks.append(i) pass else: self.tracks[i].skipped_frames += 1 print('Assignment after thresholding: ', assignment) # If tracks are not detected for long time, remove them del_tracks = [] for i in range(len(self.tracks)): if (self.tracks[i].skipped_frames > self.max_frames_to_skip): del_tracks.append(i) if len(del_tracks) > 0: # only when skipped frame exceeds max for id in del_tracks: if id < len(self.tracks): del self.tracks[id] del assignment[id] else: dprint("ERROR: id is greater than length of tracks") # Now look for un_assigned detects un_assigned_detects = [] for i in range(len(detections)): if i not in assignment: un_assigned_detects.append(i) # Start new tracks if (len(un_assigned_detects) != 0): for i in range(len(un_assigned_detects)): track = Track(detections[un_assigned_detects[i]], self.trackIdCount) self.trackIdCount += 1 self.tracks.append(track) # Update KalmanFilter state, lastResults and tracks trace for i in range(len(assignment)): print('before only prediction: ', self.tracks[i].KF.x) self.tracks[i].KF.predict(0.05) print('after only prediction: ', self.tracks[i].KF.x) if (assignment[i] != -1): self.tracks[i].skipped_frames = 0 self.tracks[i].KF.update([0], np.array([ detections[assignment[i]][0] ]), 1, [0.1]) self.tracks[i].KF.update([1], np.array([ detections[assignment[i]][1] ]), 1, [0.1]) self.tracks[i].prediction = self.tracks[i].KF.x #print("pre: ",self.tracks[i].prediction) #self.tracks[i].prediction[1]=self.tracks[i].KF.x[1]; else: print(self.tracks[i].KF.x) self.tracks[i].KF.update([0], np.array(np.array([0])), 0, [0.1]) self.tracks[i].KF.update([1], np.array(np.array([0])), 0, [0.1]) self.tracks[i].prediction = self.tracks[i].KF.x #self.tracks[i].prediction = self.tracks[i].KF.correct( # np.array([[0], [0]]), 0) #print('det :',np.array([[detections[assignment[i]][0]],[detections[assignment[i]][1]]])) print('i : ', assignment[i], 'updated prediction : ', self.tracks[i].prediction) if (len(self.tracks[i].trace) > self.max_trace_length): for j in range( len(self.tracks[i].trace) - self.max_trace_length): del self.tracks[i].trace[j] if self.tracks[i].prediction.shape[0] == 2: self.tracks[i].prediction = np.insert( self.tracks[i].prediction, self.tracks[i].prediction.shape[0], 0) self.tracks[i].prediction = np.insert( self.tracks[i].prediction, self.tracks[i].prediction.shape[0], 0) self.tracks[i].prediction = np.insert( self.tracks[i].prediction, self.tracks[i].prediction.shape[0], 0) self.tracks[i].prediction = np.insert( self.tracks[i].prediction, self.tracks[i].prediction.shape[0], 0) self.tracks[i].trace.append( np.reshape(self.tracks[i].prediction, (6, 1))) #print('cc : ',self.tracks[i].prediction.shape) self.tracks[i].KF.lastResult = self.tracks[i].prediction self.ls = assignment else: assignment = self.ls for i in range(len(assignment)): print('before only prediction: ', self.tracks[i].KF.x) self.tracks[i].KF.predict(0.08) print('after only prediction: ', self.tracks[i].KF.x) self.tracks[i].KF.update([0], np.array(np.array([0])), 0, [0.3]) self.tracks[i].KF.update([1], np.array(np.array([0])), 0, [0.3]) self.tracks[i].prediction = self.tracks[i].KF.x #self.tracks[i].prediction = self.tracks[i].KF.correct( # np.array([[0], [0]]), 0) #print('det :',np.array([[detections[assignment[i]][0]],[detections[assignment[i]][1]]])) print('i : ', assignment[i], 'updated prediction : ', self.tracks[i].prediction) if (len(self.tracks[i].trace) > self.max_trace_length): for j in range( len(self.tracks[i].trace) - self.max_trace_length): del self.tracks[i].trace[j] if self.tracks[i].prediction.shape[0] == 2: self.tracks[i].prediction = np.insert( self.tracks[i].prediction, self.tracks[i].prediction.shape[0], 0) self.tracks[i].prediction = np.insert( self.tracks[i].prediction, self.tracks[i].prediction.shape[0], 0) self.tracks[i].prediction = np.insert( self.tracks[i].prediction, self.tracks[i].prediction.shape[0], 0) self.tracks[i].prediction = np.insert( self.tracks[i].prediction, self.tracks[i].prediction.shape[0], 0) self.tracks[i].trace.append( np.reshape(self.tracks[i].prediction, (6, 1))) #print('cc : ',self.tracks[i].prediction.shape) self.tracks[i].KF.lastResult = self.tracks[i].prediction
def update(self, detection_centers, detection_imgs, MyHive): """Update tracks vector using following steps: - Create tracks if no tracks vector found - Calculate cost using sum of square distance between predicted vs detected centroids - Using Hungarian Algorithm assign the correct detected measurements to predicted tracks https://en.wikipedia.org/wiki/Hungarian_algorithm - Identify tracks with no assignment, if any - If tracks are not detected for long time, remove them - Now look for un_assigned detects - Start new tracks - Update KalmanFilter state, lastResults and tracks trace Args: detections: detected centroids of object to be tracked Return: None """ # Create tracks if no tracks vector found if (len(self.tracks) == 0): for i in range(len(detection_centers)): track = Track(detection_centers[i], detection_imgs[i], self.trackIdCount) self.trackIdCount += 1 self.tracks.append(track) # Calculate cost using sum of square distance between # predicted vs detected centroids N = len(self.tracks) M = len(detection_centers) cost = np.zeros(shape=(N, M)) # Cost matrix for i in range(len(self.tracks)): for j in range(len(detection_centers)): try: diff = self.tracks[i].prediction - detection_centers[j] distance = np.sqrt(diff[0][0] * diff[0][0] + diff[1][0] * diff[1][0]) cost[i][j] = distance except: pass # Let's average the squared ERROR cost = (0.5) * cost # Using Hungarian Algorithm assign the correct detected measurements # to predicted tracks assignment = [] for _ in range(N): assignment.append(-1) row_ind, col_ind = linear_sum_assignment(cost) for i in range(len(row_ind)): assignment[row_ind[i]] = col_ind[i] # Identify tracks with no assignment, if any un_assigned_tracks = [] for i in range(len(assignment)): if (assignment[i] != -1): # check for cost distance threshold. # If cost is very high then un_assign (delete) the track if (cost[i][assignment[i]] > self.dist_thresh): assignment[i] = -1 un_assigned_tracks.append(i) # NewBee=Bee(self.tracks[i].center_trace[0],self.tracks[i].img_trace[0]) # if len (self.tracks[i].center_trace)>1: # for j in range(len(self.tracks[i].center_trace)-1): # NewBee.add_capture (self.tracks[i].center_trace[j+1],self.tracks[i].img_trace[j+1]) #MyHive.add_bee(self.tracks[i].NewBee) #print ('bee '+str(self.tracks[i].track_id)+' via 1') pass else: self.tracks[i].skipped_frames += 1 # If tracks are not detected for long time, remove them del_tracks = [] for i in range(len(self.tracks)): if (self.tracks[i].skipped_frames > self.max_frames_to_skip): del_tracks.append(i) # NewBee=Bee(self.tracks[i].center_trace[0],self.tracks[i].img_trace[0]) # cv.imshow("bees", np.array(NewBee.frame)) # if len (self.tracks[i].center_trace)>1: # for j in range(len(self.tracks[i].center_trace)-1): # NewBee.add_capture (self.tracks[i].center_trace[j+1],self.tracks[i].img_trace[j+1]) if len(del_tracks) > 0: # only when skipped frame exceeds max for id in del_tracks: if id < len(self.tracks): MyHive.add_bee(self.tracks[id].NewBee) del self.tracks[id] del assignment[id] else: dprint("ERROR: id is greater than length of tracks") # Now look for un_assigned detects un_assigned_detects = [] for i in range(len(detection_centers)): if i not in assignment: un_assigned_detects.append(i) # Start new tracks if (len(un_assigned_detects) != 0): for i in range(len(un_assigned_detects)): track = Track(detection_centers[un_assigned_detects[i]], detection_imgs[un_assigned_detects[i]], self.trackIdCount) self.trackIdCount += 1 self.tracks.append(track) #print (self.trackIdCount) # Update KalmanFilter state, lastResults and tracks trace for i in range(len(assignment)): self.tracks[i].KF.predict() if (assignment[i] != -1): if self.tracks[i].first == 1: self.tracks[i].first = 0 else: self.tracks[i].NewBee.add_capture( detection_centers[assignment[i]], detection_imgs[assignment[i]]) self.tracks[i].skipped_frames = 0 self.tracks[i].prediction = self.tracks[i].KF.correct( detection_centers[assignment[i]], 1) else: self.tracks[i].prediction = self.tracks[i].KF.correct( np.array([[0], [0]]), 0) if (len(self.tracks[i].NewBee.center) > self.max_trace_length): for j in range( len(self.tracks[i].NewBee.center) - self.max_trace_length): del self.tracks[i].NewBee.center[j] self.tracks[i].KF.lastResult = self.tracks[i].prediction
def main(args): """ main function""" sys.excepthook = excepthook random_init() qname, qtype, qclass, csv = parse_args(args[1:]) try: qtype_val = qt.get_val(qtype) except KeyError: raise UsageError("ERROR: invalid query type: {}\n".format(qtype)) try: qclass_val = qc.get_val(qclass) except KeyError: raise UsageError("ERROR: invalid query class: {}\n".format(qclass)) if csv==0: query = DNSquery(qname, qtype_val, qclass_val) try: server_addr, port, family, _ = \ get_socketparams(options["server"], options["port"], options["af"], socket.SOCK_DGRAM) except socket.gaierror as e: raise ErrorMessage("bad server: %s (%s)" % (options["server"], e)) request = query.get_message() else: doc = pd.read_csv(qname) X = doc.iloc[:,0].values.astype(str) print(len(X)) for i in X: print(i) i += "." query = DNSquery(i, qtype_val, qclass_val) try: server_addr, port, family, _ = \ get_socketparams(options["server"], options["port"], options["af"], socket.SOCK_DGRAM) except socket.gaierror as e: raise ErrorMessage("bad server: %s (%s)" % (options["server"], e)) request = query.get_message() (responsepkt, responder_addr) = \ send_request_udp(request, server_addr, port, family, ITIMEOUT, RETRIES) response = DNSresponse(family, query, responsepkt) doc["get"] = str(response.decode_sections()) doc.to_csv(qname,index=False) response = None if not options["use_tcp"]: t1 = time.time() (responsepkt, responder_addr) = \ send_request_udp(request, server_addr, port, family, ITIMEOUT, RETRIES) t2 = time.time() if not responsepkt: raise ErrorMessage("No response from server") response = DNSresponse(family, query, responsepkt) if not response.tc: print(";; UDP response from %s, %d bytes, in %.3f sec" % (responder_addr, response.msglen, (t2-t1))) if not is_multicast(server_addr) and \ server_addr != "0.0.0.0" and responder_addr[0] != server_addr: print("WARNING: Response from unexpected address %s" % responder_addr[0]) if options["use_tcp"] or (response and response.tc) \ or (options["tls"] and options["tls_fallback"] and not response): if response and response.tc: if options["ignore"]: print(";; UDP Response was truncated.") else: print(";; UDP Response was truncated. Retrying using TCP ...") if options["tls"] and options["tls_fallback"] and not response: print(";; TLS fallback to TCP ...") if not options["ignore"]: t1 = time.time() responsepkt = send_request_tcp(request, server_addr, port, family) t2 = time.time() response = DNSresponse(family, query, responsepkt) print(";; TCP response from %s, %d bytes, in %.3f sec" % ((server_addr, port), response.msglen, (t2-t1))) response.print_all() dprint("Compression pointer dereferences=%d" % Stats.compression_cnt) return response.rcode
def Update(self, detections, old_gray, frame_gray): """Update tracks vector using following steps: - Create tracks if no tracks vector found - Calculate cost using sum of square distance between predicted vs detected centroids - Using Hungarian Algorithm assign the correct detected measurements to predicted tracks https://en.wikipedia.org/wiki/Hungarian_algorithm - Identify tracks with no assignment, if any - If tracks are not detected for long time, remove them - Now look for un_assigned detects - Start new tracks - Update KalmanFilter state, lastResults and tracks trace Args: detections: detected centroids of object to be tracked Return: None """ # Create tracks if no tracks vector found if (len(self.tracks) == 0): for i in range(len(detections)): track = Track(detections[i][0:2], self.trackIdCount) self.trackIdCount += 1 self.tracks.append(track) self.dimensions.append(detections[i][2:]) # Calculate cost using sum of square distance between # predicted vs detected centroids N = len(self.tracks) M = len(detections) cost = np.zeros(shape=(N, M)) # Cost matrix for i in range(len(self.tracks)): for j in range(len(detections)): diff = self.tracks[i].prediction - detections[j][0:2] distance = np.sqrt(diff[0] * diff[0] + diff[1] * diff[1]) cost[i][j] = distance # Let's average the squared ERROR cost = (0.5) * cost # Using Hungarian Algorithm assign the correct detected measurements # to predicted tracks assignment = [] for _ in range(N): assignment.append(-1) row_ind, col_ind = linear_sum_assignment(cost) for i in range(len(row_ind)): assignment[row_ind[i]] = col_ind[i] # Identify tracks with no assignment, if any un_assigned_tracks = [] for i in range(len(assignment)): if (assignment[i] != -1): # check for cost distance threshold. # If cost is very high then un_assign (delete) the track if (cost[i][assignment[i]] > self.dist_thresh): assignment[i] = -1 un_assigned_tracks.append(i) elif ((detections[assignment[i]][2] * detections[assignment[i]][3]) / (self.dimensions[i][0] * self.dimensions[i][1]) <= 2): self.tracks[i].trace[-1] = detections[assignment[i]][0:2] self.dimensions[i] = detections[assignment[i]][2:] #pass else: #self.tracks[i].trace[-1] = detections[assignment[i]][0:2] + np.random.randint(-1,1,(2,)) self.tracks[i].trace[-1] = detections[assignment[i]][0:2] self.dimensions[i] = detections[assignment[i]][2:] #pass else: ## LK self.tracks[i].skipped_frames += 1 # If tracks are not detected for long time, remove them del_tracks = [] for i in range(len(self.tracks)): if (self.tracks[i].skipped_frames > self.max_frames_to_skip): del_tracks.append(i) if len(del_tracks) > 0: # only when skipped frame exceeds max for id in del_tracks: if id < len(self.tracks): del self.tracks[id] del self.dimensions[id] del assignment[id] else: dprint("ERROR: id is greater than length of tracks") if (len(del_tracks)): print("del1") # Now look for un_assigned detects un_assigned_detects = [] for i in range(len(detections)): if i not in assignment: un_assigned_detects.append(i) # Start new tracks if (len(un_assigned_detects) != 0): for i in range(len(un_assigned_detects)): track = Track(detections[un_assigned_detects[i]][0:2], self.trackIdCount) self.trackIdCount += 1 self.tracks.append(track) self.dimensions.append(detections[un_assigned_detects[i]][2:]) # Update LK state and tracks trace p0 = [] for i in range(len(self.tracks)): p0.append(self.tracks[i].trace[-1]) p0 = np.array(p0).astype("float32") p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **self.lk_params) p1 = list(p1) #del_tracks = [] #for i in range(len(self.tracks)): # if (st[i] != 1): # del_tracks.append(i) #if len(del_tracks) > 0: # only when skipped frame exceeds max # for id in del_tracks: # if id < len(self.tracks): # del self.tracks[id] # del self.dimensions[id] # del assignment[id] # del p1[id] # else: # dprint("ERROR: id is greater than length of tracks") #if(len(del_tracks)): # print ("del2",len(del_tracks),len(self.tracks)) #print(len(self.tracks)) for i in range(len(self.tracks)): self.tracks[i].prediction = p1[i] self.tracks[i].trace.append(self.tracks[i].prediction)
def get_all_ids_and_creation_dates_incremental(args): """Fetches list of all ticket IDs and creation dates. This uses the /incremental API endpoint, and therefore also will return tickets that are "archived" or which have been set to a "deleted" status but are still accessible through the API. Ticket fields in JSON returned by API: * created_at * id * status = deleted|pending|new|solved|hold|closed|open ... Args: args (`dict`): The list of arguments received in the `_main function: * subdomain * username * password * auth_type Returns: List: List of 3-tuples (id, created_at, status) where "id" is an integer id for a ticket, "created_at" is a str representing the date that the ticket record was created in YYYY-MM-DD format, and "status" is a str representing the status of the ticket in Zendesk. """ url = get_list_all_tix_url(args['subdomain']) tickets = [] while url is not None: dprint(url) #search_req = urllib2.Request(url) #set_auth(search_req, args['username'], args['password'], # args['auth_type']) print "Fetching up to 1000 tickets from Zendesk..." #result = http.fetch_request(search_req) result = http.get_reponse(url=url, username=args['username'], password=args['password'], auth_type=args['auth_type'], is_delete=False, http_method=http.const.CURL) if result is not None: result_json = json.loads(result) if 'tickets' in result_json: dprint("Received %d tickets" % len(result_json['tickets'])) for ticket in result_json['tickets']: assert 'created_at' in ticket and 'id' in ticket ticket_id = int(ticket['id']) status = ticket['status'] matches = re.match(r'^(\d{4}-\d{2}-\d{2}).*$', ticket['created_at']) if matches is not None and len(matches.groups()) > 0: created_date = matches.group(1) tickets.append((ticket_id, created_date, status)) #print("DEBUG: Found ticket id %d created %s" % # (ticket_id, created_date)) else: sys.exit(("Could not find date in '%s' for ticket id " "%s") % (ticket['created_at'], ticket['id'])) if 'next_page' in result_json: url = result_json['next_page'] #if len(tickets) > 100: #DEBUG # url = None #DEBUG else: sys.exit("Expected the 'next_page' field in result " "returned from Zendesk API, but it was missing.") else: msg = "" try: msg = ( "Received unrecognized response from Zendesk API: %s" % str(result_json.read())) except AttributeError: msg = ( "Received unrecognized response from Zendesk API: %s" % str(result_json)) print msg print( "Exiting ticket collection process. Examine the error " "message above to determine whether tickets may have " "been missed.") return tickets else: #result was None, usually due to HTTP 422 "Too recent start_time. #Use a start_time older than 5 minutes" url = None if const.MAX_TICKETS is not None and len(tickets) >= const.MAX_TICKETS: break return tickets
def get_all_ids_and_creation_dates_search(args): """Fetches list of all ticket IDs and creation dates. This uses the /search API endpoint, and so will only return a limited subset of all tickets accessible through various other endpoints. Ticket fields in JSON returned by API: * created_at * id * status = deleted|pending|new|solved|hold|closed|open ... Returns: List of 3-tuples (ticket id, created at YYYY-MM-DD, status) """ url = get_search_url(args['subdomain'], args['days']) tickets = [] while url is not None: dprint(url) #get_reponse(url, username, password, auth_type, is_delete=False, # http_method=const.DEFAULT_HTTP_METHOD) #search_req = urllib2.Request(url) #set_auth(search_req, args['username'], args['password'], # args['auth_type']) print "Fetching tickets from Zendesk via /search..." result = None try: result = http.get_reponse(url=url, username=args['username'], password=args['password'], auth_type=args['auth_type'], is_delete=False, http_method=http.const.CURL) except http.MaxTriesExceededError: print( "WARNING! Maximum number of tries for fetching data was met. " "This may indicate that not all tickets will be returned.") return tickets if result is not None: result_json = json.loads(result) if 'results' in result_json: dprint("Retreived %d old tickets." % len(result_json['results'])) for ticket in result_json['results']: assert 'created_at' in ticket and 'id' in ticket ticket_id = int(ticket['id']) ticket_status = ticket['status'] matches = re.match(r'^(\d{4}-\d{2}-\d{2}).*$', ticket['created_at']) if matches is not None and len(matches.groups()) > 0: created_date = matches.group(1) tickets.append( (ticket_id, created_date, ticket_status)) dprint("Found ticket id %d created %s" % (ticket_id, created_date)) else: sys.exit(("Could not find date in '%s' for ticket id " "%s") % (ticket['created_at'], ticket['id'])) if 'next_page' in result_json: url = result_json['next_page'] else: sys.exit("Expected the 'next_page' field in result " "returned from Zendesk API, but it was missing.") else: sys.exit( "Received unrecognized response from Zendesk API: %s" % str(result_json.read())) if const.MAX_TICKETS is not None and len(tickets) >= const.MAX_TICKETS: break return tickets
def Update(self, detections): # Create tracks if no tracks vector found if (len(self.tracks) == 0): for i in range(len(detections)): track = Track(detections[i], self.trackIdCount) self.trackIdCount += 1 self.tracks.append(track) # Loss N = len(self.tracks) M = len(detections) cost = np.zeros(shape=(N, M)) # Cost matrix for i in range(len(self.tracks)): for j in range(len(detections)): try: diff = self.tracks[i].prediction - detections[j] distance = np.sqrt(diff[0][0] * diff[0][0] + diff[1][0] * diff[1][0]) cost[i][j] = distance except: pass cost = (0.5) * cost # Hungarian assignment = [] for _ in range(N): assignment.append(-1) col_ind = [] remove = [] row_ind = [] for i in range(cost.shape[0]): row_ind.append(i) min = 999999 for j in range(cost.shape[1]): if j not in remove: price = cost[i][j] if price < min: min = cost[i][j] index = j remove.append(index) col_ind.append(index) index = -1 #row_ind, col_ind = linear_sum_assignment(cost) for i in range(len(row_ind)): assignment[row_ind[i]] = col_ind[i] print(assignment) # Unassigned track un_assigned_tracks = [] for i in range(len(assignment)): if (assignment[i] != -1): # check for cost distance threshold. if (cost[i][assignment[i]] > self.dist_thresh): assignment[i] = -1 un_assigned_tracks.append(i) pass else: self.tracks[i].skipped_frames += 1 # If tracks are not detected for long time, remove them del_tracks = [] for i in range(len(self.tracks)): if (self.tracks[i].skipped_frames > self.max_frames_to_skip): del_tracks.append(i) if len(del_tracks) > 0: # only when skipped frame exceeds max for id in del_tracks: if id < len(self.tracks): del self.tracks[id] del assignment[id] else: dprint("ERROR: id is greater than length of tracks") # Now look for un_assigned detects un_assigned_detects = [] for i in range(len(detections)): if i not in assignment: un_assigned_detects.append(i) # Start new tracks if (len(un_assigned_detects) != 0): for i in range(len(un_assigned_detects)): track = Track(detections[un_assigned_detects[i]], self.trackIdCount) self.trackIdCount += 1 self.tracks.append(track) # Update KalmanFilter state, lastResults and tracks trace for i in range(len(assignment)): self.tracks[i].KF.predict() if (assignment[i] != -1): self.tracks[i].skipped_frames = 0 self.tracks[i].prediction = self.tracks[i].KF.update( detections[assignment[i]], 1) else: self.tracks[i].prediction = self.tracks[i].KF.update( np.array([[0], [0]]), 0) if (len(self.tracks[i].trace) > self.max_trace_length): for j in range( len(self.tracks[i].trace) - self.max_trace_length): del self.tracks[i].trace[j] self.tracks[i].trace.append(self.tracks[i].prediction) self.tracks[i].KF.lastResult = self.tracks[i].prediction
def Update(self, detections,fnum): """Update tracks vector using following steps: - Create tracks if no tracks vector found - Calculate cost using sum of square distance between predicted vs detected centroids - Using Hungarian Algorithm assign the correct detected measurements to predicted tracks https://en.wikipedia.org/wiki/Hungarian_algorithm - Identify tracks with no assignment, if any - If tracks are not detected for long time, remove them - Now look for un_assigned detects - Start new tracks - Update KalmanFilter state, lastResults and tracks trace Args: detections: detected centroids of object to be tracked Return: None """ # print ('here is detection', detections) # Create tracks if no tracks vector found if (len(self.tracks) == 0): for i in range(len(detections)): track = Track(detections[i], self.trackIdCount) self.trackIdCount += 1 self.originalfnum = fnum self.tracks.append(track) # Calculate cost using sum of square distance between # predicted vs detected centroids N = len(self.tracks) M = len(detections) cost = np.zeros(shape=(N, M)) # Cost matrix for i in range(len(self.tracks)): for j in range(len(detections)): try: diff = self.tracks[i].prediction - detections[j] # print ('predition',self.tracks[i].prediction, 'detection',detections[j]) # print ('difference=', diff) distance = np.sqrt(diff[0][0]*diff[0][0] + diff[1][0]*diff[1][0]) # print ('distance=', distance) # if distance > 100: # cost[i][j] = 1000 # else: cost[i][j] = distance except: pass # Let's average the squared ERROR # print ('cost before', cost) # cost = (0.5) * cost # print ('cost after', cost) # Using Hungarian Algorithm assign the correct detected measurements # to predicted tracks for wi in range(N): for wj in range(M): if cost[wi][wj]> 120: #sensetive cost[wi][wj]= 120 # assignment = [] for _ in range(N): assignment.append(-1) row_ind, col_ind = linear_sum_assignment(cost) for i in range(len(row_ind)): assignment[row_ind[i]] = col_ind[i] # Identify tracks with no assignment, if any un_assigned_tracks = [] for i in range(len(assignment)): if (assignment[i] != -1): # print ('cost=',cost[i][assignment[i]],'assignment=',assignment[i]) print ('predition',self.tracks[i].prediction, 'detection',detections[assignment[i]]) # check for cost distance threshold. # If cost is very high then un_assign (delete) the track if (cost[i][assignment[i]] > self.dist_thresh): assignment[i] = -1 un_assigned_tracks.append(i) pass else: self.tracks[i].skipped_frames += 1 # If tracks are not detected for long time, remove them del_tracks = [] for i in range(len(self.tracks)): # oframe = self.tracks[i].originalfnum # skframe= self.tracks[i].skipped_frames if (self.tracks[i].skipped_frames > self.max_frames_to_skip) or (fnum-self.tracks[i].originalfnum)>8: # CHECK IT!!! del_tracks.append(i) if len(del_tracks) > 0: # only when skipped frame exceeds max for id in del_tracks: if id < len(self.tracks): del self.tracks[id] del assignment[id] else: dprint("ERROR: id is greater than length of tracks") # Now look for un_assigned detects un_assigned_detects = [] for i in range(len(detections)): if i not in assignment: un_assigned_detects.append(i) # Start new tracks if(len(un_assigned_detects) != 0): for i in range(len(un_assigned_detects)): track = Track(detections[un_assigned_detects[i]], self.trackIdCount) self.trackIdCount += 1 self.tracks.append(track) tracklength = len(self.tracks) self.tracks[tracklength-1].originalfnum = fnum # Update KalmanFilter state, lastResults and tracks trace print ('assignment list', assignment) for i in range(len(assignment)): if len(self.tracks[i].trace) < 2: iit = len(self.tracks[i].trace) bbt = detections[assignment[i]] else: if assignment[i] == -1: iit = 0 bbt = self.tracks[i].prediction else: iit = len(self.tracks[i].trace) bbt = self.tracks[i].prediction self.tracks[i].KF.predict(iit, bbt) if(assignment[i] != -1): self.tracks[i].skipped_frames = 0 predictionp = self.tracks[i].prediction self.tracks[i].prediction = self.tracks[i].KF.correct( detections[assignment[i]], 1, 0) else: predictionp = self.tracks[i].prediction self.tracks[i].prediction = self.tracks[i].KF.correct( np.array([[0], [0]]), 0, 1) if(len(self.tracks[i].trace) > self.max_trace_length): for j in range(len(self.tracks[i].trace) - self.max_trace_length): del self.tracks[i].trace[j] # diffp = self.tracks[i].prediction - predictionp # distancep = np.sqrt(diffp[0][0]*diffp[0][0] + diffp[1][0]*diffp[1][0]) # # if distancep > 50: # print ('pb',self.tracks[i].prediction) # self.tracks[i].prediction = predictionp - [0,6] # print('id',self.tracks[i].track_id) # print('p',self.tracks[i].prediction,'pp',predictionp) self.tracks[i].framenum.append(fnum) self.tracks[i].trace.append(self.tracks[i].prediction) self.tracks[i].KF.lastResult = self.tracks[i].prediction self.tracks[i].originalfnum = fnum # print ('new x y', int(detections[assignment[i]][0]),int(detections[assignment[i]][1])) self.tracks[i].detectedx.append(int(detections[assignment[i]][0])) self.tracks[i].detectedy.append(int(detections[assignment[i]][1]))
def Update(self, detections): # Create tracks if no tracks vector found if (len(self.tracks) == 0): for i in range(len(detections)): track = Track(detections[i], self.trackIdCount) self.trackIdCount += 1 self.tracks.append(track) # tracks: object of Tracker # Calculate cost using sum of square distance between predicted vs detected centroids N = len(self.tracks) M = len(detections) cost = np.zeros(shape=(N, M)) # Cost matrix for i in range(len(self.tracks)): for j in range(len(detections)): try: diff = self.tracks[i].prediction - detections[j] distance = np.sqrt(diff[0][0]*diff[0][0] +diff[1][0]*diff[1][0]) # diff[0][0] -> x of diff, diff[1][0] -> y of diff cost[i][j] = distance except: pass # Let's average the squared ERROR cost = (0.5) * cost # Using Hungarian Algorithm assign the correct detected measurements to predicted tracks assignment = [] for _ in range(N): assignment.append(-1) row_ind, col_ind = linear_sum_assignment(cost) for i in range(len(row_ind)): assignment[row_ind[i]] = col_ind[i] # Identify tracks with no assignment, if any un_assigned_tracks = [] for i in range(len(assignment)): if (assignment[i] != -1): print(cost[i][assignment[i]],i) # check for cost distance threshold. # If cost is very high then un_assign (delete) the track if (cost[i][assignment[i]] > self.dist_thresh): assignment[i] = -1 un_assigned_tracks.append(i) pass else: self.tracks[i].skipped_frames += 1 # If tracks are not detected for long time, remove them del_tracks = [] for i in range(len(self.tracks)): if (self.tracks[i].skipped_frames > self.max_frames_to_skip): del_tracks.append(i) if len(del_tracks) > 0: # only when skipped frame exceeds max for id in del_tracks: if id < len(self.tracks): del self.tracks[id] del assignment[id] else: dprint("ERROR: id is greater than length of tracks") # Now look for un_assigned detects un_assigned_detects = [] for i in range(len(detections)): if i not in assignment: un_assigned_detects.append(i) # Start new tracks if(len(un_assigned_detects) != 0): for i in range(len(un_assigned_detects)): track = Track(detections[un_assigned_detects[i]],self.trackIdCount) self.trackIdCount += 1 self.tracks.append(track) # Update KalmanFilter state, lastResults and tracks trace for i in range(len(assignment)): self.tracks[i].KF.predict() if(assignment[i] != -1): self.tracks[i].skipped_frames = 0 self.tracks[i].prediction = self.tracks[i].KF.correct(detections[assignment[i]], 1) else: self.tracks[i].prediction = self.tracks[i].KF.correct(np.array([[0], [0]]), 0) if(len(self.tracks[i].trace) > self.max_trace_length): for j in range(len(self.tracks[i].trace) -self.max_trace_length): del self.tracks[i].trace[j] self.tracks[i].trace.append(self.tracks[i].prediction) self.tracks[i].KF.lastResult = self.tracks[i].prediction
def Update(self, detections): """Update tracks vector using following steps: 使用以下步骤更新跟踪向量 - Create tracks if no tracks vector found 创建跟踪器,如果没有找到跟踪器载体 - Calculate cost using sum of square distance between predicted vs detected centroids 利用预测的质心与检测到的质心之间的平方和计算成本 - Using Hungarian Algorithm assign the correct detected measurements to predicted tracks 使用匈牙利算法将正确的检测值分配给预测轨迹 https://en.wikipedia.org/wiki/Hungarian_algorithm - Identify tracks with no assignment, if any 识别没有任务的轨迹,如果有的话 - If tracks are not detected for long time, remove them 如果长时间没有检测到跟踪,请删除它们 - Now look for un_assigned detects 现在查找没有分配的检测 - Start new tracks 开始新的跟踪 - Update KalmanFilter state, lastResults and tracks trace 更新卡尔曼滤波器的状态,最后的结果和跟踪器的轨迹 Args: detections: detected centroids of object to be tracked 检测到要跟踪的对象的质心 Return: None """ # Create tracks if no tracks vector found # 创建跟踪器,如果没有找到跟踪器载体 if (len(self.tracks) == 0): for i in range(len(detections)): track = Track(detections[i], self.trackIdCount) self.trackIdCount += 1 self.tracks.append(track) # Calculate cost using sum of square distance between predicted vs detected centroids # 利用预测的质心与检测到的质心之间的平方和计算成本 N = len(self.tracks) M = len(detections) cost = np.zeros(shape=(N, M)) # Cost matrix 成本矩阵 for i in range(len(self.tracks)): for j in range(len(detections)): try: diff = self.tracks[i].prediction - detections[j] distance = np.sqrt(diff[0][0] * diff[0][0] + diff[1][0] * diff[1][0]) cost[i][j] = distance except: pass # Let's average the squared ERROR 求平方误差的平均值 cost = (0.5) * cost # Using Hungarian Algorithm assign the correct detected measurements to predicted tracks # 使用匈牙利算法将正确的检测值分配给预测轨迹 assignment = [] for _ in range(N): assignment.append(-1) row_ind, col_ind = linear_sum_assignment(cost) for i in range(len(row_ind)): assignment[row_ind[i]] = col_ind[i] # Identify tracks with no assignment, if any # 识别没有分配的轨迹,如果有的话 un_assigned_tracks = [] for i in range(len(assignment)): if (assignment[i] != -1): # check for cost distance threshold. # 检查成本距离阈值 # If cost is very high then un_assign (delete) the track # 如果成本非常高,那么不分配(删除)轨迹 if (cost[i][assignment[i]] > self.dist_thresh): assignment[i] = -1 un_assigned_tracks.append(i) pass else: self.tracks[i].skipped_frames += 1 # If tracks are not detected for long time, remove them # 如果长时间没有检测到跟踪,请删除它们 del_tracks = [] for i in range(len(self.tracks)): if (self.tracks[i].skipped_frames > self.max_frames_to_skip): del_tracks.append(i) if len(del_tracks ) > 0: # only when skipped frame exceeds max 只有当跳过的帧超过最大 for id in del_tracks: if id < len(self.tracks): del self.tracks[id] del assignment[id] else: dprint("ERROR: id is greater than length of tracks") # Now look for un_assigned detects # 现在查找没有分配的检测 un_assigned_detects = [] for i in range(len(detections)): if i not in assignment: un_assigned_detects.append(i) # Start new tracks if (len(un_assigned_detects) != 0): for i in range(len(un_assigned_detects)): track = Track(detections[un_assigned_detects[i]], self.trackIdCount) self.trackIdCount += 1 self.tracks.append(track) # Update KalmanFilter state, lastResults and tracks trace for i in range(len(assignment)): self.tracks[i].KF.predict() if (assignment[i] != -1): self.tracks[i].skipped_frames = 0 self.tracks[i].prediction = self.tracks[i].KF.correct( detections[assignment[i]], 1) else: self.tracks[i].prediction = self.tracks[i].KF.correct( np.array([[0], [0]]), 0) if (len(self.tracks[i].trace) > self.max_trace_length): for j in range( len(self.tracks[i].trace) - self.max_trace_length): del self.tracks[i].trace[j] self.tracks[i].trace.append(self.tracks[i].prediction) self.tracks[i].KF.lastResult = self.tracks[i].prediction
def Update(self, detections): """Update tracks vector using following steps: - Create tracks if no tracks vector found - Calculate cost using sum of square distance between predicted vs detected centroids - Using Hungarian Algorithm assign the correct detected measurements to predicted tracks https://en.wikipedia.org/wiki/Hungarian_algorithm - Identify tracks with no assignment, if any - If tracks are not detected for long time, remove them - Now look for un_assigned detects - Start new tracks - Update KalmanFilter state, lastResults and tracks trace Args: detections: detected centroids of object to be tracked Return: None """ # Create tracks if no tracks vector found if (len(self.tracks) == 0): for i in range(len(detections)): track = Track(detections[i], self.trackIdCount) self.trackIdCount += 1 self.tracks.append(track) # Calculate cost using sum of square distance between # predicted vs detected centroids N = len(self.tracks) M = len(detections) cost = np.zeros(shape=(N, M)) # Cost matrix for i in range(len(self.tracks)): for j in range(len(detections)): try: diff = self.tracks[i].prediction - detections[j] distance = np.sqrt(diff[0][0]*diff[0][0] + diff[1][0]*diff[1][0]) cost[i][j] = distance except: pass # Let's average the squared ERROR cost = (0.5) * cost # Using Hungarian Algorithm assign the correct detected measurements # to predicted tracks assignment = [] for _ in range(N): assignment.append(-1) row_ind, col_ind = linear_sum_assignment(cost) for i in range(len(row_ind)): assignment[row_ind[i]] = col_ind[i] # Identify tracks with no assignment, if any un_assigned_tracks = [] for i in range(len(assignment)): if (assignment[i] != -1): # check for cost distance threshold. # If cost is very high then un_assign (delete) the track if (cost[i][assignment[i]] > self.dist_thresh): assignment[i] = -1 un_assigned_tracks.append(i) pass else: self.tracks[i].skipped_frames += 1 # If tracks are not detected for long time, remove them del_tracks = [] for i in range(len(self.tracks)): if (self.tracks[i].skipped_frames > self.max_frames_to_skip): del_tracks.append(i) if len(del_tracks) > 0: # only when skipped frame exceeds max for id in del_tracks: if id < len(self.tracks): del self.tracks[id] del assignment[id] else: dprint("ERROR: id is greater than length of tracks") # Now look for un_assigned detects un_assigned_detects = [] for i in range(len(detections)): if i not in assignment: un_assigned_detects.append(i) # Start new tracks if(len(un_assigned_detects) != 0): for i in range(len(un_assigned_detects)): track = Track(detections[un_assigned_detects[i]], self.trackIdCount) self.trackIdCount += 1 self.tracks.append(track) # Update KalmanFilter state, lastResults and tracks trace for i in range(len(assignment)): self.tracks[i].KF.predict() if(assignment[i] != -1): self.tracks[i].skipped_frames = 0 self.tracks[i].prediction = self.tracks[i].KF.correct( detections[assignment[i]], 1) else: self.tracks[i].prediction = self.tracks[i].KF.correct( np.array([[0], [0]]), 0) if(len(self.tracks[i].trace) > self.max_trace_length): for j in range(len(self.tracks[i].trace) - self.max_trace_length): del self.tracks[i].trace[j] self.tracks[i].trace.append(self.tracks[i].prediction) self.tracks[i].KF.lastResult = self.tracks[i].prediction