fork download
  1. import math
  2.  
  3. class EuclideanDistTracker:
  4. def __init__(self):
  5. # Store the center positions of the objects
  6. self.center_points = {}
  7. # Keep the count of the IDs
  8. # each time a new object id detected, the count will increase by one
  9. self.id_count = 0
  10.  
  11.  
  12. def update(self, objects_rect):
  13. # Objects boxes and ids
  14. objects_bbs_ids = []
  15.  
  16. # Get center point of new object
  17. for rect in objects_rect:
  18. x, y, w, h = rect
  19. cx = (x + x + w) // 2
  20. cy = (y + y + h) // 2
  21.  
  22. # Find out if that object was detected already
  23. same_object_detected = False
  24. for id, pt in self.center_points.items():
  25. dist = math.hypot(cx - pt[0], cy - pt[1])
  26.  
  27. if dist < 20: # Threshold
  28. self.center_points[id] = (cx, cy)
  29. print(self.center_points)
  30. objects_bbs_ids.append([x, y, w, h, id])
  31. same_object_detected = True
  32. break
  33.  
  34. # New object is detected we assign the ID to that object
  35. if same_object_detected is False:
  36. self.center_points[self.id_count] = (cx, cy)
  37. objects_bbs_ids.append([x, y, w, h, self.id_count])
  38. self.id_count += 1
  39.  
  40. # Clean the dictionary by center points to remove IDS not used anymore
  41. new_center_points = {}
  42. for obj_bb_id in objects_bbs_ids:
  43. _, _, _, _, object_id = obj_bb_id
  44. center = self.center_points[object_id]
  45. new_center_points[object_id] = center
  46.  
  47. # Update dictionary with IDs not used removed
  48. self.center_points = new_center_points.copy()
  49. return objects_bbs_ids
Success #stdin #stdout 0.02s 9160KB
stdin
Standard input is empty
stdout
Standard output is empty