person_jump_check.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. from ultralytics.solutions.solutions import BaseSolution
  3. from ultralytics.utils.plotting import Annotator, colors
  4. from shapely.geometry import Point
  5. class PersonJump(BaseSolution):
  6. """
  7. A class to manage the counting of objects in a real-time video stream based on their tracks.
  8. This class extends the BaseSolution class and provides functionality for counting objects moving in and out of a
  9. specified region in a video stream. It supports both polygonal and linear regions for counting.
  10. Attributes:
  11. in_count (int): Counter for objects moving inward.
  12. out_count (int): Counter for objects moving outward.
  13. counted_ids (List[int]): List of IDs of objects that have been counted.
  14. classwise_counts (Dict[str, Dict[str, int]]): Dictionary for counts, categorized by object class.
  15. region_initialized (bool): Flag indicating whether the counting region has been initialized.
  16. show_in (bool): Flag to control display of inward count.
  17. show_out (bool): Flag to control display of outward count.
  18. Methods:
  19. count_objects: Counts objects within a polygonal or linear region.
  20. store_classwise_counts: Initializes class-wise counts if not already present.
  21. display_counts: Displays object counts on the frame.
  22. count: Processes input data (frames or object tracks) and updates counts.
  23. Examples:
  24. >>> counter = ObjectCounter()
  25. >>> frame = cv2.imread("frame.jpg")
  26. >>> processed_frame = counter.count(frame)
  27. >>> print(f"Inward count: {counter.in_count}, Outward count: {counter.out_count}")
  28. """
  29. def __init__(self, **kwargs):
  30. """Initializes the ObjectCounter class for real-time object counting in video streams."""
  31. super().__init__(**kwargs)
  32. self.in_count = 0 # Counter for objects moving inward
  33. self.out_count = 0 # Counter for objects moving outward
  34. self.counted_ids = [] # List of IDs of objects that have been counted
  35. self.classwise_counts = {} # Dictionary for counts, categorized by object class
  36. self.region_initialized = False # Bool variable for region initialization
  37. self.show_in = self.CFG["show_in"]
  38. self.show_out = self.CFG["show_out"]
  39. def count_objects(self, track_line, box, track_id, prev_position, cls):
  40. """
  41. Counts objects within a polygonal or linear region based on their tracks.
  42. Args:
  43. track_line (Dict): Last 30 frame track record for the object.
  44. box (List[float]): Bounding box coordinates [x1, y1, x2, y2] for the specific track in the current frame.
  45. track_id (int): Unique identifier for the tracked object.
  46. prev_position (Tuple[float, float]): Last frame position coordinates (x, y) of the track.
  47. cls (int): Class index for classwise count updates.
  48. Examples:
  49. >>> counter = ObjectCounter()
  50. >>> track_line = {1: [100, 200], 2: [110, 210], 3: [120, 220]}
  51. >>> box = [130, 230, 150, 250]
  52. >>> track_id = 1
  53. >>> prev_position = (120, 220)
  54. >>> cls = 0
  55. >>> counter.count_objects(track_line, box, track_id, prev_position, cls)
  56. """
  57. if prev_position is None or track_id in self.counted_ids:
  58. return
  59. # centroid = self.r_s.centroid
  60. if len(self.region) >= 3 and self.r_s.contains(Point(track_line[-1])):
  61. self.counted_ids.append(track_id)
  62. dy = track_line[-1][1] - prev_position[1]
  63. if dy > 0:
  64. self.in_count += 1
  65. def store_classwise_counts(self, cls):
  66. """
  67. Initialize class-wise counts for a specific object class if not already present.
  68. Args:
  69. cls (int): Class index for classwise count updates.
  70. This method ensures that the 'classwise_counts' dictionary contains an entry for the specified class,
  71. initializing 'IN' and 'OUT' counts to zero if the class is not already present.
  72. Examples:
  73. >>> counter = ObjectCounter()
  74. >>> counter.store_classwise_counts(0) # Initialize counts for class index 0
  75. >>> print(counter.classwise_counts)
  76. {'person': {'IN': 0, 'OUT': 0}}
  77. """
  78. if self.names[cls] not in self.classwise_counts:
  79. self.classwise_counts[self.names[cls]] = {"IN": 0, "OUT": 0}
  80. def display_counts(self, im0):
  81. """
  82. Displays object counts on the input image or frame.
  83. Args:
  84. im0 (numpy.ndarray): The input image or frame to display counts on.
  85. Examples:
  86. >>> counter = ObjectCounter()
  87. >>> frame = cv2.imread("image.jpg")
  88. >>> counter.display_counts(frame)
  89. """
  90. labels_dict = {
  91. str.capitalize(key): f"{'IN ' + str(value['IN']) if self.show_in else ''} "
  92. f"{'OUT ' + str(value['OUT']) if self.show_out else ''}".strip()
  93. for key, value in self.classwise_counts.items()
  94. if value["IN"] != 0 or value["OUT"] != 0
  95. }
  96. if labels_dict:
  97. self.annotator.display_analytics(im0, labels_dict, (104, 31, 17), (255, 255, 255), 10)
  98. def count(self, im0):
  99. """
  100. Processes input data (frames or object tracks) and updates object counts.
  101. This method initializes the counting region, extracts tracks, draws bounding boxes and regions, updates
  102. object counts, and displays the results on the input image.
  103. Args:
  104. im0 (numpy.ndarray): The input image or frame to be processed.
  105. Returns:
  106. (numpy.ndarray): The processed image with annotations and count information.
  107. Examples:
  108. >>> counter = ObjectCounter()
  109. >>> frame = cv2.imread("path/to/image.jpg")
  110. >>> processed_frame = counter.count(frame)
  111. """
  112. if not self.region_initialized:
  113. self.initialize_region()
  114. self.region_initialized = True
  115. self.annotator = Annotator(im0, line_width=self.line_width) # Initialize annotator
  116. self.extract_tracks(im0) # Extract tracks
  117. self.annotator.draw_region(
  118. reg_pts=self.region, color=(104, 0, 123), thickness=self.line_width * 2
  119. ) # Draw region
  120. # Iterate over bounding boxes, track ids and classes index
  121. for box, track_id, cls in zip(self.boxes, self.track_ids, self.clss):
  122. # Draw bounding box and counting region
  123. self.annotator.box_label(box, label=self.names[cls], color=colors(cls, True))
  124. self.store_tracking_history(track_id, box) # Store track history
  125. self.store_classwise_counts(cls) # store classwise counts in dict
  126. # Draw tracks of objects
  127. self.annotator.draw_centroid_and_tracks(
  128. self.track_line, color=colors(int(cls), True), track_thickness=self.line_width
  129. )
  130. # store previous position of track for object counting
  131. prev_position = None
  132. if len(self.track_history[track_id]) > 1:
  133. prev_position = self.track_history[track_id][-2]
  134. self.count_objects(self.track_line, box, track_id, prev_position, cls) # Perform object counting
  135. # self.display_counts(im0) # Display the counts on the frame
  136. self.display_output(im0) # display output with base class function
  137. return im0 # return output image for more usage