trackzone.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. import cv2
  3. import numpy as np
  4. from ultralytics.solutions.solutions import BaseSolution
  5. from ultralytics.utils.plotting import Annotator, colors
  6. class TrackZone(BaseSolution):
  7. """
  8. A class to manage region-based object tracking in a video stream.
  9. This class extends the BaseSolution class and provides functionality for tracking objects within a specific region
  10. defined by a polygonal area. Objects outside the region are excluded from tracking. It supports dynamic initialization
  11. of the region, allowing either a default region or a user-specified polygon.
  12. Attributes:
  13. region (ndarray): The polygonal region for tracking, represented as a convex hull.
  14. Methods:
  15. trackzone: Processes each frame of the video, applying region-based tracking.
  16. Examples:
  17. >>> tracker = TrackZone()
  18. >>> frame = cv2.imread("frame.jpg")
  19. >>> processed_frame = tracker.trackzone(frame)
  20. >>> cv2.imshow("Tracked Frame", processed_frame)
  21. """
  22. def __init__(self, **kwargs):
  23. """Initializes the TrackZone class for tracking objects within a defined region in video streams."""
  24. super().__init__(**kwargs)
  25. default_region = [(150, 150), (1130, 150), (1130, 570), (150, 570)]
  26. self.region = cv2.convexHull(np.array(self.region or default_region, dtype=np.int32))
  27. def trackzone(self, im0):
  28. """
  29. Processes the input frame to track objects within a defined region.
  30. This method initializes the annotator, creates a mask for the specified region, extracts tracks
  31. only from the masked area, and updates tracking information. Objects outside the region are ignored.
  32. Args:
  33. im0 (numpy.ndarray): The input image or frame to be processed.
  34. Returns:
  35. (numpy.ndarray): The processed image with tracking id and bounding boxes annotations.
  36. Examples:
  37. >>> tracker = TrackZone()
  38. >>> frame = cv2.imread("path/to/image.jpg")
  39. >>> tracker.trackzone(frame)
  40. """
  41. self.annotator = Annotator(im0, line_width=self.line_width) # Initialize annotator
  42. # Create a mask for the region and extract tracks from the masked image
  43. masked_frame = cv2.bitwise_and(im0, im0, mask=cv2.fillPoly(np.zeros_like(im0[:, :, 0]), [self.region], 255))
  44. self.extract_tracks(masked_frame)
  45. cv2.polylines(im0, [self.region], isClosed=True, color=(255, 255, 255), thickness=self.line_width * 2)
  46. # Iterate over boxes, track ids, classes indexes list and draw bounding boxes
  47. for box, track_id, cls in zip(self.boxes, self.track_ids, self.clss):
  48. self.annotator.box_label(box, label=f"{self.names[cls]}:{track_id}", color=colors(track_id, True))
  49. self.display_output(im0) # display output with base class function
  50. return im0 # return output image for more usage