+
+
+
+
+
+
+
+## 📄 Documentation
+
+See below for quickstart installation and usage examples. For comprehensive guidance on training, validation, prediction, and deployment, refer to our full [Ultralytics Docs](https://docs.ultralytics.com/).
+
+
+
+
+
+
+## 🤝 Contribute
+
+We thrive on community collaboration! Ultralytics YOLO wouldn't be the SOTA framework it is without contributions from developers like you. Please see our [Contributing Guide](https://docs.ultralytics.com/help/contributing) to get started. We also welcome your feedback—share your experience by completing our [Survey](https://www.ultralytics.com/survey?utm_source=github&utm_medium=social&utm_campaign=Survey). A huge **Thank You** 🙏 to everyone who contributes!
+
+
+
+[](https://github.com/ultralytics/ultralytics/graphs/contributors)
+
+We look forward to your contributions to help make the Ultralytics ecosystem even better!
+
+## 📜 License
+
+Ultralytics offers two licensing options to suit different needs:
+
+- **AGPL-3.0 License**: This [OSI-approved](https://opensource.org/license/agpl-3.0) open-source license is perfect for students, researchers, and enthusiasts. It encourages open collaboration and knowledge sharing. See the [LICENSE](https://github.com/ultralytics/ultralytics/blob/main/LICENSE) file for full details.
+- **Ultralytics Enterprise License**: For development and production use, this license enables seamless integration of Ultralytics software and AI models into business products and services, including internal tools, automated workflows, and production deployments, bypassing the open-source requirements of AGPL-3.0. To get started, please contact us via [Ultralytics Licensing](https://www.ultralytics.com/license).
+
+## 📞 Contact
+
+For bug reports and feature requests related to Ultralytics software, please visit [GitHub Issues](https://github.com/ultralytics/ultralytics/issues). For questions, discussions, and community support, join our active communities on [Discord](https://discord.com/invite/ultralytics), [Reddit](https://www.reddit.com/r/ultralytics/), and the [Ultralytics Community Forums](https://community.ultralytics.com/). We're here to help with all things Ultralytics!
+
+
+
+
+
+
+
+
+
+## 📄 文档
+
+请参阅下文了解快速安装和使用示例。有关训练、验证、预测和部署的全面指南,请参阅我们的完整 [Ultralytics 文档](https://docs.ultralytics.com/)。
+
+
+
+
+
+
+## 🤝 贡献
+
+我们依靠社区协作蓬勃发展!没有像您这样的开发者的贡献,Ultralytics YOLO 就不会成为如今最先进的框架。请参阅我们的[贡献指南](https://docs.ultralytics.com/help/contributing)开始贡献。我们也欢迎您的反馈——通过完成我们的[调查问卷](https://www.ultralytics.com/survey?utm_source=github&utm_medium=social&utm_campaign=Survey)分享您的体验。非常**感谢** 🙏 每一位贡献者!
+
+
+
+[](https://github.com/ultralytics/ultralytics/graphs/contributors)
+
+我们期待您的贡献,帮助 Ultralytics 生态系统变得更好!
+
+## 📜 许可证
+
+Ultralytics 提供两种许可选项以满足不同需求:
+
+- **AGPL-3.0 许可证**:这种经 [OSI 批准](https://opensource.org/license/agpl-3.0)的开源许可证非常适合学生、研究人员和爱好者。它鼓励开放协作和知识共享。有关完整详细信息,请参阅 [LICENSE](https://github.com/ultralytics/ultralytics/blob/main/LICENSE) 文件。
+- **Ultralytics 企业许可证**:适用于开发和生产用途,此许可证允许将 Ultralytics 软件和 AI 模型无缝集成到业务产品和服务中,包括内部工具、自动化工作流和生产部署,绕过 AGPL-3.0 的开源要求。如需开始使用,请通过 [Ultralytics 授权许可](https://www.ultralytics.com/license)与我们联系。
+
+## 📞 联系方式
+
+有关 Ultralytics 软件的错误报告和功能请求,请访问 [GitHub Issues](https://github.com/ultralytics/ultralytics/issues)。如有疑问、讨论和社区支持,请加入我们在 [Discord](https://discord.com/invite/ultralytics)、[Reddit](https://www.reddit.com/r/ultralytics/) 和 [Ultralytics 社区论坛](https://community.ultralytics.com/)上的活跃社区。我们随时为您提供有关 Ultralytics 的所有帮助!
+
+
+
+[Object tracking](https://www.ultralytics.com/glossary/object-tracking), a key aspect of [video analytics](https://en.wikipedia.org/wiki/Video_content_analysis), involves identifying the location and class of objects within video frames and assigning a unique ID to each detected object as it moves. This capability enables a wide range of applications, from surveillance and security systems to [real-time](https://www.ultralytics.com/glossary/real-time-inference) sports analysis and autonomous vehicle navigation. Learn more about tracking on our [tracking documentation page](https://docs.ultralytics.com/modes/track).
+
+## 🎯 Why Choose Ultralytics YOLO for Object Tracking?
+
+Ultralytics YOLO trackers provide output consistent with standard [object detection](https://docs.ultralytics.com/tasks/detect) but add persistent object IDs. This simplifies the process of tracking objects in video streams and performing subsequent analyses. Here’s why Ultralytics YOLO is an excellent choice for your object tracking needs:
+
+- **Efficiency:** Process video streams in real-time without sacrificing accuracy.
+- **Flexibility:** Supports multiple robust tracking algorithms and configurations.
+- **Ease of Use:** Offers straightforward [Python API](https://docs.ultralytics.com/usage/python) and [CLI](https://docs.ultralytics.com/usage/cli) options for rapid integration and deployment.
+- **Customizability:** Easily integrates with [custom-trained YOLO models](https://docs.ultralytics.com/modes/train), enabling deployment in specialized, domain-specific applications.
+
+**Watch:** Object Detection and Tracking with Ultralytics YOLO26.
+
+[](https://www.youtube.com/watch?v=hHyHmOtmEgs)
+
+## ✨ Features at a Glance
+
+Ultralytics YOLO extends its powerful object detection features to deliver robust and versatile object tracking:
+
+- **Real-Time Tracking:** Seamlessly track objects in high-frame-rate videos.
+- **Multiple Tracker Support:** Choose from a selection of established tracking algorithms.
+- **Customizable Tracker Configurations:** Adapt the tracking algorithm to specific requirements by adjusting various parameters.
+
+## 🛠️ Available Trackers
+
+Ultralytics YOLO supports the following tracking algorithms. Enable them by passing the relevant YAML configuration file, such as `tracker=bytetrack.yaml`:
+
+- **BoT-SORT:** Use [`botsort.yaml`](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/trackers/botsort.yaml) to enable this tracker. Based on the [BoT-SORT paper](https://arxiv.org/abs/2206.14651) and its official [code implementation](https://github.com/NirAharon/BoT-SORT).
+- **ByteTrack:** Use [`bytetrack.yaml`](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/trackers/bytetrack.yaml) to enable this tracker. Based on the [ByteTrack paper](https://arxiv.org/abs/2110.06864) and its official [code implementation](https://github.com/FoundationVision/ByteTrack).
+- **OC-SORT:** Use [`ocsort.yaml`](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/trackers/ocsort.yaml) to enable this tracker. Based on the [OC-SORT paper](https://arxiv.org/abs/2203.14360) (observation-centric SORT with ORU/OCM/OCR).
+- **Deep OC-SORT:** Use [`deepocsort.yaml`](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/trackers/deepocsort.yaml) to enable this tracker. Based on the [Deep OC-SORT paper](https://arxiv.org/abs/2302.11813), adding adaptive ReID appearance fusion and camera motion compensation on top of OC-SORT.
+- **FastTracker:** Use [`fasttrack.yaml`](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/trackers/fasttrack.yaml) to enable this tracker. Based on the [FastTracker paper](https://arxiv.org/abs/2508.14370): occlusion-aware ByteTrack variant with Kalman rollback and init-IoU suppression.
+- **TrackTrack:** Use [`tracktrack.yaml`](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/trackers/tracktrack.yaml) to enable this tracker. Based on the [TrackTrack paper](https://openaccess.thecvf.com/content/CVPR2025/papers/Shim_Focusing_on_Tracks_for_Online_Multi-Object_Tracking_CVPR_2025_paper.pdf) (CVPR 2025) — multi-cue iterative association with Track-Aware Initialization.
+
+The default tracker is **BoT-SORT**.
+
+## ⚙️ Usage
+
+To run the tracker on video streams, use a trained Detect, Segment, Pose, or OBB model like [Ultralytics YOLO26n](https://docs.ultralytics.com/models/yolo26), YOLO26n-seg, YOLO26n-pose, or YOLO26n-obb.
+
+```python
+# Python
+from ultralytics import YOLO
+
+# Load an official or custom model
+model = YOLO("yolo26n.pt") # Load an official Detect model
+# model = YOLO("yolo26n-seg.pt") # Load an official Segment model
+# model = YOLO("yolo26n-pose.pt") # Load an official Pose model
+# model = YOLO("path/to/best.pt") # Load a custom trained model
+
+# Perform tracking with the model
+results = model.track(source="https://youtu.be/LNwODJXcvt4", show=True) # Tracking with default tracker
+# results = model.track(source="https://youtu.be/LNwODJXcvt4", show=True, tracker="bytetrack.yaml") # Tracking with ByteTrack tracker
+```
+
+```bash
+# CLI
+# Perform tracking with various models using the command line interface
+yolo track model=yolo26n.pt source="https://youtu.be/LNwODJXcvt4" # Official Detect model
+# yolo track model=yolo26n-seg.pt source="https://youtu.be/LNwODJXcvt4" # Official Segment model
+# yolo track model=yolo26n-pose.pt source="https://youtu.be/LNwODJXcvt4" # Official Pose model
+# yolo track model=path/to/best.pt source="https://youtu.be/LNwODJXcvt4" # Custom trained model
+
+# Track using ByteTrack tracker
+# yolo track model=path/to/best.pt tracker="bytetrack.yaml"
+```
+
+As shown above, tracking is available for all [Detect](https://docs.ultralytics.com/tasks/detect), [Segment](https://docs.ultralytics.com/tasks/segment), and [Pose](https://docs.ultralytics.com/tasks/pose) models when run on videos or streaming sources.
+
+## 🔧 Configuration
+
+### Tracking Arguments
+
+Tracking configuration shares properties with the Predict mode, such as `conf` (confidence threshold), `iou` ([Intersection over Union](https://www.ultralytics.com/glossary/intersection-over-union-iou) threshold), and `show` (display results). For additional configurations, refer to the [Predict mode documentation](https://docs.ultralytics.com/modes/predict).
+
+```python
+# Python
+from ultralytics import YOLO
+
+# Configure the tracking parameters and run the tracker
+model = YOLO("yolo26n.pt")
+results = model.track(source="https://youtu.be/LNwODJXcvt4", conf=0.1, iou=0.7, show=True)
+```
+
+```bash
+# CLI
+# Configure tracking parameters and run the tracker using the command line interface
+yolo track model=yolo26n.pt source="https://youtu.be/LNwODJXcvt4" conf=0.1 iou=0.7 show
+```
+
+### Tracker Selection
+
+Ultralytics allows you to use a modified tracker configuration file. Create a copy of a tracker config file (e.g., `custom_tracker.yaml`) from [ultralytics/cfg/trackers](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/cfg/trackers) and adjust any configurations (except `tracker_type`) according to your needs.
+
+```python
+# Python
+from ultralytics import YOLO
+
+# Load the model and run the tracker with a custom configuration file
+model = YOLO("yolo26n.pt")
+results = model.track(source="https://youtu.be/LNwODJXcvt4", tracker="custom_tracker.yaml")
+```
+
+```bash
+# CLI
+# Load the model and run the tracker with a custom configuration file using the command line interface
+yolo track model=yolo26n.pt source="https://youtu.be/LNwODJXcvt4" tracker='custom_tracker.yaml'
+```
+
+For a comprehensive list of tracking arguments, consult the [Tracking Configuration files](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/cfg/trackers) in the repository.
+
+## 🐍 Python Examples
+
+### Persisting Tracks Loop
+
+This Python script uses [OpenCV (`cv2`)](https://opencv.org/) and Ultralytics YOLO26 to perform object tracking on video frames. Ensure you have installed the necessary packages (`opencv-python` and `ultralytics`). The [`persist=True`](https://docs.ultralytics.com/modes/predict#tracking) argument indicates that the current frame is the next in a sequence, allowing the tracker to maintain track continuity from the previous frame.
+
+```python
+# Python
+import cv2
+
+from ultralytics import YOLO
+
+# Load the YOLO26 model
+model = YOLO("yolo26n.pt")
+
+# Open the video file
+video_path = "path/to/video.mp4"
+cap = cv2.VideoCapture(video_path)
+
+# Loop through the video frames
+while cap.isOpened():
+ # Read a frame from the video
+ success, frame = cap.read()
+
+ if success:
+ # Run YOLO26 tracking on the frame, persisting tracks between frames
+ results = model.track(frame, persist=True)
+
+ # Visualize the results on the frame
+ annotated_frame = results[0].plot()
+
+ # Display the annotated frame
+ cv2.imshow("YOLO26 Tracking", annotated_frame)
+
+ # Break the loop if 'q' is pressed
+ if cv2.waitKey(1) & 0xFF == ord("q"):
+ break
+ else:
+ # Break the loop if the end of the video is reached
+ break
+
+# Release the video capture object and close the display window
+cap.release()
+cv2.destroyAllWindows()
+```
+
+Note the use of `model.track(frame)` instead of `model(frame)`, which specifically enables object tracking. This script processes each video frame, visualizes the tracking results, and displays them. Press 'q' to exit the loop.
+
+### Plotting Tracks Over Time
+
+Visualizing object tracks across consecutive frames offers valuable insights into movement patterns within a video. Ultralytics YOLO26 makes plotting these tracks efficient.
+
+The following example demonstrates how to use YOLO26's tracking capabilities to plot the movement of detected objects. The script opens a video, reads it frame by frame, and uses the YOLO model built on [PyTorch](https://pytorch.org/) to identify and track objects. By storing the center points of the detected [bounding boxes](https://www.ultralytics.com/glossary/bounding-box) and connecting them, we can draw lines representing the paths of tracked objects using [NumPy](https://numpy.org/) for numerical operations.
+
+```python
+# Python
+from collections import defaultdict
+
+import cv2
+import numpy as np
+
+from ultralytics import YOLO
+
+# Load the YOLO26 model
+model = YOLO("yolo26n.pt")
+
+# Open the video file
+video_path = "path/to/video.mp4"
+cap = cv2.VideoCapture(video_path)
+
+# Store the track history
+track_history = defaultdict(lambda: [])
+
+# Loop through the video frames
+while cap.isOpened():
+ # Read a frame from the video
+ success, frame = cap.read()
+
+ if success:
+ # Run YOLO26 tracking on the frame, persisting tracks between frames
+ result = model.track(frame, persist=True)[0]
+
+ # Get the boxes and track IDs
+ if result.boxes and result.boxes.is_track:
+ boxes = result.boxes.xywh.cpu()
+ track_ids = result.boxes.id.int().cpu().tolist()
+
+ # Visualize the result on the frame
+ frame = result.plot()
+
+ # Plot the tracks
+ for box, track_id in zip(boxes, track_ids):
+ x, y, w, h = box
+ track = track_history[track_id]
+ track.append((float(x), float(y))) # x, y center point
+ if len(track) > 30: # retain 30 tracks for 30 frames
+ track.pop(0)
+
+ # Draw the tracking lines
+ points = np.hstack(track).astype(np.int32).reshape((-1, 1, 2))
+ cv2.polylines(frame, [points], isClosed=False, color=(230, 230, 230), thickness=10)
+
+ # Display the annotated frame
+ cv2.imshow("YOLO26 Tracking", frame)
+
+ # Break the loop if 'q' is pressed
+ if cv2.waitKey(1) & 0xFF == ord("q"):
+ break
+ else:
+ # Break the loop if the end of the video is reached
+ break
+
+# Release the video capture object and close the display window
+cap.release()
+cv2.destroyAllWindows()
+```
+
+### Multithreaded Tracking
+
+Multithreaded tracking allows running object tracking on multiple video streams simultaneously, which is highly beneficial for systems handling inputs from several cameras, improving efficiency through concurrent processing.
+
+This Python script utilizes Python's [`threading`](https://docs.python.org/3/library/threading.html) module for concurrent tracker execution. Each thread manages tracking for a single video file.
+
+The `run_tracker_in_thread` function accepts a model name and a video source. It loads the model and runs the tracker in streaming mode, consuming results as they are produced.
+
+This example uses two models, `yolo26n.pt` and `yolo26n-seg.pt`, each tracking objects from a different source in the `SOURCES` list.
+
+Setting `daemon=True` in `threading.Thread` ensures threads exit when the main program finishes. Threads are started with `start()` and the main thread waits for their completion using `join()`.
+
+Finally, `cv2.destroyAllWindows()` closes all OpenCV windows after the threads finish.
+
+```python
+# Python
+import threading
+
+import cv2
+
+from ultralytics import YOLO
+
+# Define model names and video sources
+MODEL_NAMES = ["yolo26n.pt", "yolo26n-seg.pt"]
+SOURCES = ["path/to/video.mp4", "0"] # local video, 0 for webcam
+
+
+def run_tracker_in_thread(model_name, filename):
+ """Run YOLO tracker in its own thread for concurrent processing.
+
+ Args:
+ model_name (str): Model name or path that will be loaded inside the thread.
+ filename (str): Local path, device index, or URL that acts as the tracker source.
+ """
+ model = YOLO(model_name)
+ results = model.track(filename, save=True, stream=True)
+ for r in results:
+ pass
+
+
+# Create and start tracker threads using a for loop
+tracker_threads = []
+for video_file, model_name in zip(SOURCES, MODEL_NAMES):
+ thread = threading.Thread(target=run_tracker_in_thread, args=(model_name, video_file), daemon=True)
+ tracker_threads.append(thread)
+ thread.start()
+
+# Wait for all tracker threads to finish
+for thread in tracker_threads:
+ thread.join()
+
+# Clean up and close windows
+cv2.destroyAllWindows()
+```
+
+This setup can be easily scaled to handle more video streams by creating additional threads following the same pattern. Explore more applications in our [blog post on object tracking](https://www.ultralytics.com/blog/object-detection-and-tracking-with-ultralytics-yolov8).
+
+## 🤝 Contribute New Trackers
+
+Are you experienced in multi-object tracking and have implemented or adapted an algorithm with Ultralytics YOLO? We encourage you to contribute to our Trackers section in [ultralytics/cfg/trackers](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/cfg/trackers)! Your contributions can help expand the tracking solutions available within the Ultralytics [ecosystem](https://docs.ultralytics.com/).
+
+To contribute, please review our [Contributing Guide](https://docs.ultralytics.com/help/contributing) for instructions on submitting a [Pull Request (PR)](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests) 🛠️. We look forward to your contributions!
+
+Let's work together to enhance the tracking capabilities of Ultralytics YOLO and provide more powerful tools for the [computer vision](https://www.ultralytics.com/glossary/computer-vision-cv) and [deep learning](https://www.ultralytics.com/glossary/deep-learning-dl) community 🙏!
diff --git a/models_related/ultralytics/ultralytics/trackers/__init__.py b/models_related/ultralytics/ultralytics/trackers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..77ad699d51ac3a06349af3862b15290f562c996d
--- /dev/null
+++ b/models_related/ultralytics/ultralytics/trackers/__init__.py
@@ -0,0 +1,19 @@
+# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+
+from .bot_sort import BOTSORT
+from .byte_tracker import BYTETracker
+from .deep_oc_sort import DeepOCSORT
+from .fast_tracker import FASTTracker
+from .oc_sort import OCSORT
+from .track import register_tracker
+from .track_tracker import TRACKTRACK
+
+__all__ = (
+ "BOTSORT",
+ "OCSORT",
+ "TRACKTRACK",
+ "BYTETracker",
+ "DeepOCSORT",
+ "FASTTracker",
+ "register_tracker",
+) # allow simpler import
diff --git a/models_related/ultralytics/ultralytics/trackers/basetrack.py b/models_related/ultralytics/ultralytics/trackers/basetrack.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c5158801cbcfe45e49517b2adb2c5efc940974d
--- /dev/null
+++ b/models_related/ultralytics/ultralytics/trackers/basetrack.py
@@ -0,0 +1,102 @@
+# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""Module defines the base classes and structures for object tracking in YOLO."""
+
+from typing import Any
+
+
+class TrackState:
+ """Enumeration class representing the possible states of an object being tracked.
+
+ Attributes:
+ New (int): State when the object is newly detected.
+ Tracked (int): State when the object is successfully tracked in subsequent frames.
+ Lost (int): State when the object is no longer tracked.
+ Removed (int): State when the object is removed from tracking.
+
+ Examples:
+ >>> state = TrackState.New
+ >>> if state == TrackState.New:
+ ... print("Object is newly detected.")
+ """
+
+ New = 0
+ Tracked = 1
+ Lost = 2
+ Removed = 3
+
+
+class BaseTrack:
+ """Base class for object tracking, providing foundational attributes and methods.
+
+ Attributes:
+ _count (int): Class-level counter for unique track IDs.
+ track_id (int): Unique identifier for the track.
+ is_activated (bool): Flag indicating whether the track is currently active.
+ state (TrackState): Current state of the track.
+ score (float): The confidence score of the tracking.
+ start_frame (int): The frame number where tracking started.
+ frame_id (int): The most recent frame ID processed by the track.
+
+ Methods:
+ end_frame: Returns the ID of the last frame where the object was tracked.
+ next_id: Increments and returns the next global track ID.
+ activate: Abstract method to activate the track.
+ predict: Abstract method to predict the next state of the track.
+ update: Abstract method to update the track with new data.
+ mark_lost: Marks the track as lost.
+ mark_removed: Marks the track as removed.
+ reset_id: Resets the global track ID counter.
+
+ Examples:
+ Initialize a new track and mark it as lost:
+ >>> track = BaseTrack()
+ >>> track.mark_lost()
+ >>> print(track.state) # Output: 2 (TrackState.Lost)
+ """
+
+ _count = 0
+
+ def __init__(self):
+ """Initialize a new track with a unique ID and foundational tracking attributes."""
+ self.track_id = 0
+ self.is_activated = False
+ self.state = TrackState.New
+ self.score = 0
+ self.start_frame = 0
+ self.frame_id = 0
+
+ @property
+ def end_frame(self) -> int:
+ """Return the ID of the most recent frame where the object was tracked."""
+ return self.frame_id
+
+ @staticmethod
+ def next_id() -> int:
+ """Increment and return the next unique global track ID for object tracking."""
+ BaseTrack._count += 1
+ return BaseTrack._count
+
+ def activate(self, *args: Any) -> None:
+ """Activate the track with provided arguments, initializing necessary attributes for tracking."""
+ raise NotImplementedError
+
+ def predict(self) -> None:
+ """Predict the next state of the track based on the current state and tracking model."""
+ raise NotImplementedError
+
+ def update(self, *args: Any, **kwargs: Any) -> None:
+ """Update the track with new observations and data, modifying its state and attributes accordingly."""
+ raise NotImplementedError
+
+ def mark_lost(self) -> None:
+ """Mark the track as lost by updating its state to TrackState.Lost."""
+ self.state = TrackState.Lost
+
+ def mark_removed(self) -> None:
+ """Mark the track as removed by setting its state to TrackState.Removed."""
+ self.state = TrackState.Removed
+
+ @staticmethod
+ def reset_id() -> None:
+ """Reset the global track ID counter to its initial value."""
+ BaseTrack._count = 0
diff --git a/models_related/ultralytics/ultralytics/trackers/bot_sort.py b/models_related/ultralytics/ultralytics/trackers/bot_sort.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0d0e9974619cf01a28d9178594eacdac8fc7bc2
--- /dev/null
+++ b/models_related/ultralytics/ultralytics/trackers/bot_sort.py
@@ -0,0 +1,211 @@
+# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+
+from __future__ import annotations
+
+from typing import Any
+
+import numpy as np
+
+from .basetrack import TrackState
+from .byte_tracker import BYTETracker, STrack
+from .utils import matching
+from .utils.gmc import GMC
+from .utils.kalman_filter import KalmanFilterXYWH
+from .utils.reid import build_encoder, smooth_feature
+from .utils.stracks import parse_bboxes
+
+
+class BOTrack(STrack):
+ """An extended version of the STrack class for YOLO, adding object tracking features.
+
+ This class extends the STrack class to include additional functionalities for object tracking, such as feature
+ smoothing, Kalman filter prediction, and reactivation of tracks.
+
+ Attributes:
+ shared_kalman (KalmanFilterXYWH): A shared Kalman filter for all instances of BOTrack.
+ smooth_feat (np.ndarray): Smoothed feature vector.
+ curr_feat (np.ndarray): Current feature vector.
+ alpha (float): Smoothing factor for the exponential moving average of features.
+ mean (np.ndarray): The mean state of the Kalman filter.
+ covariance (np.ndarray): The covariance matrix of the Kalman filter.
+
+ Methods:
+ update_features: Update features vector and smooth it using exponential moving average.
+ predict: Predict the mean and covariance using Kalman filter.
+ re_activate: Reactivate a track with updated features and optionally new ID.
+ update: Update the track with new detection and frame ID.
+ tlwh: Property that gets the current position in tlwh format `(top left x, top left y, width, height)`.
+ multi_predict: Predict the mean and covariance of multiple object tracks using shared Kalman filter.
+ convert_coords: Convert tlwh bounding box coordinates to xywh format.
+ tlwh_to_xywh: Convert bounding box to xywh format `(center x, center y, width, height)`.
+
+ Examples:
+ Create a BOTrack instance and update its features
+ >>> bo_track = BOTrack(xywh=np.array([100, 50, 80, 40, 0]), score=0.9, cls=1, feat=np.random.rand(128))
+ >>> bo_track.predict()
+ >>> new_track = BOTrack(xywh=np.array([110, 60, 80, 40, 0]), score=0.85, cls=1, feat=np.random.rand(128))
+ >>> bo_track.update(new_track, frame_id=2)
+ """
+
+ shared_kalman = KalmanFilterXYWH()
+
+ def __init__(self, xywh: np.ndarray, score: float, cls: int, feat: np.ndarray | None = None):
+ """Initialize a BOTrack object with feature-smoothing state and a Kalman filter.
+
+ Args:
+ xywh (np.ndarray): Bounding box in `(x, y, w, h, idx)` or `(x, y, w, h, angle, idx)` format, where (x, y) is
+ the center, (w, h) are width and height, and `idx` is the detection index.
+ score (float): Confidence score of the detection.
+ cls (int): Class ID of the detected object.
+ feat (np.ndarray, optional): Feature vector associated with the detection.
+ """
+ super().__init__(xywh, score, cls)
+
+ self.smooth_feat = None
+ self.curr_feat = None
+ self.alpha = 0.9
+ if feat is not None:
+ self.update_features(feat)
+
+ def update_features(self, feat: np.ndarray) -> None:
+ """Update the current feature and its exponential-moving-average smoothed feature."""
+ curr, smooth = smooth_feature(feat, self.smooth_feat, self.alpha)
+ if curr is not None:
+ self.curr_feat, self.smooth_feat = curr, smooth
+
+ def predict(self) -> None:
+ """Predict the object's future state using the Kalman filter to update its mean and covariance."""
+ mean_state = self.mean.copy()
+ if self.state != TrackState.Tracked:
+ mean_state[6] = 0
+ mean_state[7] = 0
+
+ self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance)
+
+ def re_activate(self, new_track: BOTrack, frame_id: int, new_id: bool = False) -> None:
+ """Reactivate a track with updated features and optionally assign a new ID."""
+ if new_track.curr_feat is not None:
+ self.update_features(new_track.curr_feat)
+ super().re_activate(new_track, frame_id, new_id)
+
+ def update(self, new_track: BOTrack, frame_id: int) -> None:
+ """Update the track with new detection information and the current frame ID."""
+ if new_track.curr_feat is not None:
+ self.update_features(new_track.curr_feat)
+ super().update(new_track, frame_id)
+
+ @property
+ def tlwh(self) -> np.ndarray:
+ """Return the current bounding box position in `(top left x, top left y, width, height)` format."""
+ if self.mean is None:
+ return self._tlwh.copy()
+ ret = self.mean[:4].copy()
+ ret[:2] -= ret[2:] / 2
+ return ret
+
+ @staticmethod
+ def multi_predict(stracks: list[BOTrack]) -> None:
+ """Predict the mean and covariance for multiple object tracks using a shared Kalman filter."""
+ if not stracks:
+ return
+ multi_mean = np.asarray([st.mean.copy() for st in stracks])
+ multi_covariance = np.asarray([st.covariance for st in stracks])
+ for i, st in enumerate(stracks):
+ if st.state != TrackState.Tracked:
+ multi_mean[i][6] = 0
+ multi_mean[i][7] = 0
+ multi_mean, multi_covariance = BOTrack.shared_kalman.multi_predict(multi_mean, multi_covariance)
+ for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):
+ stracks[i].mean = mean
+ stracks[i].covariance = cov
+
+ def convert_coords(self, tlwh: np.ndarray) -> np.ndarray:
+ """Convert tlwh bounding box coordinates to xywh format."""
+ return self.tlwh_to_xywh(tlwh)
+
+ @staticmethod
+ def tlwh_to_xywh(tlwh: np.ndarray) -> np.ndarray:
+ """Convert bounding box from tlwh (top-left-width-height) to xywh (center-x-center-y-width-height) format."""
+ ret = np.asarray(tlwh).copy()
+ ret[:2] += ret[2:] / 2
+ return ret
+
+
+class BOTSORT(BYTETracker):
+ """An extended version of the BYTETracker class for YOLO, designed for object tracking with ReID and GMC algorithm.
+
+ Attributes:
+ proximity_thresh (float): Threshold for spatial proximity (IoU) between tracks and detections.
+ appearance_thresh (float): Threshold for appearance similarity (ReID embeddings) between tracks and detections.
+ encoder (Any): Object to handle ReID embeddings, set to None if ReID is not enabled.
+ gmc (GMC): An instance of the GMC algorithm for data association.
+ args (Any): Parsed command-line arguments containing tracking parameters.
+
+ Methods:
+ get_kalmanfilter: Return an instance of KalmanFilterXYWH for object tracking.
+ init_track: Initialize track with detection results and optional image for ReID.
+ get_dists: Get distances between tracks and detections using IoU and (optionally) ReID.
+ multi_predict: Predict the mean and covariance of multiple object tracks using a shared Kalman filter.
+ reset: Reset the BOTSORT tracker to its initial state.
+
+ Examples:
+ Initialize BOTSORT and process detections
+ >>> bot_sort = BOTSORT(args)
+ >>> bot_sort.init_track(results, img)
+ >>> bot_sort.multi_predict(tracks)
+
+ Notes:
+ The class is designed to work with a YOLO object detection model and supports ReID only if enabled via args.
+ """
+
+ def __init__(self, args: Any):
+ """Initialize BOTSORT object with ReID module and GMC algorithm.
+
+ Args:
+ args (Any): Parsed command-line arguments containing tracking parameters.
+ """
+ super().__init__(args)
+ self.gmc = GMC(method=args.gmc_method)
+
+ # ReID module
+ self.proximity_thresh = args.proximity_thresh
+ self.appearance_thresh = args.appearance_thresh
+ self.encoder = build_encoder(args.with_reid, args.model)
+
+ def get_kalmanfilter(self) -> KalmanFilterXYWH:
+ """Return an instance of KalmanFilterXYWH for predicting and updating object states in the tracking process."""
+ return KalmanFilterXYWH()
+
+ def init_track(self, results, img: np.ndarray | None = None) -> list[BOTrack]:
+ """Initialize object tracks using detection bounding boxes, scores, class labels, and optional ReID features."""
+ if len(results) == 0:
+ return []
+ bboxes = parse_bboxes(results)
+ if self.args.with_reid and self.encoder is not None:
+ features_keep = self.encoder(img, bboxes)
+ return [BOTrack(xywh, s, c, f) for (xywh, s, c, f) in zip(bboxes, results.conf, results.cls, features_keep)]
+ return [BOTrack(xywh, s, c) for (xywh, s, c) in zip(bboxes, results.conf, results.cls)]
+
+ def get_dists(self, tracks: list[BOTrack], detections: list[BOTrack]) -> np.ndarray:
+ """Calculate distances between tracks and detections using IoU and optionally ReID embeddings."""
+ dists = matching.iou_distance(tracks, detections)
+ dists_mask = dists > (1 - self.proximity_thresh)
+
+ if self.args.fuse_score:
+ dists = matching.fuse_score(dists, detections)
+
+ if self.args.with_reid and self.encoder is not None:
+ emb_dists = matching.embedding_distance(tracks, detections) / 2.0
+ emb_dists[emb_dists > (1 - self.appearance_thresh)] = 1.0
+ emb_dists[dists_mask] = 1.0
+ dists = np.minimum(dists, emb_dists)
+ return dists
+
+ def multi_predict(self, tracks: list[BOTrack]) -> None:
+ """Predict the mean and covariance of multiple object tracks using a shared Kalman filter."""
+ BOTrack.multi_predict(tracks)
+
+ def reset(self) -> None:
+ """Reset the BOTSORT tracker to its initial state, clearing all tracked objects and internal states."""
+ super().reset()
+ self.gmc.reset_params()
diff --git a/models_related/ultralytics/ultralytics/trackers/byte_tracker.py b/models_related/ultralytics/ultralytics/trackers/byte_tracker.py
new file mode 100644
index 0000000000000000000000000000000000000000..708db8960a56990d36e6e91cccb16b6a51576323
--- /dev/null
+++ b/models_related/ultralytics/ultralytics/trackers/byte_tracker.py
@@ -0,0 +1,521 @@
+# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+
+from __future__ import annotations
+
+from typing import Any
+
+import numpy as np
+
+from ..utils import LOGGER
+from ..utils.ops import xywh2ltwh
+from .basetrack import BaseTrack, TrackState
+from .utils import matching
+from .utils.kalman_filter import KalmanFilterXYAH
+from .utils.stracks import joint_stracks, merge_track_pools, multi_gmc, parse_bboxes
+
+
+class STrack(BaseTrack):
+ """Single object tracking representation that uses Kalman filtering for state estimation.
+
+ This class is responsible for storing all the information regarding individual tracklets and performs state updates
+ and predictions based on Kalman filter.
+
+ Attributes:
+ shared_kalman (KalmanFilterXYAH): Shared Kalman filter used across all STrack instances for prediction.
+ _tlwh (np.ndarray): Private attribute to store top-left corner coordinates and width and height of bounding box.
+ kalman_filter (KalmanFilterXYAH): Instance of Kalman filter used for this particular object track.
+ mean (np.ndarray): Mean state estimate vector.
+ covariance (np.ndarray): Covariance of state estimate.
+ is_activated (bool): Boolean flag indicating if the track has been activated.
+ score (float): Confidence score of the track.
+ tracklet_len (int): Length of the tracklet.
+ cls (Any): Class label for the object.
+ idx (int): Index or identifier for the object.
+ frame_id (int): Current frame ID.
+ start_frame (int): Frame where the object was first detected.
+ angle (float | None): Optional angle information for oriented bounding boxes.
+
+ Methods:
+ predict: Predict the next state of the object using Kalman filter.
+ multi_predict: Predict the next states for multiple tracks.
+ activate: Activate a new tracklet.
+ re_activate: Reactivate a previously lost tracklet.
+ update: Update the state of a matched track.
+ convert_coords: Convert bounding box to x-y-aspect-height format.
+ tlwh_to_xyah: Convert tlwh bounding box to xyah format.
+
+ Examples:
+ Initialize and activate a new track
+ >>> track = STrack(xywh=[100, 200, 50, 80, 0], score=0.9, cls="person")
+ >>> track.activate(kalman_filter=KalmanFilterXYAH(), frame_id=1)
+ """
+
+ shared_kalman = KalmanFilterXYAH()
+
+ def __init__(self, xywh: np.ndarray, score: float, cls: Any):
+ """Initialize a new STrack instance.
+
+ Args:
+ xywh (np.ndarray): Bounding box in `(x, y, w, h, idx)` or `(x, y, w, h, angle, idx)` format, where (x, y) is
+ the center, (w, h) are width and height, and `idx` is the detection index.
+ score (float): Confidence score of the detection.
+ cls (Any): Class label for the detected object.
+ """
+ super().__init__()
+ # xywh+idx or xywha+idx
+ assert len(xywh) in {5, 6}, f"expected 5 or 6 values but got {len(xywh)}"
+ self._tlwh = np.asarray(xywh2ltwh(xywh[:4]), dtype=np.float32)
+ self.kalman_filter = None
+ self.mean, self.covariance = None, None
+ self.is_activated = False
+
+ self.score = score
+ self.tracklet_len = 0
+ self.cls = cls
+ self.idx = xywh[-1]
+ self.angle = xywh[4] if len(xywh) == 6 else None
+
+ def predict(self):
+ """Predict the next state (mean and covariance) of the object using the Kalman filter."""
+ mean_state = self.mean.copy()
+ if self.state != TrackState.Tracked:
+ mean_state[7] = 0
+ self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance)
+
+ @staticmethod
+ def multi_predict(stracks: list[STrack]):
+ """Perform multi-object predictive tracking using Kalman filter for the provided list of STrack instances."""
+ if not stracks:
+ return
+ multi_mean = np.asarray([st.mean.copy() for st in stracks])
+ multi_covariance = np.asarray([st.covariance for st in stracks])
+ for i, st in enumerate(stracks):
+ if st.state != TrackState.Tracked:
+ multi_mean[i][7] = 0
+ multi_mean, multi_covariance = STrack.shared_kalman.multi_predict(multi_mean, multi_covariance)
+ for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):
+ stracks[i].mean = mean
+ stracks[i].covariance = cov
+
+ def activate(self, kalman_filter: KalmanFilterXYAH, frame_id: int):
+ """Activate a new tracklet using the provided Kalman filter and initialize its state and covariance."""
+ self.kalman_filter = kalman_filter
+ self.track_id = self.next_id()
+ self.mean, self.covariance = self.kalman_filter.initiate(self.convert_coords(self._tlwh))
+
+ self.tracklet_len = 0
+ self.state = TrackState.Tracked
+ if frame_id == 1:
+ self.is_activated = True
+ self.frame_id = frame_id
+ self.start_frame = frame_id
+
+ def re_activate(self, new_track: STrack, frame_id: int, new_id: bool = False):
+ """Reactivate a previously lost track using new detection data and update its state and attributes."""
+ self.mean, self.covariance = self.kalman_filter.update(
+ self.mean, self.covariance, self.convert_coords(new_track.tlwh)
+ )
+ self.tracklet_len = 0
+ self.state = TrackState.Tracked
+ self.is_activated = True
+ self.frame_id = frame_id
+ if new_id:
+ self.track_id = self.next_id()
+ self.score = new_track.score
+ self.cls = new_track.cls
+ self.angle = new_track.angle
+ self.idx = new_track.idx
+
+ def update(self, new_track: STrack, frame_id: int):
+ """Update the state of a matched track.
+
+ Args:
+ new_track (STrack): The new track containing updated information.
+ frame_id (int): The ID of the current frame.
+
+ Examples:
+ Update the state of a track with new detection information
+ >>> track = STrack([100, 200, 50, 80, 0], score=0.9, cls=0)
+ >>> new_track = STrack([105, 205, 55, 85, 0], score=0.95, cls=0)
+ >>> track.update(new_track, 2)
+ """
+ self.frame_id = frame_id
+ self.tracklet_len += 1
+
+ new_tlwh = new_track.tlwh
+ self.mean, self.covariance = self.kalman_filter.update(
+ self.mean, self.covariance, self.convert_coords(new_tlwh)
+ )
+ self.state = TrackState.Tracked
+ self.is_activated = True
+
+ self.score = new_track.score
+ self.cls = new_track.cls
+ self.angle = new_track.angle
+ self.idx = new_track.idx
+
+ def convert_coords(self, tlwh: np.ndarray) -> np.ndarray:
+ """Convert a bounding box's top-left-width-height format to its x-y-aspect-height equivalent."""
+ return self.tlwh_to_xyah(tlwh)
+
+ @property
+ def tlwh(self) -> np.ndarray:
+ """Get the bounding box in top-left-width-height format from the current state estimate."""
+ if self.mean is None:
+ return self._tlwh.copy()
+ ret = self.mean[:4].copy()
+ ret[2] *= ret[3]
+ ret[:2] -= ret[2:] / 2
+ return ret
+
+ @property
+ def xyxy(self) -> np.ndarray:
+ """Convert bounding box from (top left x, top left y, width, height) to (min x, min y, max x, max y) format."""
+ ret = self.tlwh.copy()
+ ret[2:] += ret[:2]
+ return ret
+
+ @staticmethod
+ def tlwh_to_xyah(tlwh: np.ndarray) -> np.ndarray:
+ """Convert bounding box from tlwh format to center-x-center-y-aspect-height (xyah) format."""
+ ret = np.asarray(tlwh).copy()
+ ret[:2] += ret[2:] / 2
+ ret[2] /= ret[3]
+ return ret
+
+ @property
+ def xywh(self) -> np.ndarray:
+ """Get the current position of the bounding box in (center x, center y, width, height) format."""
+ ret = np.asarray(self.tlwh).copy()
+ ret[:2] += ret[2:] / 2
+ return ret
+
+ @property
+ def xywha(self) -> np.ndarray:
+ """Get position in (center x, center y, width, height, angle) format, warning if angle is missing."""
+ if self.angle is None:
+ LOGGER.warning("`angle` attr not found, returning `xywh` instead.")
+ return self.xywh
+ return np.concatenate([self.xywh, self.angle[None]])
+
+ @property
+ def result(self) -> list[float]:
+ """Get the current tracking results in the appropriate bounding box format."""
+ coords = self.xyxy if self.angle is None else self.xywha
+ return [*coords.tolist(), self.track_id, self.score, self.cls, self.idx]
+
+ def __repr__(self) -> str:
+ """Return a string representation of the STrack object including start frame, end frame, and track ID."""
+ return f"OT_{self.track_id}_({self.start_frame}-{self.end_frame})"
+
+
+class BYTETracker:
+ """BYTETracker: A tracking algorithm built on top of YOLO for object detection and tracking.
+
+ This class encapsulates the functionality for initializing, updating, and managing the tracks for detected objects
+ in a video sequence. It maintains the state of tracked, lost, and removed tracks over frames, utilizes Kalman
+ filtering for predicting the new object locations, and performs data association.
+
+ Attributes:
+ tracked_stracks (list[STrack]): List of successfully activated tracks.
+ lost_stracks (list[STrack]): List of lost tracks.
+ removed_stracks (list[STrack]): List of removed tracks.
+ frame_id (int): The current frame ID.
+ args (Namespace): Command-line arguments.
+ max_frames_lost (int): The maximum frames for a track to be considered as 'lost'.
+ kalman_filter (KalmanFilterXYAH): Kalman Filter object.
+
+ Methods:
+ update: Update object tracker with new detections.
+ get_kalmanfilter: Return a Kalman filter object for tracking bounding boxes.
+ init_track: Initialize object tracking with detections.
+ get_dists: Calculate the distance between tracks and detections.
+ multi_predict: Predict the location of tracks.
+ reset_id: Reset the ID counter of STrack.
+ reset: Reset the tracker by clearing all tracks.
+ joint_stracks: Combine two lists of stracks.
+ sub_stracks: Filter out the stracks present in the second list from the first list.
+ remove_duplicate_stracks: Remove duplicate stracks based on IoU.
+
+ Examples:
+ Initialize BYTETracker and update with detection results
+ >>> tracker = BYTETracker(args)
+ >>> results = yolo_model.detect(image)
+ >>> tracked_objects = tracker.update(results)
+ """
+
+ track_class = STrack
+
+ def __init__(self, args):
+ """Initialize a BYTETracker instance for object tracking.
+
+ Args:
+ args (Namespace): Command-line arguments containing tracking parameters.
+ """
+ self.tracked_stracks: list[STrack] = []
+ self.lost_stracks: list[STrack] = []
+ self.removed_stracks: list[STrack] = []
+
+ self.frame_id = 0
+ self.args = args
+ self.max_frames_lost = args.track_buffer
+ self.kalman_filter = self.get_kalmanfilter()
+ self.reset_id()
+
+ def update(self, results, img: np.ndarray | None = None, feats: np.ndarray | None = None, **kwargs) -> np.ndarray:
+ """Update the tracker with new detections and return the current list of tracked objects."""
+ self.frame_id += 1
+ activated_stracks = []
+ refind_stracks = []
+ lost_stracks = []
+ removed_stracks = []
+
+ results_high, results_low, mask_high, mask_low = self._split_detections(results)
+ detections = self.init_track(results_high, self._input_for(img, feats, mask_high))
+ detections_second = self.init_track(results_low, self._input_for(img, feats, mask_low))
+
+ unconfirmed, tracked_stracks = self._split_tracked()
+ strack_pool = joint_stracks(tracked_stracks, self.lost_stracks)
+ self.multi_predict(strack_pool)
+ self._pre_first_associate(strack_pool, unconfirmed, img, results_high)
+
+ u_track, u_detection = self._first_association(strack_pool, detections, activated_stracks, refind_stracks)
+ u_track, u_detection = self._post_first_association(
+ strack_pool, detections, u_track, u_detection, activated_stracks, refind_stracks
+ )
+ self._second_association(
+ strack_pool, u_track, detections_second, activated_stracks, refind_stracks, lost_stracks
+ )
+ u_detection, detections = self._unconfirmed_association(
+ unconfirmed, u_detection, detections, activated_stracks, removed_stracks
+ )
+ self._init_new_tracks(u_detection, detections, activated_stracks, refind_stracks)
+ self._remove_stale_lost(removed_stracks)
+
+ merge_track_pools(self, activated_stracks, refind_stracks, lost_stracks, removed_stracks)
+ return self._format_output()
+
+ def _split_detections(self, results: Any) -> tuple[Any, Any, np.ndarray, np.ndarray]:
+ """Split detections into high-confidence and low-confidence subsets.
+
+ Args:
+ results (Any): Results-like object with ``conf`` attribute supporting boolean indexing.
+
+ Returns:
+ (tuple[Any, Any, np.ndarray, np.ndarray]): High-confidence results, low-confidence results, high mask, and
+ low mask.
+ """
+ scores = results.conf
+ remain_inds = scores >= self.args.track_high_thresh
+ inds_low = scores > self.args.track_low_thresh
+ inds_below_high = scores < self.args.track_high_thresh
+ return results[remain_inds], results[inds_low & inds_below_high], remain_inds, inds_low & inds_below_high
+
+ def _input_for(self, img: np.ndarray | None, feats: np.ndarray | None, mask: np.ndarray) -> Any:
+ """Return the per-detection auxiliary input for ``init_track``.
+
+ Default behavior preserves the legacy flow: when ``feats`` is provided it is sliced by the
+ detection mask, otherwise the raw frame ``img`` is passed through.
+
+ Args:
+ img (np.ndarray | None): Current BGR frame.
+ feats (np.ndarray | None): Optional per-detection features.
+ mask (np.ndarray): Boolean mask used to slice ``feats``.
+
+ Returns:
+ (Any): The auxiliary payload (features or image) to hand to ``init_track``.
+ """
+ if feats is not None and len(feats):
+ return feats[mask]
+ return img
+
+ def _split_tracked(self) -> tuple[list[STrack], list[STrack]]:
+ """Separate ``self.tracked_stracks`` into confirmed and unconfirmed lists.
+
+ Returns:
+ (tuple[list[STrack], list[STrack]]): ``(unconfirmed, tracked)`` where ``unconfirmed`` holds tracks whose
+ ``is_activated`` flag is False.
+ """
+ unconfirmed, tracked = [], []
+ for track in self.tracked_stracks:
+ (unconfirmed if not track.is_activated else tracked).append(track)
+ return unconfirmed, tracked
+
+ def _pre_first_associate(
+ self, strack_pool: list[STrack], unconfirmed: list[STrack], img: np.ndarray | None, results_high: Any
+ ) -> None:
+ """Hook called after Kalman predict, before first-stage assignment. Default: GMC if available."""
+ if hasattr(self, "gmc") and img is not None:
+ try:
+ warp = self.gmc.apply(img, results_high.xyxy)
+ except Exception as e:
+ LOGGER.warning(f"GMC failed, falling back to identity: {e}")
+ warp = np.eye(2, 3)
+ multi_gmc(strack_pool, warp)
+ multi_gmc(unconfirmed, warp)
+
+ def _first_association(
+ self, strack_pool: list[STrack], detections: list[STrack], activated: list[STrack], refind: list[STrack]
+ ) -> tuple[list[int], list[int]]:
+ """First-stage association between track pool and high-score detections.
+
+ Returns:
+ (tuple[list[int], list[int]]): Unmatched track indices and unmatched detection indices.
+ """
+ dists = self.get_dists(strack_pool, detections)
+ matches, u_track, u_detection = matching.linear_assignment(dists, thresh=self.args.match_thresh)
+ self._apply_matches(matches, strack_pool, detections, activated, refind)
+ return u_track, u_detection
+
+ def _post_first_association(
+ self,
+ strack_pool: list[STrack],
+ detections: list[STrack],
+ u_track: list[int],
+ u_detection: list[int],
+ activated: list[STrack],
+ refind: list[STrack],
+ ) -> tuple[list[int], list[int]]:
+ """Hook executed after the first association stage and before the second.
+
+ Returns:
+ (tuple[list[int], list[int]]): Potentially modified unmatched track and detection indices.
+ """
+ return u_track, u_detection
+
+ def _apply_matches(
+ self,
+ matches: list[list[int]] | np.ndarray,
+ pool: list[STrack],
+ detections: list[STrack],
+ activated: list[STrack],
+ refind: list[STrack],
+ ) -> None:
+ """Apply a list of matched (track, detection) pairs from an association stage."""
+ for itracked, idet in matches:
+ self._apply_match(pool[itracked], detections[idet], activated, refind)
+
+ def _apply_match(self, track: STrack, det: STrack, activated: list[STrack], refind: list[STrack]) -> None:
+ """Update or re-activate a single track with its matched detection."""
+ if track.state == TrackState.Tracked:
+ track.update(det, self.frame_id)
+ activated.append(track)
+ else:
+ track.re_activate(det, self.frame_id, new_id=False)
+ refind.append(track)
+
+ def _second_association(
+ self,
+ strack_pool: list[STrack],
+ u_track: list[int],
+ detections_second: list[STrack],
+ activated: list[STrack],
+ refind: list[STrack],
+ lost: list[STrack],
+ ) -> None:
+ """Second-stage association between remaining tracked tracks and low-score detections."""
+ r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]
+ if r_tracked_stracks and detections_second:
+ dists = matching.iou_distance(r_tracked_stracks, detections_second)
+ if self.args.fuse_score:
+ dists = matching.fuse_score(dists, detections_second)
+ matches, u_track, _ = matching.linear_assignment(dists, thresh=0.5)
+ self._apply_matches(matches, r_tracked_stracks, detections_second, activated, refind)
+ else:
+ u_track = list(range(len(r_tracked_stracks)))
+
+ for it in u_track:
+ track = r_tracked_stracks[it]
+ if track.state != TrackState.Lost:
+ track.mark_lost()
+ lost.append(track)
+
+ def _unconfirmed_association(
+ self,
+ unconfirmed: list[STrack],
+ u_detection: list[int],
+ detections: list[STrack],
+ activated: list[STrack],
+ removed: list[STrack],
+ ) -> tuple[list[int], list[STrack]]:
+ """Associate unconfirmed tracks with leftover high-score detections.
+
+ Returns:
+ (tuple[list[int], list[STrack]]): Unmatched detection indices after association, and the filtered detection
+ list those indices refer to.
+ """
+ detections = [detections[i] for i in u_detection]
+ if not unconfirmed:
+ return list(range(len(detections))), detections
+ dists = self.get_dists(unconfirmed, detections)
+ matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)
+ for itracked, idet in matches:
+ unconfirmed[itracked].update(detections[idet], self.frame_id)
+ activated.append(unconfirmed[itracked])
+ for it in u_unconfirmed:
+ track = unconfirmed[it]
+ track.mark_removed()
+ removed.append(track)
+ return u_detection, detections
+
+ def _init_new_tracks(
+ self,
+ u_detection: list[int],
+ detections: list[STrack],
+ activated: list[STrack],
+ refind: list[STrack] | None = None,
+ ) -> None:
+ """Activate new tracks from detections that survived all association stages."""
+ for inew in u_detection:
+ track = detections[inew]
+ if track.score < self.args.new_track_thresh:
+ continue
+ track.activate(self.kalman_filter, self.frame_id)
+ activated.append(track)
+
+ def _remove_stale_lost(self, removed: list[STrack]) -> None:
+ """Remove lost tracks that have exceeded the maximum allowed frames."""
+ for track in self.lost_stracks:
+ if self.frame_id - track.end_frame > self.max_frames_lost:
+ track.mark_removed()
+ removed.append(track)
+
+ def _format_output(self) -> np.ndarray:
+ """Format the current tracked objects into the output array."""
+ return np.asarray([x.result for x in self.tracked_stracks if x.is_activated], dtype=np.float32)
+
+ def get_kalmanfilter(self) -> KalmanFilterXYAH:
+ """Return a Kalman filter object for tracking bounding boxes using KalmanFilterXYAH."""
+ return KalmanFilterXYAH()
+
+ def init_track(self, results, img: np.ndarray | None = None) -> list[STrack]:
+ """Initialize object tracking with given detections, scores, and class labels as STrack instances."""
+ if len(results) == 0:
+ return []
+ bboxes = parse_bboxes(results)
+ return [self.track_class(xywh, s, c) for (xywh, s, c) in zip(bboxes, results.conf, results.cls)]
+
+ def get_dists(self, tracks: list[STrack], detections: list[STrack]) -> np.ndarray:
+ """Calculate the distance between tracks and detections using IoU and optionally fuse scores."""
+ dists = matching.iou_distance(tracks, detections)
+ if self.args.fuse_score:
+ dists = matching.fuse_score(dists, detections)
+ return dists
+
+ def multi_predict(self, tracks: list[STrack]):
+ """Predict the next states for multiple tracks using Kalman filter."""
+ STrack.multi_predict(tracks)
+
+ @staticmethod
+ def reset_id():
+ """Reset the ID counter for STrack instances to ensure unique track IDs across tracking sessions."""
+ STrack.reset_id()
+
+ def reset(self):
+ """Reset the tracker by clearing all tracked, lost, and removed tracks and reinitializing the Kalman filter."""
+ self.tracked_stracks = []
+ self.lost_stracks = []
+ self.removed_stracks = []
+ self.frame_id = 0
+ self.kalman_filter = self.get_kalmanfilter()
+ self.reset_id()
diff --git a/models_related/ultralytics/ultralytics/trackers/deep_oc_sort.py b/models_related/ultralytics/ultralytics/trackers/deep_oc_sort.py
new file mode 100644
index 0000000000000000000000000000000000000000..5749bc3900c5bf19eb07a637983fc1391f0189f7
--- /dev/null
+++ b/models_related/ultralytics/ultralytics/trackers/deep_oc_sort.py
@@ -0,0 +1,275 @@
+# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+
+from __future__ import annotations
+
+from typing import Any
+
+import numpy as np
+
+from .byte_tracker import STrack
+from .oc_sort import OCSORT, OCSortTrack
+from .utils import matching
+from .utils.gmc import GMC
+from .utils.reid import build_encoder, smooth_feature
+from .utils.stracks import parse_bboxes
+
+
+class DeepOCSortTrack(OCSortTrack):
+ """Track object for Deep OC-SORT with appearance features and observation-centric state management.
+
+ Extends OCSortTrack with ReID embedding storage and exponential moving average smoothing, plus confidence-adaptive
+ embedding update rates.
+
+ Attributes:
+ smooth_feat (np.ndarray | None): Smoothed feature vector via EMA.
+ curr_feat (np.ndarray | None): Current frame's feature vector.
+ alpha_fixed_emb (float): Base EMA factor for embedding updates.
+ det_thresh (float): Confidence threshold below which a new embedding is ignored rather than blended.
+ """
+
+ def __init__(
+ self,
+ xywh: np.ndarray,
+ score: float,
+ cls: Any,
+ delta_t: int = 3,
+ feat: np.ndarray | None = None,
+ alpha_fixed_emb: float = 0.95,
+ det_thresh: float = 0.25,
+ ):
+ """Initialize a `DeepOCSortTrack` with optional appearance features.
+
+ Args:
+ xywh (np.ndarray): Bounding box in `(x, y, w, h, idx)` or `(x, y, w, h, angle, idx)` format.
+ score (float): Detection confidence in `[0, 1]`.
+ cls (Any): Class label for the detection.
+ delta_t (int): Temporal window for OCM velocity direction computation.
+ feat (np.ndarray | None): Optional appearance feature vector for this detection.
+ alpha_fixed_emb (float): Base EMA factor for embedding updates; higher = slower updates.
+ det_thresh (float): Detection-confidence threshold below which the embedding is replaced rather than
+ blended.
+ """
+ super().__init__(xywh, score, cls, delta_t)
+ self.smooth_feat = None
+ self.curr_feat = None
+ self.alpha_fixed_emb = alpha_fixed_emb
+ self.det_thresh = det_thresh
+ if feat is not None:
+ self.update_features(feat, score)
+
+ def update_features(self, feat: np.ndarray, score: float | None = None) -> None:
+ """Blend a new appearance feature into `smooth_feat` with confidence-adaptive EMA.
+
+ When `score` exceeds `det_thresh`, the EMA factor `alpha = alpha_fixed_emb + (1 - alpha_fixed_emb) * (1 - trust)`
+ with `trust = (score - det_thresh) / (1 - det_thresh)`, so a high-confidence detection blends in more strongly.
+ At or below `det_thresh`, `alpha = 1.0` so the existing `smooth_feat` is kept and the new (low-trust) feature is
+ ignored — same behavior used by the reference Deep OC-SORT implementation.
+
+ Args:
+ feat (np.ndarray): New (un-normalized) appearance feature vector.
+ score (float | None): Detection confidence used to modulate the EMA factor.
+ """
+ if score is not None and score > self.det_thresh:
+ trust = (score - self.det_thresh) / max(1 - self.det_thresh, 1e-9)
+ alpha = self.alpha_fixed_emb + (1 - self.alpha_fixed_emb) * (1 - trust)
+ else:
+ alpha = 1.0 # keep the existing smooth_feat for low-trust detections
+ curr, smooth = smooth_feature(feat, self.smooth_feat, alpha)
+ if curr is not None:
+ self.curr_feat, self.smooth_feat = curr, smooth
+
+ def update(self, new_track: STrack, frame_id: int) -> None:
+ """Update track state with a matched detection and refresh appearance features.
+
+ Args:
+ new_track (STrack): Matched detection for this frame, with optional `curr_feat`.
+ frame_id (int): Current frame id.
+ """
+ if new_track.curr_feat is not None:
+ self.update_features(new_track.curr_feat, new_track.score)
+ super().update(new_track, frame_id)
+
+ def re_activate(self, new_track: STrack, frame_id: int, new_id: bool = False) -> None:
+ """Re-activate a lost track and refresh appearance features.
+
+ Args:
+ new_track (STrack): Detection used to revive this track.
+ frame_id (int): Current frame id.
+ new_id (bool): If True, assign a fresh track id instead of reusing the old one.
+ """
+ if new_track.curr_feat is not None:
+ self.update_features(new_track.curr_feat, new_track.score)
+ super().re_activate(new_track, frame_id, new_id)
+
+ @staticmethod
+ def multi_gmc(stracks: list[DeepOCSortTrack], H: np.ndarray) -> None:
+ """Apply global motion compensation correctly for the XYAH Kalman state.
+
+ The standard `multi_gmc` helper from `utils.stracks` would rotate `(a, h)` along with
+ `(x, y)`, which is wrong for an aspect-ratio dim. This variant only rotates the
+ position `(x, y)` and the velocity `(vx, vy)` blocks, leaves `(a, h)` and `(va, vh)`
+ untouched, and also rotates the stored `last_observation` so OCR/ORU stay consistent.
+
+ Args:
+ stracks (list[DeepOCSortTrack]): Tracks to warp in place.
+ H (np.ndarray): 2x3 affine homography mapping the previous frame to the current one.
+ """
+ if not stracks:
+ return
+ multi_mean = np.asarray([st.mean.copy() for st in stracks])
+ multi_covariance = np.asarray([st.covariance for st in stracks])
+
+ R = H[:2, :2]
+ t = H[:2, 2]
+
+ # Build 8x8 transform: rotate (x,y) and (vx,vy), identity for (a,h) and (va,vh)
+ R8x8 = np.eye(8, dtype=np.float32)
+ R8x8[:2, :2] = R # rotate position (x, y)
+ R8x8[4:6, 4:6] = R # rotate velocity (vx, vy)
+ # indices 2,3 (a,h) and 6,7 (va,vh) remain identity
+
+ for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):
+ mean = R8x8.dot(mean)
+ mean[:2] += t
+ cov = R8x8.dot(cov).dot(R8x8.transpose())
+ stracks[i].mean = mean
+ stracks[i].covariance = cov
+
+ # Also transform stored observations for OCR/ORU consistency
+ if stracks[i].last_observation[0] >= 0:
+ obs = stracks[i].last_observation
+ # Transform xyxy observation centers
+ cx, cy = (obs[0] + obs[2]) / 2, (obs[1] + obs[3]) / 2
+ w, h = obs[2] - obs[0], obs[3] - obs[1]
+ new_c = R @ np.array([cx, cy]) + t
+ stracks[i].last_observation = np.array(
+ [
+ new_c[0] - w / 2,
+ new_c[1] - h / 2,
+ new_c[0] + w / 2,
+ new_c[1] + h / 2,
+ ],
+ dtype=np.float32,
+ )
+
+
+class DeepOCSORT(OCSORT):
+ """Deep OC-SORT: OC-SORT enhanced with appearance features, GMC, and adaptive weighting.
+
+ Fixes over naive integration:
+ - GMC correctly handles XYAH state (rotates only x,y positions, not aspect ratio/height)
+ - Cost combination uses min(IoU, appearance) following BOTSORT's proven approach
+ - OCR recovery pass also uses appearance features
+ - ByteTrack-style low-confidence second pass disabled by default
+ """
+
+ def __init__(self, args: Any):
+ """Initialize Deep OC-SORT tracker.
+
+ Args:
+ args (Namespace | IterableSimpleNamespace): Parsed tracker config providing the OC-SORT keys plus
+ `gmc_method`, `proximity_thresh`, `appearance_thresh`, `alpha_fixed_emb`, `with_reid`, and `model`.
+ """
+ super().__init__(args)
+
+ # GMC for camera motion compensation
+ self.gmc = GMC(method=getattr(args, "gmc_method", "sparseOptFlow"))
+
+ # Appearance parameters
+ self.proximity_thresh = getattr(args, "proximity_thresh", 0.5)
+ self.appearance_thresh = getattr(args, "appearance_thresh", 0.75)
+ self.alpha_fixed_emb = getattr(args, "alpha_fixed_emb", 0.95)
+
+ self.encoder = build_encoder(getattr(args, "with_reid", False), getattr(args, "model", "auto"))
+
+ def init_track(self, results, img: np.ndarray | None = None) -> list[DeepOCSortTrack]:
+ """Build `DeepOCSortTrack` instances, attaching ReID features when enabled.
+
+ When `with_reid=True` and `model="auto"`, `img` should already be a list of native
+ backbone features (one per detection); for any other `model`, `img` is the source frame
+ and the configured external ReID encoder is invoked on detection crops.
+
+ Args:
+ results (Any): Object exposing `xywh` (or `xywhr`), `conf`, and `cls`.
+ img (np.ndarray | None): Either the BGR frame or pre-extracted feature tensors, depending on the ReID
+ configuration.
+
+ Returns:
+ (list[DeepOCSortTrack]): One track per detection, empty if no detections.
+ """
+ if len(results) == 0:
+ return []
+ bboxes = parse_bboxes(results)
+
+ if self.encoder is not None and img is not None:
+ features = self.encoder(img, bboxes)
+ return [
+ DeepOCSortTrack(
+ xywh,
+ s,
+ c,
+ self.delta_t,
+ feat=f,
+ alpha_fixed_emb=self.alpha_fixed_emb,
+ det_thresh=self.args.track_high_thresh,
+ )
+ for (xywh, s, c, f) in zip(bboxes, results.conf, results.cls, features)
+ ]
+ return [
+ DeepOCSortTrack(
+ xywh, s, c, self.delta_t, alpha_fixed_emb=self.alpha_fixed_emb, det_thresh=self.args.track_high_thresh
+ )
+ for (xywh, s, c) in zip(bboxes, results.conf, results.cls)
+ ]
+
+ def _input_for(self, img: np.ndarray | None, feats: np.ndarray | None, mask: np.ndarray) -> np.ndarray | None:
+ """Return what `init_track` should receive.
+
+ For `model="auto"` (native-features mode) the encoder iterates a per-detection feature
+ tensor, so we must hand it `feats[mask]`. If the upstream pipeline didn't populate
+ `feats` (e.g. user-supplied detections), return None so `init_track` falls back
+ to the no-encoding path instead of feeding a BGR frame into the auto encoder. For
+ external ReID models, `init_track` always wants the BGR frame.
+ """
+ use_native = self.encoder is not None and getattr(self.args, "model", "auto") == "auto"
+ if use_native:
+ return feats[mask] if (feats is not None and len(feats)) else None
+ return img
+
+ def _pre_first_associate(
+ self,
+ strack_pool: list[DeepOCSortTrack],
+ unconfirmed: list[DeepOCSortTrack],
+ img: np.ndarray | None,
+ results_high: Any,
+ ) -> None:
+ """Apply GMC warp to Kalman state before first-stage association."""
+ if img is None:
+ return
+ try:
+ warp = self.gmc.apply(img, results_high.xyxy if len(results_high) else np.empty((0, 4)))
+ except Exception:
+ warp = np.eye(2, 3)
+ DeepOCSortTrack.multi_gmc(strack_pool, warp)
+ DeepOCSortTrack.multi_gmc(unconfirmed, warp)
+
+ def _fuse_appearance(
+ self,
+ dists: np.ndarray,
+ tracks: list[DeepOCSortTrack],
+ detections: list[DeepOCSortTrack],
+ iou_dists: np.ndarray | None = None,
+ ) -> np.ndarray:
+ """Min-fuse appearance distance into the motion cost (BoT-SORT-style)."""
+ if self.encoder is None or not tracks or not detections:
+ return dists
+ emb_dists = matching.embedding_distance(tracks, detections) / 2.0
+ emb_dists[emb_dists > (1 - self.appearance_thresh)] = 1.0
+ if iou_dists is not None:
+ emb_dists[iou_dists > (1 - self.proximity_thresh)] = 1.0
+ return np.minimum(dists, emb_dists)
+
+ def reset(self) -> None:
+ """Reset the Deep OC-SORT tracker, also clearing the GMC warp state."""
+ super().reset()
+ self.gmc.reset_params()
diff --git a/models_related/ultralytics/ultralytics/trackers/fast_tracker.py b/models_related/ultralytics/ultralytics/trackers/fast_tracker.py
new file mode 100644
index 0000000000000000000000000000000000000000..88a629f6fed68824477f4f4fa7011b14a50e0107
--- /dev/null
+++ b/models_related/ultralytics/ultralytics/trackers/fast_tracker.py
@@ -0,0 +1,348 @@
+# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+
+from __future__ import annotations
+
+from collections import deque
+from typing import Any
+
+import numpy as np
+
+from models_related.ultralytics.ultralytics.utils.metrics import bbox_ioa
+
+from .basetrack import TrackState
+from .byte_tracker import BYTETracker, STrack
+from .utils import matching
+from .utils.stracks import parse_bboxes
+
+
+class FastSTrack(STrack):
+ """Single-object track for FastTracker with occlusion-aware state.
+
+ Extends `STrack` with a bounded ring-buffer of recent Kalman means and per-track occlusion
+ bookkeeping. The history buffer enables rolling the Kalman state back to a pre-occlusion frame
+ when a neighbor suddenly covers the target. The buffer is a fixed-size `collections.deque`, so memory stays bounded
+ regardless of track lifetime.
+
+ Attributes:
+ mean_history (collections.deque): Bounded ring-buffer of recent ``(mean, covariance)`` snapshots, newest last,
+ capped at ``history_len`` entries. Rolling back both together keeps the Kalman state internally consistent
+ when a track is restored after an occlusion gap.
+ not_matched (int): Consecutive frames this track has failed to match a detection.
+ is_occluded (bool): True while the track is hidden behind another target.
+ occluded_len (int): Consecutive frames the track has been continuously occluded.
+ last_occluded_frame (int): Frame id when occlusion was last detected, or -1 if never occluded.
+ was_recently_occluded (bool): Sticky flag kept for ``occ_reappear_window`` frames, used by `FASTTracker` to
+ extend the re-find window for tracks that went lost while occluded.
+
+ Examples:
+ >>> from ultralytics.trackers.utils.kalman_filter import KalmanFilterXYAH
+ >>> t = FastSTrack([100, 200, 50, 80, 0], score=0.9, cls=0, history_len=8)
+ >>> t.activate(KalmanFilterXYAH(), frame_id=1)
+ >>> len(t.mean_history)
+ 1
+ """
+
+ def __init__(self, xywh: np.ndarray, score: float, cls: Any, history_len: int = 16):
+ """Initialize a FastSTrack.
+
+ Args:
+ xywh (np.ndarray): Bounding box in ``(x, y, w, h, idx)`` or ``(x, y, w, h, angle, idx)`` format.
+ score (float): Detection confidence in `[0, 1]`.
+ cls (Any): Class label for the detection.
+ history_len (int): Maximum number of past Kalman mean vectors kept for occlusion rollback.
+ """
+ super().__init__(xywh, score, cls)
+ self.mean_history: deque = deque(maxlen=history_len)
+ self.not_matched = 0
+ self.is_occluded = False
+ self.occluded_len = 0
+ self.last_occluded_frame = -1
+ self.was_recently_occluded = False
+
+ def _push_history(self):
+ """Append `(mean, covariance)` copies of the current Kalman state to the bounded buffer."""
+ if self.mean is not None:
+ self.mean_history.append((self.mean.copy(), self.covariance.copy()))
+
+ def activate(self, kalman_filter, frame_id: int):
+ """Activate the track and seed its mean history.
+
+ Args:
+ kalman_filter (KalmanFilterXYAH): Shared Kalman filter instance.
+ frame_id (int): Frame id at which the track is created.
+ """
+ super().activate(kalman_filter, frame_id)
+ self._push_history()
+
+ def re_activate(self, new_track, frame_id: int, new_id: bool = False):
+ """Re-activate a previously lost track and clear any stale occlusion bookkeeping.
+
+ Args:
+ new_track (FastSTrack): Detection used to revive this track.
+ frame_id (int): Current frame id.
+ new_id (bool): If True, assign a fresh track id instead of reusing the old one.
+ """
+ super().re_activate(new_track, frame_id, new_id=new_id)
+ self.is_occluded = False
+ self.occluded_len = 0
+ self.not_matched = 0
+ self.was_recently_occluded = False
+ self.last_occluded_frame = -1
+ self._push_history()
+
+ def update(self, new_track, frame_id: int):
+ """Update the track with a newly matched detection.
+
+ Args:
+ new_track (FastSTrack): Matched detection for this frame.
+ frame_id (int): Current frame id.
+ """
+ super().update(new_track, frame_id)
+ self._push_history()
+
+
+class FASTTracker(BYTETracker):
+ """Occlusion-aware ByteTrack-style multi-object tracker.
+
+ Adapted from the reference implementation in the FastTracker paper (arXiv:2508.14370). FastTracker extends
+ `BYTETracker` with lightweight mechanisms that reduce ID switches through crowd occlusions without sacrificing
+ throughput. Unmatched tracks whose area is strongly covered by an active neighbor are flagged as occluded and their
+ Kalman state is rolled back to a pre-occlusion frame, with a one-shot bbox enlargement and dampened motion so they
+ survive the occlusion. An occluded track is kept alive for an extra grace window before being marked lost, and once
+ lost it stays re-findable for an extended window beyond the regular ``track_buffer``. New detections that strongly
+ overlap an already-active track are suppressed at spawn time to prevent ghost IDs.
+
+ All added work uses vectorized IoU / coverage matrices and only runs on unmatched tracks, so the per-frame overhead
+ over `BYTETracker` stays on the order of a few hundred microseconds.
+
+ Attributes:
+ reset_velocity_offset_occ (int): Number of frames to look back when restoring Kalman velocity at occlusion
+ onset.
+ reset_pos_offset_occ (int): Number of frames to look back when restoring Kalman position at occlusion onset.
+ enlarge_bbox_occ (float): One-shot multiplier applied to the bbox height when occlusion is first detected.
+ dampen_motion_occ (float): Multiplier in `[0, 1]` applied to Kalman velocity during occlusion.
+ active_occ_to_lost_thresh (int): Maximum consecutive occluded frames before a track is marked lost anyway.
+ init_iou_suppress (float): IoU threshold above which a new detection is prevented from spawning a fresh track.
+ Set to 1.0 to disable suppression.
+ occ_cover_thresh (float): Fraction of a track's area that must be covered by another active track to declare
+ occlusion.
+ occ_reappear_window (int): Frames a recently-occluded lost track stays re-findable beyond the regular
+ ``track_buffer``.
+
+ Methods:
+ update: Consume a frame's detections and return the currently-tracked objects.
+ init_track: Build `FastSTrack` instances from a ``Results``-like object.
+
+ Examples:
+ Plug FastTracker into a YOLO model via the bundled config:
+ >>> from ultralytics import YOLO
+ >>> model = YOLO("yolo26s.pt")
+ >>> model.track("video.mp4", tracker="fasttrack.yaml")
+
+ Drive FastTracker directly with your own detections:
+ >>> from ultralytics.trackers import FASTTracker
+ >>> from ultralytics.utils import YAML, IterableSimpleNamespace
+ >>> cfg = IterableSimpleNamespace(**YAML.load("ultralytics/cfg/trackers/fasttrack.yaml"))
+ >>> tracker = FASTTracker(cfg)
+ >>> tracks = tracker.update(detections)
+ """
+
+ track_class = FastSTrack
+
+ def __init__(self, args):
+ """Initialize FastTracker with tunables read from ``args``.
+
+ Any FastTracker-specific key missing on ``args`` falls back to a sensible default, so
+ FastTracker can also be driven by a plain ByteTrack config.
+
+ Args:
+ args (Namespace | IterableSimpleNamespace): Parsed tracker config. Must provide the BYTETracker keys
+ (``track_high_thresh``, ``track_low_thresh``, ``new_track_thresh``, ``track_buffer``, ``match_thresh``,
+ ``fuse_score``) and may provide the FastTracker-specific keys described in the class docstring.
+ """
+ super().__init__(args)
+ # Occlusion-handling knobs (fall back to sensible defaults if absent on args)
+ self.reset_velocity_offset_occ = int(getattr(args, "reset_velocity_offset_occ", 5))
+ self.reset_pos_offset_occ = int(getattr(args, "reset_pos_offset_occ", 3))
+ self.enlarge_bbox_occ = float(getattr(args, "enlarge_bbox_occ", 1.1))
+ self.dampen_motion_occ = float(getattr(args, "dampen_motion_occ", 0.5))
+ self.active_occ_to_lost_thresh = int(getattr(args, "active_occ_to_lost_thresh", 10))
+ self.init_iou_suppress = float(getattr(args, "init_iou_suppress", 0.7))
+ self.occ_cover_thresh = float(getattr(args, "occ_cover_thresh", 0.7))
+ self.occ_reappear_window = int(getattr(args, "occ_reappear_window", 40))
+ # Cap history to the max rollback we'll need + small slack.
+ self._history_len = max(self.reset_velocity_offset_occ, self.reset_pos_offset_occ) + 4
+
+ def init_track(self, results, img: np.ndarray | None = None) -> list[FastSTrack]:
+ """Build `FastSTrack` instances from a ``Results``-like object.
+
+ Args:
+ results (Any): Object exposing ``xywh`` (or ``xywhr``), ``conf``, and ``cls``.
+ img (np.ndarray | None): Current BGR frame. Unused by FastTracker; accepted for signature parity with other
+ trackers.
+
+ Returns:
+ (list[FastSTrack]): One `FastSTrack` per detection, empty if no detections.
+ """
+ if len(results) == 0:
+ return []
+ bboxes = parse_bboxes(results)
+ return [
+ FastSTrack(xywh, s, c, history_len=self._history_len)
+ for (xywh, s, c) in zip(bboxes, results.conf, results.cls)
+ ]
+
+ def _apply_match(self, track: STrack, det: STrack, activated: list[STrack], refind: list[STrack]) -> None:
+ """Update or re-activate a track and clear any occlusion bookkeeping on a successful match."""
+ super()._apply_match(track, det, activated, refind)
+ track.is_occluded = False
+ track.not_matched = 0
+ track.occluded_len = 0
+
+ def _second_association(
+ self,
+ strack_pool: list[STrack],
+ u_track: list[int],
+ detections_second: list[STrack],
+ activated: list[STrack],
+ refind: list[STrack],
+ lost: list[STrack],
+ ) -> None:
+ """Second-stage association + occlusion handling (replaces base mark-lost loop)."""
+ r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]
+ if r_tracked_stracks and detections_second:
+ dists = matching.iou_distance(r_tracked_stracks, detections_second)
+ if self.args.fuse_score:
+ dists = matching.fuse_score(dists, detections_second)
+ matches, u_track, _ = matching.linear_assignment(dists, thresh=0.5)
+ self._apply_matches(matches, r_tracked_stracks, detections_second, activated, refind)
+ else:
+ u_track = list(range(len(r_tracked_stracks)))
+ self._handle_occlusions(r_tracked_stracks, u_track, activated, lost)
+
+ def _init_new_tracks(
+ self,
+ u_detection: list[int],
+ detections: list[STrack],
+ activated: list[STrack],
+ refind: list[STrack] | None = None,
+ ) -> None:
+ """Activate new tracks, suppressing detections that heavily overlap already-active tracks."""
+ active_boxes = [t.xyxy for t in activated if t.is_activated]
+ if refind:
+ active_boxes.extend(t.xyxy for t in refind if t.is_activated)
+ active_boxes.extend(t.xyxy for t in self.tracked_stracks if t.state == TrackState.Tracked)
+ suppress_on = self.init_iou_suppress < 1.0
+ active_stack = (
+ np.asarray(active_boxes, dtype=np.float32) if active_boxes else np.empty((0, 4), dtype=np.float32)
+ )
+ for inew in u_detection:
+ det = detections[inew]
+ if det.score < self.args.new_track_thresh:
+ continue
+ if suppress_on and len(active_stack):
+ if bbox_ioa(det.xyxy[None, :], active_stack, iou=True).max() >= self.init_iou_suppress:
+ continue
+ det.activate(self.kalman_filter, self.frame_id)
+ activated.append(det)
+ active_stack = np.concatenate([active_stack, det.xyxy[None, :]], axis=0)
+
+ def _remove_stale_lost(self, removed: list[STrack]) -> None:
+ """Remove lost tracks, with a grace window for recently-occluded ones."""
+ for track in self.lost_stracks:
+ recently_occluded = track.was_recently_occluded and (
+ self.frame_id - track.last_occluded_frame <= self.occ_reappear_window
+ )
+ if not recently_occluded and (self.frame_id - track.end_frame > self.max_frames_lost):
+ track.mark_removed()
+ removed.append(track)
+
+ def _format_output(self) -> np.ndarray:
+ """Only emit tracks updated this frame to avoid stale ``idx`` values."""
+ return np.asarray(
+ [x.result for x in self.tracked_stracks if x.is_activated and x.frame_id == self.frame_id],
+ dtype=np.float32,
+ )
+
+ def _handle_occlusions(self, r_tracked, u_track, activated_stracks, lost_stracks):
+ """Flag unmatched tracked tracks as occluded when covered by an active neighbor.
+
+ For each unmatched track, computes the fraction of its area covered by any currently-active
+ track. If coverage exceeds ``occ_cover_thresh``, the track is marked occluded, its Kalman
+ state is rolled back using the ring-buffer history (velocity from ``reset_velocity_offset_occ``
+ frames ago, position from ``reset_pos_offset_occ`` frames ago), the bbox height is scaled by
+ ``enlarge_bbox_occ`` once, and velocity is dampened by ``dampen_motion_occ``. Tracks that
+ remain unmatched for more than two frames are transitioned to Lost, except while they are
+ within the ``active_occ_to_lost_thresh`` occluded-grace window.
+
+ Args:
+ r_tracked (list[FastSTrack]): Candidate track pool.
+ u_track (list[int] | np.ndarray): Indices into ``r_tracked`` of tracks still unmatched.
+ activated_stracks (list[FastSTrack]): Tracks already matched this frame; used as the pool of potential
+ occluders.
+ lost_stracks (list[FastSTrack]): Output list; tracks transitioned to Lost are appended.
+ """
+ if len(u_track) == 0:
+ return
+
+ # Build active-track box array once (vectorized cover check).
+ active = [t for t in activated_stracks if t.is_activated and not t.is_occluded]
+ if len(active):
+ active_boxes = np.asarray([t.xyxy for t in active], dtype=np.float32)
+ active_ids = np.asarray([t.track_id for t in active])
+ else:
+ active_boxes = np.empty((0, 4), dtype=np.float32)
+ active_ids = np.empty((0,), dtype=np.int64)
+
+ unmatched = [r_tracked[i] for i in u_track]
+ unmatched_boxes = (
+ np.asarray([t.xyxy for t in unmatched], dtype=np.float32)
+ if unmatched
+ else np.empty((0, 4), dtype=np.float32)
+ )
+
+ if active_boxes.size and unmatched_boxes.size:
+ cov = bbox_ioa(active_boxes, unmatched_boxes) # (A, U) = intersection / unmatched-track area
+ # Avoid self-match: zero out entries that correspond to the same track id.
+ unm_ids = np.asarray([t.track_id for t in unmatched])
+ same = active_ids[:, None] == unm_ids[None, :]
+ cov[same] = 0.0
+ max_cov = cov.max(axis=0) # per unmatched track, max fraction of its area covered by an active track
+ else:
+ max_cov = np.zeros(len(unmatched), dtype=np.float32)
+
+ for i, track in enumerate(unmatched):
+ track.not_matched += 1
+
+ if max_cov[i] > self.occ_cover_thresh and not track.is_occluded and track.state == TrackState.Tracked:
+ track.is_occluded = True
+ track.occluded_len = 1
+ track.last_occluded_frame = self.frame_id
+ track.was_recently_occluded = True
+
+ hist = track.mean_history
+ if track.mean is not None and hist:
+ if len(hist) >= self.reset_velocity_offset_occ:
+ prev_mean, _ = hist[-self.reset_velocity_offset_occ]
+ track.mean[4:8] = prev_mean[4:8]
+ if len(hist) >= self.reset_pos_offset_occ:
+ prev_mean, prev_cov = hist[-self.reset_pos_offset_occ]
+ track.mean[0:4] = prev_mean[0:4]
+ track.covariance = prev_cov.copy()
+ # Enlarge height once to expand search region (XYAH state: a is held, so
+ # scaling h proportionally scales w via w = a * h).
+ track.mean[3] *= self.enlarge_bbox_occ
+ track.mean[4:8] *= self.dampen_motion_occ
+ elif track.is_occluded:
+ track.occluded_len += 1
+
+ if track.was_recently_occluded and (self.frame_id - track.last_occluded_frame > self.occ_reappear_window):
+ track.was_recently_occluded = False
+
+ if track.state != TrackState.Lost:
+ # Give occluded tracks a grace period before marking lost.
+ if track.not_matched > 2 and (
+ not track.is_occluded or track.occluded_len > self.active_occ_to_lost_thresh
+ ):
+ track.mark_lost()
+ lost_stracks.append(track)
diff --git a/models_related/ultralytics/ultralytics/trackers/oc_sort.py b/models_related/ultralytics/ultralytics/trackers/oc_sort.py
new file mode 100644
index 0000000000000000000000000000000000000000..d2b0f4bafa1c5613f756e8af28d8d84789869cd9
--- /dev/null
+++ b/models_related/ultralytics/ultralytics/trackers/oc_sort.py
@@ -0,0 +1,361 @@
+# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+
+from __future__ import annotations
+
+from typing import Any
+
+import numpy as np
+
+from .basetrack import TrackState
+from .byte_tracker import BYTETracker, STrack
+from .utils import matching
+from .utils.stracks import parse_bboxes
+
+
+class OCSortTrack(STrack):
+ """Track object for OC-SORT with observation-centric state management.
+
+ Extends STrack with storage of real detector observations and velocity computation, enabling the three OC-SORT
+ components: ORU, OCM, and OCR.
+
+ Attributes:
+ last_observation (np.ndarray): Last real detection in xyxy format.
+ observations (dict): Maps frame_id to xyxy observation arrays.
+ velocity (np.ndarray | None): Observation-centric velocity direction vector (dx, dy).
+ delta_t (int): Temporal window for velocity computation.
+ """
+
+ def __init__(self, xywh: np.ndarray, score: float, cls: Any, delta_t: int = 3):
+ """Initialize an OCSortTrack with observation storage.
+
+ Args:
+ xywh (np.ndarray): Bounding box in `(x, y, w, h, idx)` or `(x, y, w, h, angle, idx)` format.
+ score (float): Detection confidence in `[0, 1]`.
+ cls (Any): Class label for the detection.
+ delta_t (int): Temporal window (in frames) used for velocity direction computation.
+ """
+ super().__init__(xywh, score, cls)
+ self.last_observation = np.array([-1, -1, -1, -1], dtype=np.float32)
+ self.observations: dict[int, np.ndarray] = {}
+ self.velocity: np.ndarray | None = None
+ self.delta_t = delta_t
+ self._saved_mean: np.ndarray | None = None
+ self._saved_covariance: np.ndarray | None = None
+
+ def activate(self, kalman_filter, frame_id: int) -> None:
+ """Activate a new tracklet and seed its observation history.
+
+ Args:
+ kalman_filter (KalmanFilterXYAH): Shared Kalman filter instance.
+ frame_id (int): Frame id at which the track is created.
+ """
+ super().activate(kalman_filter, frame_id)
+ self.last_observation = self.xyxy.copy()
+ self.observations[frame_id] = self.xyxy.copy()
+ self._saved_mean = self.mean.copy()
+ self._saved_covariance = self.covariance.copy()
+
+ def update(self, new_track: STrack, frame_id: int) -> None:
+ """Update the track with a matched detection and record the observation.
+
+ Args:
+ new_track (STrack): Matched detection for this frame.
+ frame_id (int): Current frame id.
+ """
+ obs = new_track.xyxy.copy()
+ self.last_observation = obs
+ self.observations[frame_id] = obs
+ self._prune_observations()
+ super().update(new_track, frame_id)
+ self._saved_mean = self.mean.copy()
+ self._saved_covariance = self.covariance.copy()
+ self.velocity = self._compute_velocity()
+
+ def re_activate(self, new_track: STrack, frame_id: int, new_id: bool = False) -> None:
+ """Re-activate a previously lost track with a new detection.
+
+ Args:
+ new_track (STrack): Detection used to revive this track.
+ frame_id (int): Current frame id.
+ new_id (bool): If True, assign a fresh track id instead of reusing the old one.
+ """
+ obs = new_track.xyxy.copy()
+ self.last_observation = obs
+ self.observations[frame_id] = obs
+ super().re_activate(new_track, frame_id, new_id)
+ self._saved_mean = self.mean.copy()
+ self._saved_covariance = self.covariance.copy()
+ self.velocity = self._compute_velocity()
+
+ @staticmethod
+ def _xyxy_center(xyxy: np.ndarray) -> np.ndarray:
+ """Return `(cx, cy)` center of an xyxy bounding box."""
+ return np.array([(xyxy[0] + xyxy[2]) / 2, (xyxy[1] + xyxy[3]) / 2])
+
+ def _prune_observations(self) -> None:
+ """Drop old observations beyond `delta_t + 2` to bound memory while keeping enough for velocity."""
+ max_keep = self.delta_t + 2
+ if len(self.observations) <= max_keep:
+ return
+ sorted_frames = sorted(self.observations.keys())
+ for frame in sorted_frames[:-max_keep]:
+ del self.observations[frame]
+
+ def _compute_velocity(self) -> np.ndarray | None:
+ """Compute the observation-centric velocity direction from stored observations.
+
+ Returns:
+ (np.ndarray | None): Normalized `(dx, dy)` direction vector, or None if there are fewer than two usable
+ observations.
+ """
+ if len(self.observations) < 2:
+ return None
+
+ current_frame = max(self.observations.keys())
+ current_center = self._xyxy_center(self.observations[current_frame])
+
+ # Find the most recent observation at least delta_t frames before current
+ prev_obs = None
+ for frame in sorted(self.observations.keys(), reverse=True):
+ if frame < current_frame - self.delta_t + 1:
+ prev_obs = self.observations[frame]
+ break
+
+ # Fallback: use the earliest observation if nothing is delta_t frames back
+ if prev_obs is None:
+ earliest_frame = min(self.observations.keys())
+ if earliest_frame == current_frame:
+ return None
+ prev_obs = self.observations[earliest_frame]
+
+ direction = current_center - self._xyxy_center(prev_obs)
+ norm = np.linalg.norm(direction)
+ if norm < 1e-6:
+ return np.zeros(2, dtype=np.float32)
+ return (direction / norm).astype(np.float32)
+
+ def apply_oru(self, new_observation_xyxy: np.ndarray, current_frame_id: int) -> None:
+ """Repair Kalman state across an occlusion gap by replaying predict-updates on virtual observations."""
+ if self._saved_mean is None or not self.observations:
+ return
+
+ last_frame = max(self.observations.keys())
+ gap = current_frame_id - last_frame
+ if gap <= 1:
+ return
+
+ # Restore Kalman state to last observation point
+ self.mean = self._saved_mean.copy()
+ self.covariance = self._saved_covariance.copy()
+
+ last_obs = self.observations[last_frame]
+
+ # Replay with virtual observations
+ for t in range(1, gap):
+ alpha = t / gap
+ virtual_xyxy = (1 - alpha) * last_obs + alpha * new_observation_xyxy
+ # Convert xyxy to tlwh then to xyah for Kalman measurement
+ virtual_tlwh = np.array(
+ [
+ virtual_xyxy[0],
+ virtual_xyxy[1],
+ virtual_xyxy[2] - virtual_xyxy[0],
+ virtual_xyxy[3] - virtual_xyxy[1],
+ ]
+ )
+ virtual_xyah = self.tlwh_to_xyah(virtual_tlwh)
+ self.mean, self.covariance = self.kalman_filter.predict(self.mean, self.covariance)
+ self.mean, self.covariance = self.kalman_filter.update(self.mean, self.covariance, virtual_xyah)
+
+ # Final predict to reach current frame
+ self.mean, self.covariance = self.kalman_filter.predict(self.mean, self.covariance)
+
+
+class OCSORT(BYTETracker):
+ """OC-SORT multi-object tracker with observation-centric association.
+
+ Implements three key components on top of BYTETracker:
+ - Observation-Centric Re-Update (ORU): repairs Kalman state after occlusion
+ - Observation-Centric Momentum (OCM): velocity direction consistency cost
+ - Observation-Centric Recovery (OCR): re-association using last observation position
+
+ Attributes:
+ delta_t (int): Temporal window for velocity direction computation.
+ inertia (float): Weight of velocity consistency cost in association.
+ use_byte (bool): Whether to use ByteTrack-style low-confidence second pass.
+ """
+
+ track_class = OCSortTrack
+
+ def __init__(self, args: Any):
+ """Initialize OC-SORT tracker.
+
+ Args:
+ args (Namespace | IterableSimpleNamespace): Parsed tracker config providing the BYTE keys plus `delta_t`,
+ `inertia`, and `use_byte`.
+ """
+ super().__init__(args)
+ self.delta_t = getattr(args, "delta_t", 3)
+ self.inertia = getattr(args, "inertia", 0.2)
+ self.use_byte = getattr(args, "use_byte", False)
+
+ def init_track(self, results, img: np.ndarray | None = None) -> list[OCSortTrack]:
+ """Build `OCSortTrack` instances from a `Results`-like object."""
+ if len(results) == 0:
+ return []
+ bboxes = parse_bboxes(results)
+ return [OCSortTrack(xywh, s, c, self.delta_t) for (xywh, s, c) in zip(bboxes, results.conf, results.cls)]
+
+ def _fuse_appearance(
+ self,
+ dists: np.ndarray,
+ tracks: list[OCSortTrack],
+ detections: list[OCSortTrack],
+ iou_dists: np.ndarray | None = None,
+ ) -> np.ndarray:
+ """Hook combining motion cost with appearance cost. Default: pass-through (no ReID)."""
+ return dists
+
+ def get_dists(self, tracks: list[OCSortTrack], detections: list[OCSortTrack]) -> np.ndarray:
+ """Cost matrix = IoU (+score-fuse) + inertia·OCM (+ optional appearance, via hook)."""
+ iou_dists = matching.iou_distance(tracks, detections)
+ dists = matching.fuse_score(iou_dists, detections) if self.args.fuse_score else iou_dists.copy()
+ dists = dists + self.inertia * self._velocity_direction_cost(tracks, detections)
+ return self._fuse_appearance(dists, tracks, detections, iou_dists=iou_dists)
+
+ def _ocr_associate(
+ self,
+ tracks: list[OCSortTrack],
+ dets: list[OCSortTrack],
+ activated: list[OCSortTrack],
+ refind: list[OCSortTrack],
+ ) -> tuple[list[int], list[int]]:
+ """Run one OCR (last-observation IoU) pass, applying matches in place.
+
+ Returns:
+ (tuple[list[int], list[int]]): Local indices of unmatched ``tracks`` and unmatched ``dets``.
+ """
+ if not tracks or not dets:
+ return list(range(len(tracks))), list(range(len(dets)))
+ ocr_dists = self._ocr_distance(tracks, dets)
+ if self.args.fuse_score:
+ ocr_dists = matching.fuse_score(ocr_dists, dets)
+ ocr_dists = self._fuse_appearance(ocr_dists, tracks, dets)
+ matches, u_track, u_det = matching.linear_assignment(ocr_dists, thresh=self.args.match_thresh)
+ for itracked, idet in matches:
+ track, det = tracks[itracked], dets[idet]
+ if track.state == TrackState.Tracked:
+ track.update(det, self.frame_id)
+ activated.append(track)
+ else:
+ track.apply_oru(det.xyxy, self.frame_id)
+ track.re_activate(det, self.frame_id, new_id=False)
+ refind.append(track)
+ return list(u_track), list(u_det)
+
+ def _post_first_association(
+ self,
+ strack_pool: list[OCSortTrack],
+ detections: list[OCSortTrack],
+ u_track: list[int],
+ u_detection: list[int],
+ activated: list[OCSortTrack],
+ refind: list[OCSortTrack],
+ ) -> tuple[list[int], list[int]]:
+ """Observation-Centric Recovery (OCR) pass after first-stage association.
+
+ Runs OCR for still-Tracked unmatched tracks first to preserve active-track matching priority, then for
+ Lost tracks on the detections still unmatched, so a recently-lost track cannot outbid an active one.
+ """
+ ocr_dets = [detections[i] for i in u_detection]
+ if not ocr_dets:
+ return u_track, u_detection
+
+ tracked = [i for i in u_track if strack_pool[i].state == TrackState.Tracked]
+ other = [i for i in u_track if strack_pool[i].state != TrackState.Tracked]
+
+ u_t1, u_d1 = self._ocr_associate([strack_pool[i] for i in tracked], ocr_dets, activated, refind)
+ remaining = [ocr_dets[j] for j in u_d1]
+ u_t2, u_d2 = self._ocr_associate([strack_pool[i] for i in other], remaining, activated, refind)
+
+ u_track = [tracked[i] for i in u_t1] + [other[i] for i in u_t2]
+ u_detection = [u_detection[u_d1[j]] for j in u_d2]
+ return u_track, u_detection
+
+ def _second_association(
+ self,
+ strack_pool: list[OCSortTrack],
+ u_track: list[int],
+ detections_second: list[OCSortTrack],
+ activated: list[OCSortTrack],
+ refind: list[OCSortTrack],
+ lost: list[OCSortTrack],
+ ) -> None:
+ """Run ByteTrack-style second pass only when ``use_byte`` is enabled."""
+ if not self.use_byte:
+ for i in u_track:
+ track = strack_pool[i]
+ if track.state == TrackState.Tracked:
+ track.mark_lost()
+ lost.append(track)
+ return
+ super()._second_association(strack_pool, u_track, detections_second, activated, refind, lost)
+
+ def _velocity_direction_cost(self, tracks: list[OCSortTrack], detections: list[OCSortTrack]) -> np.ndarray:
+ """Compute OCM velocity direction consistency cost matrix (vectorized).
+
+ For each track-detection pair, measures the angular difference between
+ the track's historical motion direction and the direction to the candidate detection.
+
+ Args:
+ tracks (list[OCSortTrack]): List of tracks.
+ detections (list[OCSortTrack]): List of detections.
+
+ Returns:
+ (np.ndarray): Cost matrix of shape (len(tracks), len(detections)).
+ """
+ cost = np.zeros((len(tracks), len(detections)), dtype=np.float32)
+ if cost.size == 0:
+ return cost
+
+ # Pre-extract detection centers as (M, 2) array
+ det_centers = np.array([OCSortTrack._xyxy_center(det.xyxy) for det in detections], dtype=np.float32)
+
+ for i, track in enumerate(tracks):
+ if track.velocity is None or track.last_observation[0] < 0:
+ continue
+ track_center = OCSortTrack._xyxy_center(track.last_observation)
+ directions = det_centers - track_center # (M, 2)
+ norms = np.linalg.norm(directions, axis=1) # (M,)
+ valid = norms > 1e-6
+ if not valid.any():
+ continue
+ directions[valid] /= norms[valid, None]
+ dots = np.clip(directions[valid] @ track.velocity, -1.0, 1.0)
+ cost[i, valid] = np.arccos(dots) / np.pi
+
+ return cost
+
+ def _ocr_distance(self, tracks: list[OCSortTrack], detections: list[OCSortTrack]) -> np.ndarray:
+ """Compute IoU distance using tracks' last observation positions instead of Kalman predictions.
+
+ Args:
+ tracks (list[OCSortTrack]): List of tracks with last_observation attributes.
+ detections (list[OCSortTrack]): List of detections.
+
+ Returns:
+ (np.ndarray): Cost matrix based on IoU with last observations (or xywha for OBB).
+
+ Notes:
+ `last_observation` is stored in xyxy form. For oriented (OBB) tracks no oriented
+ last-observation is kept, so this method falls back to the Kalman-predicted `xywha`
+ and the OCR pass degenerates to standard IoU on the predicted box. Standard
+ (axis-aligned) tracking gets the full OCR benefit.
+ """
+ if tracks and tracks[0].angle is not None:
+ atlbrs = [t.xywha for t in tracks]
+ btlbrs = [d.xywha for d in detections]
+ else:
+ atlbrs = [t.last_observation if t.last_observation[0] >= 0 else t.xyxy for t in tracks]
+ btlbrs = [d.xyxy for d in detections]
+ return matching.iou_distance(atlbrs, btlbrs)
diff --git a/models_related/ultralytics/ultralytics/trackers/track.py b/models_related/ultralytics/ultralytics/trackers/track.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5539b96aa8f9794d51d32f567a1b6c98fe059d1
--- /dev/null
+++ b/models_related/ultralytics/ultralytics/trackers/track.py
@@ -0,0 +1,143 @@
+# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+
+from functools import partial
+from pathlib import Path
+
+import torch
+
+from models_related.ultralytics.ultralytics.utils import YAML, IterableSimpleNamespace
+from models_related.ultralytics.ultralytics.utils.checks import check_yaml
+
+from .bot_sort import BOTSORT
+from .byte_tracker import BYTETracker
+from .deep_oc_sort import DeepOCSORT
+from .fast_tracker import FASTTracker
+from .oc_sort import OCSORT
+from .track_tracker import TRACKTRACK
+
+# A mapping of tracker types to corresponding tracker classes
+TRACKER_MAP = {
+ "bytetrack": BYTETracker,
+ "botsort": BOTSORT,
+ "tracktrack": TRACKTRACK,
+ "fasttrack": FASTTracker,
+ "ocsort": OCSORT,
+ "deepocsort": DeepOCSORT,
+}
+
+
+def on_predict_start(predictor: object, persist: bool = False) -> None:
+ """Initialize trackers for object tracking during prediction.
+
+ Args:
+ predictor (ultralytics.engine.predictor.BasePredictor): The predictor object to initialize trackers for.
+ persist (bool, optional): Whether to reuse existing trackers if they are already attached.
+
+ Examples:
+ Initialize trackers for a predictor object
+ >>> predictor = SomePredictorClass()
+ >>> on_predict_start(predictor, persist=True)
+ """
+ if predictor.args.task == "classify":
+ raise ValueError("❌ Classification doesn't support 'mode=track'")
+
+ if hasattr(predictor, "trackers") and persist:
+ return
+
+ tracker = check_yaml(predictor.args.tracker)
+ cfg = IterableSimpleNamespace(**YAML.load(tracker))
+
+ if cfg.tracker_type not in TRACKER_MAP:
+ raise AssertionError(f"Only {sorted(TRACKER_MAP)} are supported for now, but got '{cfg.tracker_type}'")
+
+ predictor._feats = None # reset ReID pre-hook state
+ if hasattr(predictor, "_hook"):
+ predictor._hook.remove()
+ if hasattr(predictor, "_orig_postprocess"): # restore any raw-preds wrapper left by a prior TRACKTRACK run
+ predictor.postprocess = predictor._orig_postprocess
+ del predictor._orig_postprocess
+ if cfg.tracker_type in {"botsort", "tracktrack", "deepocsort"} and cfg.with_reid and cfg.model == "auto":
+ from models_related.ultralytics.ultralytics.nn.modules.head import Detect
+
+ if not (
+ isinstance(predictor.model.model, torch.nn.Module)
+ and isinstance(predictor.model.model.model[-1], Detect)
+ and not predictor.model.model.model[-1].end2end
+ ):
+ cfg.model = "yolo26n-cls.pt"
+ else:
+ # Register hook to extract input of Detect layer
+ def pre_hook(module, input):
+ predictor._feats = list(input[0]) # unroll to new list to avoid mutation in forward
+
+ predictor._hook = predictor.model.model.model[-1].register_forward_pre_hook(pre_hook)
+
+ trackers = []
+ for _ in range(predictor.dataset.bs):
+ tracker = TRACKER_MAP[cfg.tracker_type](args=cfg)
+ trackers.append(tracker)
+ if predictor.dataset.mode != "stream": # non-stream modes reuse a single tracker
+ break
+ predictor.trackers = trackers
+ predictor.vid_path = [None] * predictor.dataset.bs # used to reset the tracker when switching videos
+
+ tracker_cls = TRACKER_MAP[cfg.tracker_type]
+ if hasattr(tracker_cls, "setup_predictor"):
+ tracker_cls.setup_predictor(predictor)
+
+
+def on_predict_postprocess_end(predictor: object, persist: bool = False) -> None:
+ """Postprocess detected boxes and update with object tracking.
+
+ Args:
+ predictor (object): The predictor object containing the predictions.
+ persist (bool, optional): Whether to persist the trackers if they already exist.
+
+ Examples:
+ Postprocess predictions and update with tracking
+ >>> predictor = YourPredictorClass()
+ >>> on_predict_postprocess_end(predictor, persist=True)
+ """
+ is_obb = predictor.args.task == "obb"
+ is_stream = predictor.dataset.mode == "stream"
+
+ tracker_cls = type(predictor.trackers[0])
+ dets_del_list = (
+ tracker_cls.compute_frame_extras(predictor) if hasattr(tracker_cls, "compute_frame_extras") else None
+ )
+
+ for i, result in enumerate(predictor.results):
+ tracker = predictor.trackers[i if is_stream else 0]
+ vid_path = predictor.save_dir / Path(result.path).name
+ if not persist and predictor.vid_path[i if is_stream else 0] != vid_path:
+ tracker.reset()
+ predictor.vid_path[i if is_stream else 0] = vid_path
+
+ det = (result.obb if is_obb else result.boxes).cpu().numpy()
+ kwargs = {"feats": getattr(result, "feats", None)}
+ if dets_del_list is not None:
+ kwargs["dets_del"] = dets_del_list[i]
+ tracks = tracker.update(det, result.orig_img, **kwargs)
+ if len(tracks) == 0:
+ continue
+ idx = tracks[:, -1].astype(int)
+ predictor.results[i] = result[idx]
+
+ update_args = {"obb" if is_obb else "boxes": torch.as_tensor(tracks[:, :-1])}
+ predictor.results[i].update(**update_args)
+
+
+def register_tracker(model: object, persist: bool) -> None:
+ """Register tracking callbacks to the model for object tracking during prediction.
+
+ Args:
+ model (object): The model object to register tracking callbacks for.
+ persist (bool): Whether to persist the trackers if they already exist.
+
+ Examples:
+ Register tracking callbacks to a YOLO model
+ >>> model = YOLOModel()
+ >>> register_tracker(model, persist=True)
+ """
+ model.add_callback("on_predict_start", partial(on_predict_start, persist=persist))
+ model.add_callback("on_predict_postprocess_end", partial(on_predict_postprocess_end, persist=persist))
diff --git a/models_related/ultralytics/ultralytics/trackers/track_tracker.py b/models_related/ultralytics/ultralytics/trackers/track_tracker.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e8dfd1331b5f5c547362b8a0e1c3d53a0dd7811
--- /dev/null
+++ b/models_related/ultralytics/ultralytics/trackers/track_tracker.py
@@ -0,0 +1,585 @@
+# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+
+from __future__ import annotations
+
+from collections import deque
+from functools import wraps
+from typing import Any
+
+import numpy as np
+import scipy.linalg
+import torch
+
+from models_related.ultralytics.ultralytics.utils.metrics import bbox_ioa
+
+from ..utils import LOGGER
+from .basetrack import TrackState
+from .bot_sort import BOTrack
+from .utils.gmc import GMC
+from .utils.kalman_filter import KalmanFilterXYWH
+from .utils.reid import smooth_feature
+from .utils.stracks import joint_stracks, merge_track_pools, multi_gmc, parse_bboxes
+
+# Corner index arrays (LT, LB, RT, RB of an (x1,y1,x2,y2) box) for angle-distance vectorization.
+_CORNER_DX_IDX = np.array([0, 0, 2, 2])
+_CORNER_DY_IDX = np.array([1, 3, 1, 3])
+
+_LOOSE_NMS_IOU = 0.95 # looser NMS IoU used to recover detections the tight NMS dropped
+_LOOSE_NMS_DEDUP_IOU = 0.97 # IoU threshold to consider duplicate detections as "new"
+
+
+def _nsa_kalman_update(
+ kf: KalmanFilterXYWH, mean: np.ndarray, covariance: np.ndarray, measurement: np.ndarray, confidence: float
+) -> tuple[np.ndarray, np.ndarray]:
+ """Run a NSA-Kalman update (StrongSORT) that scales the measurement noise by (1 - confidence)."""
+ w = max(1.0 - float(confidence), 0.05)
+ std = kf._std_weight_position * mean[2:4]
+ R = np.diag(np.square(np.r_[std, std])) * w
+ H = kf._update_mat
+ projected_mean = H @ mean
+ projected_cov = np.linalg.multi_dot((H, covariance, H.T)) + R
+
+ chol, low = scipy.linalg.cho_factor(projected_cov, lower=True, check_finite=False)
+ gain = scipy.linalg.cho_solve((chol, low), np.dot(covariance, H.T).T, check_finite=False).T
+ innovation = measurement - projected_mean
+ new_mean = mean + innovation @ gain.T
+ new_cov = covariance - np.linalg.multi_dot((gain, projected_cov, gain.T))
+ return new_mean, new_cov
+
+
+def _hmiou_distance(tracks_a: list[TTSTrack], tracks_b: list[TTSTrack]) -> tuple[np.ndarray, np.ndarray]:
+ """Return (iou_sim, 1 - HMIoU) where HMIoU = HIoU * IoU and HIoU is vertical-overlap / vertical-union."""
+ n, m = len(tracks_a), len(tracks_b)
+ if n == 0 or m == 0:
+ return np.zeros((n, m), dtype=np.float32), np.ones((n, m), dtype=np.float32)
+ boxes_a = np.ascontiguousarray([track.xyxy for track in tracks_a], dtype=np.float32)
+ boxes_b = np.ascontiguousarray([track.xyxy for track in tracks_b], dtype=np.float32)
+ iou_sim = bbox_ioa(boxes_a, boxes_b, iou=True)
+ h_over = np.minimum(boxes_a[:, 3:4], boxes_b[:, 3:4].T) - np.maximum(boxes_a[:, 1:2], boxes_b[:, 1:2].T)
+ h_union = np.maximum(boxes_a[:, 3:4], boxes_b[:, 3:4].T) - np.minimum(boxes_a[:, 1:2], boxes_b[:, 1:2].T)
+ h_iou = np.clip(h_over / (h_union + 1e-9), 0, 1)
+ return iou_sim, 1.0 - h_iou * iou_sim
+
+
+def _angle_distance(tracks: list[TTSTrack], dets: list[TTSTrack], frame_id: int, delta_t: int = 3) -> np.ndarray:
+ """Return angle distance between each track's corner velocities and the track-to-detection direction."""
+ if len(tracks) == 0 or len(dets) == 0:
+ return np.ones((len(tracks), len(dets)), dtype=np.float32)
+ track_boxes = np.stack([track.get_history_box(frame_id, delta_t) for track in tracks]) # (N, 4)
+ det_boxes = np.stack([det.xyxy for det in dets]) # (M, 4)
+ deltas = det_boxes[None] - track_boxes[:, None] # (N, M, 4)
+ dx = deltas[:, :, _CORNER_DX_IDX]
+ dy = deltas[:, :, _CORNER_DY_IDX]
+ norms = np.sqrt(dx * dx + dy * dy) + 1e-5
+ dx /= norms
+ dy /= norms
+ track_velocities = np.stack([track.velocity for track in tracks]) # (N, 4, 2)
+ dot = track_velocities[:, None, :, 0] * dx + track_velocities[:, None, :, 1] * dy
+ dist = np.abs(np.arccos(np.clip(dot, -1, 1))).mean(axis=-1) / np.pi # (N, M)
+ return dist * np.array([det.score for det in dets])[None]
+
+
+def _confidence_distance(tracks: list[TTSTrack], dets: list[TTSTrack]) -> np.ndarray:
+ """Absolute difference between each track's projected score and each detection's confidence."""
+ if len(tracks) == 0 or len(dets) == 0:
+ return np.ones((len(tracks), len(dets)), dtype=np.float32)
+ track_prev_scores = np.array([track.prev_score for track in tracks])
+ track_curr_scores = np.array([track.score for track in tracks])
+ track_proj_scores = track_curr_scores + (track_curr_scores - track_prev_scores) # first-order extrapolation
+ det_scores = np.array([det.score for det in dets])
+ return np.abs(track_proj_scores[:, None] - det_scores[None])
+
+
+def _iterative_associate(cost: np.ndarray, match_thr: float, reduce_step: float = 0.05) -> tuple[list]:
+ """Greedy mutually-nearest matching with a threshold that shrinks each iteration.
+
+ Returns (matches, unmatched_tracks, unmatched_dets).
+ """
+ matches = []
+ cost = cost.copy()
+ while cost.shape[0] > 0 and cost.shape[1] > 0:
+ nearest_det = np.argmin(cost, axis=1)
+ nearest_track = np.argmin(cost, axis=0)
+ new_matches = [
+ [track_idx, nearest_det[track_idx]]
+ for track_idx in range(cost.shape[0])
+ if nearest_track[nearest_det[track_idx]] == track_idx
+ and cost[track_idx, nearest_det[track_idx]] < match_thr
+ ]
+ if not new_matches:
+ break
+ matches.extend(new_matches)
+ for track_idx, det_idx in new_matches:
+ cost[track_idx, :] = np.inf
+ cost[:, det_idx] = np.inf
+ match_thr -= reduce_step
+ matched_tracks = {track_idx for track_idx, _ in matches}
+ matched_dets = {det_idx for _, det_idx in matches}
+ unmatched_tracks = [i for i in range(cost.shape[0]) if i not in matched_tracks]
+ unmatched_dets = [i for i in range(cost.shape[1]) if i not in matched_dets]
+ return matches, unmatched_tracks, unmatched_dets
+
+
+def _track_aware_nms(
+ tracks: list[TTSTrack], dets: list[TTSTrack], tai_thr: float, new_track_thresh: float
+) -> list[bool]:
+ """TAI NMS: suppress detections that heavily overlap an existing track or a stronger detection."""
+ if not dets:
+ return []
+ scores = np.array([det.score for det in dets])
+ allow = scores > new_track_thresh
+ n_tracks, n_dets = len(tracks), len(dets)
+ if n_tracks + n_dets < 2:
+ return allow.tolist()
+ boxes = np.ascontiguousarray([obj.xyxy for obj in tracks + dets], dtype=np.float32)
+ iou = bbox_ioa(boxes, boxes, iou=True)
+
+ if n_tracks:
+ allow &= iou[n_tracks:, :n_tracks].max(axis=1) <= tai_thr
+
+ det_iou = iou[n_tracks:, n_tracks:]
+ order = scores.argsort()[::-1]
+ for i in order:
+ if not allow[i]:
+ continue
+ suppress = det_iou[i] > tai_thr
+ suppress[i] = False
+ allow[suppress] = False
+
+ return allow.tolist()
+
+
+def attach_raw_preds_hook(predictor) -> None:
+ """Wrap `predictor.postprocess` to capture raw pre-NMS predictions and inputs (idempotent)."""
+ if hasattr(predictor, "_orig_postprocess"):
+ return
+ orig = predictor.postprocess
+
+ @wraps(orig)
+ def _wrapped(preds, img, orig_imgs, *args, **kwargs):
+ # copy=True so the in-place NMS xywh->xyxy conversion can't mutate this captured tensor (CPU aliasing)
+ predictor._raw_preds = preds.detach().to("cpu", copy=True) if isinstance(preds, torch.Tensor) else preds
+ predictor._postprocess_im = img
+ predictor._postprocess_im0s = orig_imgs
+ return orig(preds, img, orig_imgs, *args, **kwargs)
+
+ predictor._orig_postprocess = orig
+ predictor.postprocess = _wrapped
+
+
+def compute_dets_del(predictor) -> list | None:
+ """Return per-batch `(xywh, conf, cls)` tuples for detections the tight NMS dropped, or None if unavailable."""
+ raw = getattr(predictor, "_raw_preds", None)
+ if raw is None or not isinstance(raw, torch.Tensor):
+ return None
+ from models_related.ultralytics.ultralytics.utils import ops
+ from models_related.ultralytics.ultralytics.utils.metrics import box_iou
+
+ loose_results = predictor._orig_postprocess(
+ raw, predictor._postprocess_im, predictor._postprocess_im0s, iou=_LOOSE_NMS_IOU
+ )
+
+ is_obb = predictor.args.task == "obb"
+ out = []
+ for loose, tight in zip(loose_results, predictor.results):
+ tight_boxes = tight.obb if is_obb else tight.boxes
+ loose_boxes = loose.obb if is_obb else loose.boxes
+ if len(loose_boxes) == 0 or len(tight_boxes) == 0:
+ out.append(None)
+ continue
+ max_iou = box_iou(loose_boxes.xyxy, tight_boxes.xyxy).max(dim=1).values
+ mask = max_iou < _LOOSE_NMS_DEDUP_IOU
+ if not mask.any():
+ out.append(None)
+ continue
+ dels = loose_boxes.data[mask].cpu()
+ if is_obb:
+ xywh = dels[:, :5].numpy() # xywhr
+ out.append((xywh, dels[:, 5].numpy(), dels[:, 6].numpy()))
+ else:
+ xywh = ops.xyxy2xywh(dels[:, :4]).numpy()
+ out.append((xywh, dels[:, 4].numpy(), dels[:, 5].numpy()))
+
+ predictor._raw_preds = None
+ return out
+
+
+def _cosine_distance(tracks: list[TTSTrack], dets: list[TTSTrack]) -> np.ndarray:
+ """Cosine distance in `[0, 1]` between track and detection embeddings; NaN where either side has no feature.
+
+ A NaN entry signals "no appearance evidence for this pair" so the caller falls back to motion rather than treating a
+ missing/occlusion-suppressed embedding as maximally dissimilar (which would penalize true matches).
+ """
+ if not tracks or not dets:
+ return np.ones((len(tracks), len(dets)), dtype=np.float32)
+ tfeat = [t.smooth_feat if t.smooth_feat is not None else t.curr_feat for t in tracks]
+ dfeat = [d.curr_feat for d in dets]
+ dim = next((f.shape[0] for f in (*tfeat, *dfeat) if f is not None), 128)
+ zeros = np.zeros(dim, dtype=np.float32)
+ T = np.stack([f if f is not None else zeros for f in tfeat])
+ D = np.stack([f if f is not None else zeros for f in dfeat])
+ valid = np.array([f is not None for f in tfeat])[:, None] & np.array([f is not None for f in dfeat])[None, :]
+ return np.where(valid, np.clip(1 - T @ D.T, 0, 1), np.nan).astype(np.float32)
+
+
+class TTSTrack(BOTrack):
+ """Single-object track for TrackTrack with corner velocity, score history, and ReID features.
+
+ Extends `BOTrack` (XYWH Kalman state and EMA ReID smoothing), adding corner-velocity motion, score history, and
+ score-adaptive feature smoothing.
+
+ Attributes:
+ min_track_len (int): Class-level default; overridden by TRACKTRACK from config.
+ kalman_filter (KalmanFilterXYWH): Per-track Kalman filter used after activation.
+ mean (np.ndarray): Mean state vector.
+ covariance (np.ndarray): Covariance matrix.
+ score (float): Current detection confidence.
+ prev_score (float): Confidence from the previous update (for score projection).
+ tracklet_len (int): Successful updates since activation.
+ velocity (np.ndarray): Per-corner (4,2) unit velocity vectors.
+ smooth_feat (np.ndarray | None): EMA-smoothed ReID embedding.
+ curr_feat (np.ndarray | None): Raw ReID embedding from the current frame.
+
+ Examples:
+ Create and activate a new track
+ >>> track = TTSTrack([100, 200, 50, 80, 0], score=0.9, cls="person")
+ >>> track.activate(KalmanFilterXYWH(), frame_id=1)
+ """
+
+ min_track_len = 3
+ _alpha = 0.95
+ _delta_t = 3
+
+ def __init__(self, xywh: np.ndarray, score: float, cls: Any, feat: np.ndarray | None = None):
+ """Initialize a TTSTrack from a detection bounding box.
+
+ Args:
+ xywh (np.ndarray): `(x, y, w, h, idx)` or `(x, y, w, h, angle, idx)`, center-based with detection index.
+ score (float): Detection confidence.
+ cls (Any): Class label.
+ feat (np.ndarray | None): Optional ReID feature vector.
+ """
+ super().__init__(xywh, score, cls) # BOTrack sets smooth_feat/curr_feat and the XYWH Kalman state
+ self.prev_score = score
+ self.velocity = np.zeros((4, 2), dtype=np.float32)
+ self._history: deque[tuple[int, np.ndarray]] = deque(maxlen=self._delta_t + 1)
+ if feat is not None:
+ self.update_features(feat)
+
+ def update_features(self, feat: np.ndarray) -> None:
+ """Normalize `feat` and blend it into `smooth_feat` via score-adaptive EMA."""
+ beta = self._alpha + (1 - self._alpha) * (1 - self.score)
+ curr, smooth = smooth_feature(feat, self.smooth_feat, beta)
+ if curr is not None:
+ self.curr_feat, self.smooth_feat = curr, smooth
+
+ def get_history_box(self, frame_id: int, dt: int) -> np.ndarray:
+ """Return the box from `dt` frames back, or the most recent box, or the current box."""
+ target = frame_id - dt
+ for fid, box in self._history:
+ if fid == target:
+ return box.copy()
+ if self._history:
+ return self._history[-1][1].copy()
+ return self.xyxy.copy()
+
+ def activate(self, kalman_filter: KalmanFilterXYWH, frame_id: int) -> None:
+ """Initialize Kalman state and promote to New state."""
+ self.kalman_filter = kalman_filter
+ self.track_id = self.next_id()
+ self.mean, self.covariance = kalman_filter.initiate(self.convert_coords(self._tlwh))
+ self._history.append((frame_id, self.xyxy.copy()))
+ self.tracklet_len = 0
+ self.state = TrackState.New
+ if frame_id == 1:
+ self.is_activated = True
+ self.frame_id = self.start_frame = frame_id
+
+ def re_activate(self, new_track, frame_id: int, new_id: bool = False) -> None:
+ """Rebind a lost track to a fresh detection via NSA-Kalman."""
+ self.prev_score = self.score
+ self.mean, self.covariance = _nsa_kalman_update(
+ self.kalman_filter, self.mean, self.covariance, self.convert_coords(new_track.tlwh), new_track.score
+ )
+ self._history.append((frame_id, self.xyxy.copy()))
+ self.score = new_track.score # set before update_features so the EMA weight uses the current confidence
+ if new_track.curr_feat is not None:
+ self.update_features(new_track.curr_feat)
+ self.tracklet_len = 0
+ self.state = TrackState.Tracked
+ self.is_activated = True
+ self.frame_id = frame_id
+ if new_id:
+ self.track_id = self.next_id()
+ self.cls, self.angle, self.idx = new_track.cls, new_track.angle, new_track.idx
+
+ def update(self, new_track, frame_id: int) -> None:
+ """Update a matched track with a new detection; promote to Tracked after min_track_len."""
+ self.frame_id = frame_id
+ self.tracklet_len += 1
+ self.prev_score = self.score
+ self.mean, self.covariance = _nsa_kalman_update(
+ self.kalman_filter, self.mean, self.covariance, self.convert_coords(new_track.tlwh), new_track.score
+ )
+ self._history.append((frame_id, new_track.xyxy.copy()))
+
+ velocity = np.zeros((4, 2), dtype=np.float32)
+ curr_box = new_track.xyxy
+ for dt in range(1, self._delta_t + 1):
+ delta = curr_box - self.get_history_box(frame_id, dt)
+ dx, dy = delta[_CORNER_DX_IDX], delta[_CORNER_DY_IDX]
+ norm = np.sqrt(dx * dx + dy * dy) + 1e-5
+ velocity += np.stack([dx / norm, dy / norm], axis=-1) / dt
+ self.velocity = velocity / self._delta_t
+
+ self.score = new_track.score # set before update_features so the EMA weight uses the current confidence
+ if new_track.curr_feat is not None:
+ self.update_features(new_track.curr_feat)
+
+ if self.state == TrackState.Tracked or self.tracklet_len >= self.min_track_len:
+ self.state = TrackState.Tracked
+ self.is_activated = True
+ self.cls, self.angle, self.idx = new_track.cls, new_track.angle, new_track.idx
+
+ def __repr__(self) -> str:
+ """Short string representation of the track."""
+ return f"TT_{self.track_id}_({self.start_frame}-{self.end_frame})"
+
+
+class TRACKTRACK:
+ """Multi-object tracker implementing Track-Perspective Association and Track-Aware Initialization.
+
+ Detections are partitioned into high, low, and deleted (loose-NMS recovered) sets, then matched against the union of
+ tracked and lost tracks using a multi-cue cost (HMIoU + cosine ReID + confidence + angle distance) solved with
+ iterative assignment. Unmatched still-Lost tracks may optionally be re-associated against leftover detections in a
+ relaxed second pass, and surviving leftover detections spawn new tracks via track-aware NMS.
+
+ Attributes:
+ tracked_stracks (list[TTSTrack]): Currently tracked tracks.
+ lost_stracks (list[TTSTrack]): Tracks that lost their detection but remain within the buffer window.
+ frame_id (int): Current frame index.
+ args (Any): Parsed tracker configuration.
+ max_time_lost (int): Frame budget before a lost track is removed (scaled to source frame rate).
+ kalman_filter (KalmanFilterXYWH): Kalman filter for new-track initialization.
+ match_thr (float): Cost gate for the main iterative assignment.
+ lost_match_thr (float): Cost gate for the optional relaxed lost-rebind pass; 0 disables it.
+ gmc (GMC): Global motion compensation for camera-motion warping.
+ encoder (Any): ReID encoder, or None when ReID is disabled.
+
+ Methods:
+ update: Advance the tracker by one frame and return per-object tracking results.
+ reset: Clear all tracker state.
+
+ Examples:
+ Initialize and run on a single frame
+ >>> tracker = TRACKTRACK(args)
+ >>> tracked_objects = tracker.update(yolo_results, img=image)
+ """
+
+ def __init__(self, args):
+ """Initialize TRACKTRACK from a tracker config (see `ultralytics/cfg/trackers/tracktrack.yaml`).
+
+ Args:
+ args (Any): Parsed tracker configuration. All knobs are read with `getattr(..., default)` so legacy YAMLs
+ missing recently added keys still load.
+ """
+ self.tracked_stracks: list[TTSTrack] = []
+ self.lost_stracks: list[TTSTrack] = []
+ self.removed_stracks: list[TTSTrack] = []
+ self.frame_id = 0
+ self.args = args
+ self.max_time_lost = args.track_buffer
+ self.kalman_filter = KalmanFilterXYWH()
+
+ self.match_thr = getattr(args, "match_thresh", 0.7)
+ self.lost_match_thr = getattr(args, "lost_match_thr", 0.0)
+ self.penalty_p = getattr(args, "penalty_p", 0.2)
+ self.penalty_q = getattr(args, "penalty_q", 0.4)
+ self.reduce_step = getattr(args, "reduce_step", 0.05)
+ self.iou_weight = getattr(args, "iou_weight", 0.5)
+ self.reid_weight = getattr(args, "reid_weight", 0.5)
+ self.conf_weight = getattr(args, "conf_weight", 0.1)
+ self.angle_weight = getattr(args, "angle_weight", 0.05)
+ self.tai_thr = getattr(args, "tai_thr", 0.55)
+ self.new_track_thresh = getattr(args, "new_track_thresh", 0.7)
+ self.min_track_len = getattr(args, "min_track_len", 3)
+
+ self.gmc = GMC(method=getattr(args, "gmc_method", "sparseOptFlow"))
+
+ from .utils.reid import build_encoder
+
+ self.encoder = build_encoder(getattr(args, "with_reid", False), getattr(args, "model", "auto"))
+
+ @classmethod
+ def setup_predictor(cls, predictor):
+ """Attach the raw-predictions hook for Track-Aware Initialization (detect/obb only).
+
+ Recovered (loose-NMS) detections are box-only and have no row in the post-NMS Results, so on segment/pose
+ tasks they cannot carry mask/keypoint data and would mis-index downstream; skip recovery (and its
+ per-frame overhead) for those tasks.
+ """
+ if predictor.args.task in {"detect", "obb"}:
+ attach_raw_preds_hook(predictor)
+
+ @classmethod
+ def compute_frame_extras(cls, predictor):
+ """Return per-batch ``(xywh, conf, cls)`` tuples for detections dropped by tight NMS."""
+ return compute_dets_del(predictor)
+
+ def _cost_matrix(self, tracks: list[TTSTrack], dets: list[TTSTrack]) -> np.ndarray:
+ """Return the multi-cue cost matrix (HMIoU + ReID + confidence + angle), gated by IoU support."""
+ iou_sim, hmiou_dist = _hmiou_distance(tracks, dets)
+ if self.encoder is not None:
+ cos = _cosine_distance(tracks, dets)
+ # Where appearance is missing (NaN: new track, or occlusion-suppressed detection), fall back to
+ # pure motion cost for that pair so the embedding neither helps nor penalizes it.
+ cost = np.where(np.isnan(cos), hmiou_dist, self.iou_weight * hmiou_dist + self.reid_weight * cos)
+ else:
+ cost = hmiou_dist
+ cost += self.conf_weight * _confidence_distance(tracks, dets)
+ cost += self.angle_weight * _angle_distance(tracks, dets, self.frame_id)
+ if iou_sim.size > 0:
+ cost[iou_sim <= 0.10] = 1.0
+ return np.clip(cost, 0, 1)
+
+ def _apply_gmc(self, img: np.ndarray, detections: list, pools: list[list[TTSTrack]]) -> None:
+ """Warp `pools` in place by the current GMC affine."""
+ try:
+ warp = self.gmc.apply(img, [det.xyxy for det in detections])
+ except Exception as e:
+ LOGGER.warning(f"GMC failed, falling back to identity: {e}")
+ warp = np.eye(2, 3)
+ for pool in pools:
+ multi_gmc(pool, warp)
+
+ def update(self, results, img: np.ndarray | None = None, dets_del=None, **kwargs) -> np.ndarray:
+ """Advance the tracker by one frame and return an `(N, 8)` array of `[x1, y1, x2, y2, id, score, cls, idx]`."""
+ self.frame_id += 1
+ activated, refind, lost, removed = [], [], [], []
+
+ scores = results.conf
+ boxes = parse_bboxes(results)
+ high_mask = scores >= self.args.track_high_thresh
+ low_mask = (scores > self.args.track_low_thresh) & (scores < self.args.track_high_thresh)
+
+ def _new_track(box, score, cls, feat=None):
+ track = TTSTrack(box, score, cls, feat) if feat is not None else TTSTrack(box, score, cls)
+ track.min_track_len = self.min_track_len
+ return track
+
+ high_boxes, high_scores, high_cls = boxes[high_mask], scores[high_mask], results.cls[high_mask]
+ feats = kwargs.get("feats")
+ use_native = getattr(self.args, "model", "auto") == "auto"
+ encoder_input = None
+ if self.encoder is not None and len(high_boxes) > 0:
+ if use_native:
+ encoder_input = feats[high_mask] if (feats is not None and len(feats)) else None
+ elif img is not None:
+ encoder_input = img
+
+ if encoder_input is not None:
+ features = self.encoder(encoder_input, high_boxes)
+ dets_high = [_new_track(b, s, c, f) for b, s, c, f in zip(high_boxes, high_scores, high_cls, features)]
+ else:
+ dets_high = [_new_track(b, s, c) for b, s, c in zip(high_boxes, high_scores, high_cls)]
+ dets_low = [_new_track(b, s, c) for b, s, c in zip(boxes[low_mask], scores[low_mask], results.cls[low_mask])]
+
+ dets_recovered: list[TTSTrack] = []
+ if dets_del is not None:
+ del_xywh, del_conf, del_cls = dets_del
+ mask = del_conf > self.args.track_high_thresh
+ if mask.any():
+ del_boxes = np.concatenate([del_xywh[mask], -np.ones((mask.sum(), 1))], axis=-1)
+ dets_recovered = [_new_track(b, s, c) for b, s, c in zip(del_boxes, del_conf[mask], del_cls[mask])]
+
+ unconfirmed, tracked = [], []
+ for track in self.tracked_stracks:
+ (unconfirmed if not track.is_activated else tracked).append(track)
+ pool = joint_stracks(tracked, self.lost_stracks)
+
+ if img is not None:
+ self._apply_gmc(img, dets_high, [pool, unconfirmed])
+ TTSTrack.multi_predict(pool)
+
+ # Main association: pool vs (high + low + recovered) detections, with per-bucket cost penalties.
+ all_dets = dets_high + dets_low + dets_recovered
+ n_high, n_low = len(dets_high), len(dets_low)
+ cost = self._cost_matrix(pool, all_dets)
+ if cost.shape[1] > n_high:
+ cost[:, n_high : n_high + n_low] += self.penalty_p
+ if dets_recovered:
+ cost[:, n_high + n_low :] += self.penalty_q
+ cost = np.clip(cost, 0, 1)
+
+ matches, unmatched_tracks, unmatched_dets = _iterative_associate(cost, self.match_thr, self.reduce_step)
+ for track_idx, det_idx in matches:
+ track, det = pool[track_idx], all_dets[det_idx]
+ if track.state == TrackState.Tracked:
+ track.update(det, self.frame_id)
+ activated.append(track)
+ else:
+ track.re_activate(det, self.frame_id, new_id=False)
+ refind.append(track)
+ for track_idx in unmatched_tracks:
+ track = pool[track_idx]
+ if track.state != TrackState.Lost:
+ track.mark_lost()
+ lost.append(track)
+
+ # Second association: unconfirmed tracks vs leftover high-confidence detections.
+ leftover = [all_dets[i] for i in unmatched_dets if i < n_high]
+ if unconfirmed and leftover:
+ uc_cost = self._cost_matrix(unconfirmed, leftover)
+ uc_matches, uc_unmatched_tracks, uc_unmatched_dets = _iterative_associate(
+ uc_cost, self.match_thr, self.reduce_step
+ )
+ for track_idx, det_idx in uc_matches:
+ unconfirmed[track_idx].update(leftover[det_idx], self.frame_id)
+ activated.append(unconfirmed[track_idx])
+ for track_idx in uc_unmatched_tracks:
+ unconfirmed[track_idx].mark_removed()
+ removed.append(unconfirmed[track_idx])
+ leftover = [leftover[i] for i in uc_unmatched_dets]
+ else:
+ for track in unconfirmed:
+ track.mark_removed()
+ removed.append(track)
+
+ # Optional relaxed rebind: still-Lost tracks vs leftover detections (disabled when lost_match_thr <= 0).
+ if self.lost_match_thr > 0 and leftover:
+ unmatched_lost = [t for t in pool if t.state == TrackState.Lost and t not in lost]
+ if unmatched_lost:
+ lost_cost = self._cost_matrix(unmatched_lost, leftover)
+ lost_matches, _, lost_unmatched = _iterative_associate(lost_cost, self.lost_match_thr, self.reduce_step)
+ for track_idx, det_idx in lost_matches:
+ unmatched_lost[track_idx].re_activate(leftover[det_idx], self.frame_id, new_id=False)
+ refind.append(unmatched_lost[track_idx])
+ leftover = [leftover[i] for i in lost_unmatched]
+
+ # TAI: spawn new tracks from leftover detections that survive NMS against existing tracks.
+ active = [track for track in self.tracked_stracks if track.state == TrackState.Tracked] + activated
+ for det, ok in zip(leftover, _track_aware_nms(active, leftover, self.tai_thr, self.new_track_thresh)):
+ if ok:
+ det.activate(self.kalman_filter, self.frame_id)
+ activated.append(det)
+
+ for track in self.lost_stracks:
+ if self.frame_id - track.end_frame > self.max_time_lost:
+ track.mark_removed()
+ removed.append(track)
+
+ merge_track_pools(self, activated, refind, lost, removed)
+ return np.asarray(
+ [track.result for track in self.tracked_stracks if track.is_activated and track.frame_id == self.frame_id],
+ dtype=np.float32,
+ )
+
+ def reset(self) -> None:
+ """Clear all tracker state including GMC warp history and the global ID counter."""
+ self.tracked_stracks = []
+ self.lost_stracks = []
+ self.removed_stracks = []
+ self.frame_id = 0
+ self.kalman_filter = KalmanFilterXYWH()
+ TTSTrack.reset_id()
+ self.gmc.reset_params()
diff --git a/models_related/ultralytics/ultralytics/trackers/utils/__init__.py b/models_related/ultralytics/ultralytics/trackers/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..77a19dcf0f8093de419453747db2e7e719f96349
--- /dev/null
+++ b/models_related/ultralytics/ultralytics/trackers/utils/__init__.py
@@ -0,0 +1 @@
+# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
diff --git a/models_related/ultralytics/ultralytics/trackers/utils/gmc.py b/models_related/ultralytics/ultralytics/trackers/utils/gmc.py
new file mode 100644
index 0000000000000000000000000000000000000000..875356d28b45571ee900bd3ab8c84bdf436f2ac4
--- /dev/null
+++ b/models_related/ultralytics/ultralytics/trackers/utils/gmc.py
@@ -0,0 +1,339 @@
+# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+
+from __future__ import annotations
+
+import copy
+
+import cv2
+import numpy as np
+
+from models_related.ultralytics.ultralytics.utils import LOGGER
+
+
+class GMC:
+ """Generalized Motion Compensation (GMC) class for tracking and object detection in video frames.
+
+ This class provides methods for tracking and detecting objects based on several tracking algorithms including ORB,
+ SIFT, ECC, and Sparse Optical Flow. It also supports downscaling of frames for computational efficiency.
+
+ Attributes:
+ method (str | None): The tracking method to use. Options include 'orb', 'sift', 'ecc', 'sparseOptFlow', None.
+ downscale (int): Factor by which to downscale the frames for processing.
+ prevFrame (np.ndarray | None): Previous frame for tracking.
+ prevKeyPoints (tuple | np.ndarray | None): Keypoints from the previous frame.
+ prevDescriptors (np.ndarray | None): Descriptors from the previous frame.
+ initializedFirstFrame (bool): Flag indicating if the first frame has been processed.
+
+ Methods:
+ apply: Apply the chosen method to a raw frame and optionally use provided detections.
+ apply_ecc: Apply the ECC algorithm to a raw frame.
+ apply_features: Apply feature-based methods like ORB or SIFT to a raw frame.
+ apply_sparseoptflow: Apply the Sparse Optical Flow method to a raw frame.
+ reset_params: Reset the internal parameters of the GMC object.
+
+ Examples:
+ Create a GMC object and apply it to a frame
+ >>> gmc = GMC(method="sparseOptFlow", downscale=2)
+ >>> frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
+ >>> warp = gmc.apply(frame)
+ >>> print(warp.shape)
+ (2, 3)
+ """
+
+ def __init__(self, method: str = "sparseOptFlow", downscale: int = 2) -> None:
+ """Initialize a Generalized Motion Compensation (GMC) object with tracking method and downscale factor.
+
+ Args:
+ method (str): The tracking method to use. Options include 'orb', 'sift', 'ecc', 'sparseOptFlow', 'none'.
+ downscale (int): Downscale factor for processing frames.
+ """
+ super().__init__()
+
+ self.method = method
+ self.downscale = max(1, downscale)
+
+ if self.method == "orb":
+ self.detector = cv2.FastFeatureDetector_create(20)
+ self.extractor = cv2.ORB_create()
+ self.matcher = cv2.BFMatcher(cv2.NORM_HAMMING)
+
+ elif self.method == "sift":
+ self.detector = cv2.SIFT_create(nOctaveLayers=3, contrastThreshold=0.02, edgeThreshold=20)
+ self.extractor = cv2.SIFT_create(nOctaveLayers=3, contrastThreshold=0.02, edgeThreshold=20)
+ self.matcher = cv2.BFMatcher(cv2.NORM_L2)
+
+ elif self.method == "ecc":
+ number_of_iterations = 5000
+ termination_eps = 1e-6
+ self.warp_mode = cv2.MOTION_EUCLIDEAN
+ self.criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, number_of_iterations, termination_eps)
+
+ elif self.method == "sparseOptFlow":
+ self.feature_params = dict(
+ maxCorners=1000, qualityLevel=0.01, minDistance=1, blockSize=3, useHarrisDetector=False, k=0.04
+ )
+
+ elif self.method in {"none", "None", None}:
+ self.method = None
+ else:
+ raise ValueError(f"Unknown GMC method: {method}")
+
+ self.prevFrame = None
+ self.prevKeyPoints = None
+ self.prevDescriptors = None
+ self.initializedFirstFrame = False
+
+ def apply(self, raw_frame: np.ndarray, detections: list | None = None) -> np.ndarray:
+ """Estimate a 2×3 motion compensation warp for a frame.
+
+ Args:
+ raw_frame (np.ndarray): The raw frame to be processed, with shape (H, W, C).
+ detections (list, optional): List of detections to be used in the processing.
+
+ Returns:
+ (np.ndarray): Transformation matrix with shape (2, 3).
+
+ Examples:
+ >>> gmc = GMC(method="sparseOptFlow")
+ >>> raw_frame = np.random.rand(480, 640, 3)
+ >>> transformation_matrix = gmc.apply(raw_frame)
+ >>> print(transformation_matrix.shape)
+ (2, 3)
+ """
+ if self.method in {"orb", "sift"}:
+ return self.apply_features(raw_frame, detections)
+ elif self.method == "ecc":
+ return self.apply_ecc(raw_frame)
+ elif self.method == "sparseOptFlow":
+ return self.apply_sparseoptflow(raw_frame)
+ else:
+ return np.eye(2, 3)
+
+ def apply_ecc(self, raw_frame: np.ndarray) -> np.ndarray:
+ """Apply the ECC (Enhanced Correlation Coefficient) algorithm to a raw frame for motion compensation.
+
+ Args:
+ raw_frame (np.ndarray): The raw frame to be processed, with shape (H, W, C).
+
+ Returns:
+ (np.ndarray): Transformation matrix with shape (2, 3).
+
+ Examples:
+ >>> gmc = GMC(method="ecc")
+ >>> processed_frame = gmc.apply_ecc(np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]))
+ >>> print(processed_frame)
+ [[1. 0. 0.]
+ [0. 1. 0.]]
+ """
+ height, width, c = raw_frame.shape
+ frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY) if c == 3 else raw_frame
+ H = np.eye(2, 3, dtype=np.float32)
+
+ # Downscale image for computational efficiency
+ if self.downscale > 1.0:
+ frame = cv2.GaussianBlur(frame, (3, 3), 1.5)
+ frame = cv2.resize(frame, (width // self.downscale, height // self.downscale))
+
+ # Handle first frame initialization
+ if not self.initializedFirstFrame:
+ self.prevFrame = frame.copy()
+ self.initializedFirstFrame = True
+ return H
+
+ # Run the ECC algorithm to find transformation matrix
+ try:
+ (_, H) = cv2.findTransformECC(self.prevFrame, frame, H, self.warp_mode, self.criteria, None, 1)
+ except Exception as e:
+ LOGGER.warning(f"findTransformECC failed; using identity warp. {e}")
+
+ return H
+
+ def apply_features(self, raw_frame: np.ndarray, detections: list | None = None) -> np.ndarray:
+ """Apply feature-based methods like ORB or SIFT to a raw frame.
+
+ Args:
+ raw_frame (np.ndarray): The raw frame to be processed, with shape (H, W, C).
+ detections (list, optional): List of detections to be used in the processing.
+
+ Returns:
+ (np.ndarray): Transformation matrix with shape (2, 3).
+
+ Examples:
+ >>> gmc = GMC(method="orb")
+ >>> raw_frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
+ >>> transformation_matrix = gmc.apply_features(raw_frame)
+ >>> print(transformation_matrix.shape)
+ (2, 3)
+ """
+ height, width, c = raw_frame.shape
+ frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY) if c == 3 else raw_frame
+ H = np.eye(2, 3)
+
+ # Downscale image for computational efficiency
+ if self.downscale > 1.0:
+ frame = cv2.resize(frame, (width // self.downscale, height // self.downscale))
+ width = width // self.downscale
+ height = height // self.downscale
+
+ # Create mask for keypoint detection, excluding border regions
+ mask = np.zeros_like(frame)
+ mask[int(0.02 * height) : int(0.98 * height), int(0.02 * width) : int(0.98 * width)] = 255
+
+ # Exclude detection regions from mask to avoid tracking detected objects
+ if detections is not None:
+ for det in detections:
+ tlbr = (det[:4] / self.downscale).astype(np.int_)
+ mask[tlbr[1] : tlbr[3], tlbr[0] : tlbr[2]] = 0
+
+ # Find keypoints and compute descriptors
+ keypoints = self.detector.detect(frame, mask)
+ keypoints, descriptors = self.extractor.compute(frame, keypoints)
+
+ # Handle first frame initialization
+ if not self.initializedFirstFrame:
+ self.prevFrame = frame.copy()
+ self.prevKeyPoints = copy.copy(keypoints)
+ self.prevDescriptors = copy.copy(descriptors)
+ self.initializedFirstFrame = True
+ return H
+
+ # Match descriptors between previous and current frame
+ knnMatches = self.matcher.knnMatch(self.prevDescriptors, descriptors, 2)
+
+ # Filter matches based on spatial distance constraints
+ matches = []
+ spatialDistances = []
+ maxSpatialDistance = 0.25 * np.array([width, height])
+
+ # Handle empty matches case
+ if len(knnMatches) == 0:
+ self.prevFrame = frame.copy()
+ self.prevKeyPoints = copy.copy(keypoints)
+ self.prevDescriptors = copy.copy(descriptors)
+ return H
+
+ # Apply Lowe's ratio test and spatial distance filtering
+ for m, n in knnMatches:
+ if m.distance < 0.9 * n.distance:
+ prevKeyPointLocation = self.prevKeyPoints[m.queryIdx].pt
+ currKeyPointLocation = keypoints[m.trainIdx].pt
+
+ spatialDistance = (
+ prevKeyPointLocation[0] - currKeyPointLocation[0],
+ prevKeyPointLocation[1] - currKeyPointLocation[1],
+ )
+
+ if (np.abs(spatialDistance[0]) < maxSpatialDistance[0]) and (
+ np.abs(spatialDistance[1]) < maxSpatialDistance[1]
+ ):
+ spatialDistances.append(spatialDistance)
+ matches.append(m)
+
+ # Filter outliers using statistical analysis
+ meanSpatialDistances = np.mean(spatialDistances, 0)
+ stdSpatialDistances = np.std(spatialDistances, 0)
+ inliers = (spatialDistances - meanSpatialDistances) < 2.5 * stdSpatialDistances
+
+ # Extract good matches and corresponding points
+ goodMatches = []
+ prevPoints = []
+ currPoints = []
+ for i in range(len(matches)):
+ if inliers[i, 0] and inliers[i, 1]:
+ goodMatches.append(matches[i])
+ prevPoints.append(self.prevKeyPoints[matches[i].queryIdx].pt)
+ currPoints.append(keypoints[matches[i].trainIdx].pt)
+
+ prevPoints = np.array(prevPoints)
+ currPoints = np.array(currPoints)
+
+ # Estimate transformation matrix using RANSAC
+ if prevPoints.shape[0] > 4:
+ H, inliers = cv2.estimateAffinePartial2D(prevPoints, currPoints, cv2.RANSAC)
+
+ # Scale translation components back to original resolution
+ if self.downscale > 1.0:
+ H[0, 2] *= self.downscale
+ H[1, 2] *= self.downscale
+ else:
+ LOGGER.warning("not enough matching points")
+
+ # Store current frame data for next iteration
+ self.prevFrame = frame.copy()
+ self.prevKeyPoints = copy.copy(keypoints)
+ self.prevDescriptors = copy.copy(descriptors)
+
+ return H
+
+ def apply_sparseoptflow(self, raw_frame: np.ndarray) -> np.ndarray:
+ """Apply Sparse Optical Flow method to a raw frame.
+
+ Args:
+ raw_frame (np.ndarray): The raw frame to be processed, with shape (H, W, C).
+
+ Returns:
+ (np.ndarray): Transformation matrix with shape (2, 3).
+
+ Examples:
+ >>> gmc = GMC()
+ >>> result = gmc.apply_sparseoptflow(np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]))
+ >>> print(result)
+ [[1. 0. 0.]
+ [0. 1. 0.]]
+ """
+ height, width, c = raw_frame.shape
+ frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY) if c == 3 else raw_frame
+ H = np.eye(2, 3)
+
+ # Downscale image for computational efficiency
+ if self.downscale > 1.0:
+ frame = cv2.resize(frame, (width // self.downscale, height // self.downscale))
+
+ # Find good features to track
+ keypoints = cv2.goodFeaturesToTrack(frame, mask=None, **self.feature_params)
+
+ # Handle first frame initialization
+ if not self.initializedFirstFrame or self.prevKeyPoints is None:
+ self.prevFrame = frame.copy()
+ self.prevKeyPoints = copy.copy(keypoints)
+ self.initializedFirstFrame = True
+ return H
+
+ # Calculate optical flow using Lucas-Kanade method
+ matchedKeypoints, status, _ = cv2.calcOpticalFlowPyrLK(self.prevFrame, frame, self.prevKeyPoints, None)
+
+ # Extract successfully tracked points
+ prevPoints = []
+ currPoints = []
+
+ for i in range(len(status)):
+ if status[i]:
+ prevPoints.append(self.prevKeyPoints[i])
+ currPoints.append(matchedKeypoints[i])
+
+ prevPoints = np.array(prevPoints)
+ currPoints = np.array(currPoints)
+
+ # Estimate transformation matrix using RANSAC
+ if (prevPoints.shape[0] > 4) and (prevPoints.shape[0] == currPoints.shape[0]):
+ H, _ = cv2.estimateAffinePartial2D(prevPoints, currPoints, cv2.RANSAC)
+
+ # Scale translation components back to original resolution
+ if self.downscale > 1.0:
+ H[0, 2] *= self.downscale
+ H[1, 2] *= self.downscale
+ else:
+ LOGGER.warning("not enough matching points")
+
+ # Store current frame data for next iteration
+ self.prevFrame = frame.copy()
+ self.prevKeyPoints = copy.copy(keypoints)
+
+ return H
+
+ def reset_params(self) -> None:
+ """Reset the internal parameters including previous frame, keypoints, and descriptors."""
+ self.prevFrame = None
+ self.prevKeyPoints = None
+ self.prevDescriptors = None
+ self.initializedFirstFrame = False
diff --git a/models_related/ultralytics/ultralytics/trackers/utils/kalman_filter.py b/models_related/ultralytics/ultralytics/trackers/utils/kalman_filter.py
new file mode 100644
index 0000000000000000000000000000000000000000..49f44f7a7a52cc444031198500a5d80d92e2c675
--- /dev/null
+++ b/models_related/ultralytics/ultralytics/trackers/utils/kalman_filter.py
@@ -0,0 +1,476 @@
+# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+
+import numpy as np
+
+
+class KalmanFilterXYAH:
+ """A KalmanFilterXYAH class for tracking bounding boxes in image space using a Kalman filter.
+
+ Implements a simple Kalman filter for tracking bounding boxes in image space. The 8-dimensional state space (x, y,
+ a, h, vx, vy, va, vh) contains the bounding box center position (x, y), aspect ratio a, height h, and their
+ respective velocities. Object motion follows a constant velocity model, and bounding box location (x, y, a, h) is
+ taken as a direct observation of the state space (linear observation model).
+
+ Attributes:
+ _motion_mat (np.ndarray): The motion matrix for the Kalman filter.
+ _update_mat (np.ndarray): The update matrix for the Kalman filter.
+ _std_weight_position (float): Standard deviation weight for position.
+ _std_weight_velocity (float): Standard deviation weight for velocity.
+
+ Methods:
+ initiate: Create a track from an unassociated measurement.
+ predict: Run the Kalman filter prediction step.
+ project: Project the state distribution to measurement space.
+ multi_predict: Run the Kalman filter prediction step (vectorized version).
+ update: Run the Kalman filter correction step.
+ gating_distance: Compute the gating distance between state distribution and measurements.
+
+ Examples:
+ Initialize the Kalman filter and create a track from a measurement
+ >>> kf = KalmanFilterXYAH()
+ >>> measurement = np.array([100, 200, 1.5, 50])
+ >>> mean, covariance = kf.initiate(measurement)
+ >>> print(mean)
+ >>> print(covariance)
+ """
+
+ def __init__(self):
+ """Initialize Kalman filter model matrices with motion and observation uncertainty weights.
+
+ The Kalman filter is initialized with an 8-dimensional state space (x, y, a, h, vx, vy, va, vh), where (x, y)
+ represents the bounding box center position, 'a' is the aspect ratio, 'h' is the height, and their respective
+ velocities are (vx, vy, va, vh). The filter uses a constant velocity model for object motion and a linear
+ observation model for bounding box location.
+ """
+ ndim, dt = 4, 1.0
+
+ # Create Kalman filter model matrices
+ self._motion_mat = np.eye(2 * ndim, 2 * ndim)
+ for i in range(ndim):
+ self._motion_mat[i, ndim + i] = dt
+ self._update_mat = np.eye(ndim, 2 * ndim)
+
+ # Motion and observation uncertainty are chosen relative to the current state estimate
+ self._std_weight_position = 1.0 / 20
+ self._std_weight_velocity = 1.0 / 160
+
+ def initiate(self, measurement: np.ndarray):
+ """Create a track from an unassociated measurement.
+
+ Args:
+ measurement (np.ndarray): Bounding box coordinates (x, y, a, h) with center position (x, y), aspect ratio a,
+ and height h.
+
+ Returns:
+ mean (np.ndarray): Mean vector (8-dimensional) of the new track. Unobserved velocities are initialized to 0.
+ covariance (np.ndarray): Covariance matrix (8x8 dimensional) of the new track.
+
+ Examples:
+ >>> kf = KalmanFilterXYAH()
+ >>> measurement = np.array([100, 50, 1.5, 200])
+ >>> mean, covariance = kf.initiate(measurement)
+ """
+ mean_pos = measurement
+ mean_vel = np.zeros_like(mean_pos)
+ mean = np.r_[mean_pos, mean_vel]
+
+ std = [
+ 2 * self._std_weight_position * measurement[3],
+ 2 * self._std_weight_position * measurement[3],
+ 1e-2,
+ 2 * self._std_weight_position * measurement[3],
+ 10 * self._std_weight_velocity * measurement[3],
+ 10 * self._std_weight_velocity * measurement[3],
+ 1e-5,
+ 10 * self._std_weight_velocity * measurement[3],
+ ]
+ covariance = np.diag(np.square(std))
+ return mean, covariance
+
+ def predict(self, mean: np.ndarray, covariance: np.ndarray):
+ """Run Kalman filter prediction step.
+
+ Args:
+ mean (np.ndarray): The 8-dimensional mean vector of the object state at the previous time step.
+ covariance (np.ndarray): The 8x8-dimensional covariance matrix of the object state at the previous time
+ step.
+
+ Returns:
+ mean (np.ndarray): Mean vector of the predicted state.
+ covariance (np.ndarray): Covariance matrix of the predicted state.
+
+ Examples:
+ >>> kf = KalmanFilterXYAH()
+ >>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0])
+ >>> covariance = np.eye(8)
+ >>> predicted_mean, predicted_covariance = kf.predict(mean, covariance)
+ """
+ std_pos = [
+ self._std_weight_position * mean[3],
+ self._std_weight_position * mean[3],
+ 1e-2,
+ self._std_weight_position * mean[3],
+ ]
+ std_vel = [
+ self._std_weight_velocity * mean[3],
+ self._std_weight_velocity * mean[3],
+ 1e-5,
+ self._std_weight_velocity * mean[3],
+ ]
+ motion_cov = np.diag(np.square(np.r_[std_pos, std_vel]))
+
+ mean = np.dot(mean, self._motion_mat.T)
+ covariance = np.linalg.multi_dot((self._motion_mat, covariance, self._motion_mat.T)) + motion_cov
+
+ return mean, covariance
+
+ def project(self, mean: np.ndarray, covariance: np.ndarray):
+ """Project state distribution to measurement space.
+
+ Args:
+ mean (np.ndarray): The state's mean vector (8 dimensional array).
+ covariance (np.ndarray): The state's covariance matrix (8x8 dimensional).
+
+ Returns:
+ mean (np.ndarray): Projected mean of the given state estimate.
+ covariance (np.ndarray): Projected covariance matrix of the given state estimate.
+
+ Examples:
+ >>> kf = KalmanFilterXYAH()
+ >>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0])
+ >>> covariance = np.eye(8)
+ >>> projected_mean, projected_covariance = kf.project(mean, covariance)
+ """
+ std = [
+ self._std_weight_position * mean[3],
+ self._std_weight_position * mean[3],
+ 1e-1,
+ self._std_weight_position * mean[3],
+ ]
+ innovation_cov = np.diag(np.square(std))
+
+ mean = np.dot(self._update_mat, mean)
+ covariance = np.linalg.multi_dot((self._update_mat, covariance, self._update_mat.T))
+ return mean, covariance + innovation_cov
+
+ def multi_predict(self, mean: np.ndarray, covariance: np.ndarray):
+ """Run Kalman filter prediction step for multiple object states (Vectorized version).
+
+ Args:
+ mean (np.ndarray): The Nx8 dimensional mean matrix of the object states at the previous time step.
+ covariance (np.ndarray): The Nx8x8 covariance matrix of the object states at the previous time step.
+
+ Returns:
+ mean (np.ndarray): Mean matrix of the predicted states with shape (N, 8).
+ covariance (np.ndarray): Covariance matrix of the predicted states with shape (N, 8, 8).
+
+ Examples:
+ >>> kf = KalmanFilterXYAH()
+ >>> mean = np.random.rand(10, 8) # 10 object states
+ >>> covariance = np.random.rand(10, 8, 8) # Covariance matrices for 10 object states
+ >>> predicted_mean, predicted_covariance = kf.multi_predict(mean, covariance)
+ """
+ std_pos = [
+ self._std_weight_position * mean[:, 3],
+ self._std_weight_position * mean[:, 3],
+ 1e-2 * np.ones_like(mean[:, 3]),
+ self._std_weight_position * mean[:, 3],
+ ]
+ std_vel = [
+ self._std_weight_velocity * mean[:, 3],
+ self._std_weight_velocity * mean[:, 3],
+ 1e-5 * np.ones_like(mean[:, 3]),
+ self._std_weight_velocity * mean[:, 3],
+ ]
+ sqr = np.square(np.r_[std_pos, std_vel]).T
+
+ motion_cov = [np.diag(sqr[i]) for i in range(len(mean))]
+ motion_cov = np.asarray(motion_cov)
+
+ mean = np.dot(mean, self._motion_mat.T)
+ left = np.dot(self._motion_mat, covariance).transpose((1, 0, 2))
+ covariance = np.dot(left, self._motion_mat.T) + motion_cov
+
+ return mean, covariance
+
+ def update(self, mean: np.ndarray, covariance: np.ndarray, measurement: np.ndarray):
+ """Run Kalman filter correction step.
+
+ Args:
+ mean (np.ndarray): The predicted state's mean vector (8 dimensional).
+ covariance (np.ndarray): The state's covariance matrix (8x8 dimensional).
+ measurement (np.ndarray): The 4 dimensional measurement vector (x, y, a, h), where (x, y) is the center
+ position, a the aspect ratio, and h the height of the bounding box.
+
+ Returns:
+ new_mean (np.ndarray): Measurement-corrected state mean.
+ new_covariance (np.ndarray): Measurement-corrected state covariance.
+
+ Examples:
+ >>> kf = KalmanFilterXYAH()
+ >>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0])
+ >>> covariance = np.eye(8)
+ >>> measurement = np.array([1, 1, 1, 1])
+ >>> new_mean, new_covariance = kf.update(mean, covariance, measurement)
+ """
+ projected_mean, projected_cov = self.project(mean, covariance)
+
+ kalman_gain = np.linalg.solve(projected_cov, np.dot(covariance, self._update_mat.T).T).T
+ innovation = measurement - projected_mean
+
+ new_mean = mean + np.dot(innovation, kalman_gain.T)
+ new_covariance = covariance - np.linalg.multi_dot((kalman_gain, projected_cov, kalman_gain.T))
+ return new_mean, new_covariance
+
+ def gating_distance(
+ self,
+ mean: np.ndarray,
+ covariance: np.ndarray,
+ measurements: np.ndarray,
+ only_position: bool = False,
+ metric: str = "maha",
+ ) -> np.ndarray:
+ """Compute gating distance between state distribution and measurements.
+
+ A suitable distance threshold can be obtained from `chi2inv95`. If `only_position` is False, the chi-square
+ distribution has 4 degrees of freedom, otherwise 2.
+
+ Args:
+ mean (np.ndarray): Mean vector over the state distribution (8 dimensional).
+ covariance (np.ndarray): Covariance of the state distribution (8x8 dimensional).
+ measurements (np.ndarray): An (N, 4) matrix of N measurements, each in format (x, y, a, h) where (x, y) is
+ the bounding box center position, a the aspect ratio, and h the height.
+ only_position (bool, optional): If True, distance computation is done with respect to box center position
+ only.
+ metric (str, optional): The metric to use for calculating the distance. Options are 'gaussian' for the
+ squared Euclidean distance and 'maha' for the squared Mahalanobis distance.
+
+ Returns:
+ (np.ndarray): Returns an array of length N, where the i-th element contains the squared distance between
+ (mean, covariance) and `measurements[i]`.
+
+ Examples:
+ Compute gating distance using Mahalanobis metric:
+ >>> kf = KalmanFilterXYAH()
+ >>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0])
+ >>> covariance = np.eye(8)
+ >>> measurements = np.array([[1, 1, 1, 1], [2, 2, 1, 1]])
+ >>> distances = kf.gating_distance(mean, covariance, measurements, only_position=False, metric="maha")
+ """
+ mean, covariance = self.project(mean, covariance)
+ if only_position:
+ mean, covariance = mean[:2], covariance[:2, :2]
+ measurements = measurements[:, :2]
+
+ d = measurements - mean
+ if metric == "gaussian":
+ return np.sum(d * d, axis=1)
+ elif metric == "maha":
+ cholesky_factor = np.linalg.cholesky(covariance)
+ z = np.linalg.solve(cholesky_factor, d.T)
+ return np.sum(z * z, axis=0) # square maha
+ else:
+ raise ValueError("Invalid distance metric")
+
+
+class KalmanFilterXYWH(KalmanFilterXYAH):
+ """A KalmanFilterXYWH class for tracking bounding boxes in image space using a Kalman filter.
+
+ Implements a Kalman filter for tracking bounding boxes with state space (x, y, w, h, vx, vy, vw, vh), where (x, y)
+ is the center position, w is the width, h is the height, and vx, vy, vw, vh are their respective velocities. The
+ object motion follows a constant velocity model, and the bounding box location (x, y, w, h) is taken as a direct
+ observation of the state space (linear observation model).
+
+ Attributes:
+ _motion_mat (np.ndarray): The motion matrix for the Kalman filter.
+ _update_mat (np.ndarray): The update matrix for the Kalman filter.
+ _std_weight_position (float): Standard deviation weight for position.
+ _std_weight_velocity (float): Standard deviation weight for velocity.
+
+ Methods:
+ initiate: Create a track from an unassociated measurement.
+ predict: Run the Kalman filter prediction step.
+ project: Project the state distribution to measurement space.
+ multi_predict: Run the Kalman filter prediction step in a vectorized manner.
+ update: Run the Kalman filter correction step.
+
+ Examples:
+ Create a Kalman filter and initialize a track
+ >>> kf = KalmanFilterXYWH()
+ >>> measurement = np.array([100, 50, 20, 40])
+ >>> mean, covariance = kf.initiate(measurement)
+ >>> print(mean)
+ >>> print(covariance)
+ """
+
+ def initiate(self, measurement: np.ndarray):
+ """Create track from unassociated measurement.
+
+ Args:
+ measurement (np.ndarray): Bounding box coordinates (x, y, w, h) with center position (x, y), width, and
+ height.
+
+ Returns:
+ mean (np.ndarray): Mean vector (8 dimensional) of the new track. Unobserved velocities are initialized to 0.
+ covariance (np.ndarray): Covariance matrix (8x8 dimensional) of the new track.
+
+ Examples:
+ >>> kf = KalmanFilterXYWH()
+ >>> measurement = np.array([100, 50, 20, 40])
+ >>> mean, covariance = kf.initiate(measurement)
+ >>> print(mean)
+ [100. 50. 20. 40. 0. 0. 0. 0.]
+ >>> print(covariance)
+ [[ 4. 0. 0. 0. 0. 0. 0. 0. ]
+ [ 0. 16. 0. 0. 0. 0. 0. 0. ]
+ [ 0. 0. 4. 0. 0. 0. 0. 0. ]
+ [ 0. 0. 0. 16. 0. 0. 0. 0. ]
+ [ 0. 0. 0. 0. 1.5625 0. 0. 0. ]
+ [ 0. 0. 0. 0. 0. 6.25 0. 0. ]
+ [ 0. 0. 0. 0. 0. 0. 1.5625 0. ]
+ [ 0. 0. 0. 0. 0. 0. 0. 6.25 ]]
+ """
+ mean_pos = measurement
+ mean_vel = np.zeros_like(mean_pos)
+ mean = np.r_[mean_pos, mean_vel]
+
+ std = [
+ 2 * self._std_weight_position * measurement[2],
+ 2 * self._std_weight_position * measurement[3],
+ 2 * self._std_weight_position * measurement[2],
+ 2 * self._std_weight_position * measurement[3],
+ 10 * self._std_weight_velocity * measurement[2],
+ 10 * self._std_weight_velocity * measurement[3],
+ 10 * self._std_weight_velocity * measurement[2],
+ 10 * self._std_weight_velocity * measurement[3],
+ ]
+ covariance = np.diag(np.square(std))
+ return mean, covariance
+
+ def predict(self, mean: np.ndarray, covariance: np.ndarray):
+ """Run Kalman filter prediction step.
+
+ Args:
+ mean (np.ndarray): The 8-dimensional mean vector of the object state at the previous time step.
+ covariance (np.ndarray): The 8x8-dimensional covariance matrix of the object state at the previous time
+ step.
+
+ Returns:
+ mean (np.ndarray): Mean vector of the predicted state.
+ covariance (np.ndarray): Covariance matrix of the predicted state.
+
+ Examples:
+ >>> kf = KalmanFilterXYWH()
+ >>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0])
+ >>> covariance = np.eye(8)
+ >>> predicted_mean, predicted_covariance = kf.predict(mean, covariance)
+ """
+ std_pos = [
+ self._std_weight_position * mean[2],
+ self._std_weight_position * mean[3],
+ self._std_weight_position * mean[2],
+ self._std_weight_position * mean[3],
+ ]
+ std_vel = [
+ self._std_weight_velocity * mean[2],
+ self._std_weight_velocity * mean[3],
+ self._std_weight_velocity * mean[2],
+ self._std_weight_velocity * mean[3],
+ ]
+ motion_cov = np.diag(np.square(np.r_[std_pos, std_vel]))
+
+ mean = np.dot(mean, self._motion_mat.T)
+ covariance = np.linalg.multi_dot((self._motion_mat, covariance, self._motion_mat.T)) + motion_cov
+
+ return mean, covariance
+
+ def project(self, mean: np.ndarray, covariance: np.ndarray):
+ """Project state distribution to measurement space.
+
+ Args:
+ mean (np.ndarray): The state's mean vector (8 dimensional array).
+ covariance (np.ndarray): The state's covariance matrix (8x8 dimensional).
+
+ Returns:
+ mean (np.ndarray): Projected mean of the given state estimate.
+ covariance (np.ndarray): Projected covariance matrix of the given state estimate.
+
+ Examples:
+ >>> kf = KalmanFilterXYWH()
+ >>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0])
+ >>> covariance = np.eye(8)
+ >>> projected_mean, projected_cov = kf.project(mean, covariance)
+ """
+ std = [
+ self._std_weight_position * mean[2],
+ self._std_weight_position * mean[3],
+ self._std_weight_position * mean[2],
+ self._std_weight_position * mean[3],
+ ]
+ innovation_cov = np.diag(np.square(std))
+
+ mean = np.dot(self._update_mat, mean)
+ covariance = np.linalg.multi_dot((self._update_mat, covariance, self._update_mat.T))
+ return mean, covariance + innovation_cov
+
+ def multi_predict(self, mean: np.ndarray, covariance: np.ndarray):
+ """Run Kalman filter prediction step (Vectorized version).
+
+ Args:
+ mean (np.ndarray): The Nx8 dimensional mean matrix of the object states at the previous time step.
+ covariance (np.ndarray): The Nx8x8 covariance matrix of the object states at the previous time step.
+
+ Returns:
+ mean (np.ndarray): Mean matrix of the predicted states with shape (N, 8).
+ covariance (np.ndarray): Covariance matrix of the predicted states with shape (N, 8, 8).
+
+ Examples:
+ >>> mean = np.random.rand(5, 8) # 5 objects with 8-dimensional state vectors
+ >>> covariance = np.random.rand(5, 8, 8) # 5 objects with 8x8 covariance matrices
+ >>> kf = KalmanFilterXYWH()
+ >>> predicted_mean, predicted_covariance = kf.multi_predict(mean, covariance)
+ """
+ std_pos = [
+ self._std_weight_position * mean[:, 2],
+ self._std_weight_position * mean[:, 3],
+ self._std_weight_position * mean[:, 2],
+ self._std_weight_position * mean[:, 3],
+ ]
+ std_vel = [
+ self._std_weight_velocity * mean[:, 2],
+ self._std_weight_velocity * mean[:, 3],
+ self._std_weight_velocity * mean[:, 2],
+ self._std_weight_velocity * mean[:, 3],
+ ]
+ sqr = np.square(np.r_[std_pos, std_vel]).T
+
+ motion_cov = [np.diag(sqr[i]) for i in range(len(mean))]
+ motion_cov = np.asarray(motion_cov)
+
+ mean = np.dot(mean, self._motion_mat.T)
+ left = np.dot(self._motion_mat, covariance).transpose((1, 0, 2))
+ covariance = np.dot(left, self._motion_mat.T) + motion_cov
+
+ return mean, covariance
+
+ def update(self, mean: np.ndarray, covariance: np.ndarray, measurement: np.ndarray):
+ """Run Kalman filter correction step.
+
+ Args:
+ mean (np.ndarray): The predicted state's mean vector (8 dimensional).
+ covariance (np.ndarray): The state's covariance matrix (8x8 dimensional).
+ measurement (np.ndarray): The 4 dimensional measurement vector (x, y, w, h), where (x, y) is the center
+ position, w the width, and h the height of the bounding box.
+
+ Returns:
+ new_mean (np.ndarray): Measurement-corrected state mean.
+ new_covariance (np.ndarray): Measurement-corrected state covariance.
+
+ Examples:
+ >>> kf = KalmanFilterXYWH()
+ >>> mean = np.array([0, 0, 1, 1, 0, 0, 0, 0])
+ >>> covariance = np.eye(8)
+ >>> measurement = np.array([0.5, 0.5, 1.2, 1.2])
+ >>> new_mean, new_covariance = kf.update(mean, covariance, measurement)
+ """
+ return super().update(mean, covariance, measurement)
diff --git a/models_related/ultralytics/ultralytics/trackers/utils/matching.py b/models_related/ultralytics/ultralytics/trackers/utils/matching.py
new file mode 100644
index 0000000000000000000000000000000000000000..7624af3a45195b52abb07df97af7f58a9ae7d9b0
--- /dev/null
+++ b/models_related/ultralytics/ultralytics/trackers/utils/matching.py
@@ -0,0 +1,173 @@
+# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+
+import numpy as np
+
+from models_related.ultralytics.ultralytics.utils.metrics import batch_probiou, bbox_ioa
+
+try:
+ import lap # for linear_assignment
+
+ assert lap.__version__ # verify package is not directory
+except (ImportError, AssertionError, AttributeError):
+ from models_related.ultralytics.ultralytics.utils.checks import check_requirements
+
+ check_requirements("lap>=0.5.12") # https://github.com/gatagat/lap
+ import lap
+
+
+def linear_assignment(cost_matrix: np.ndarray, thresh: float, use_lap: bool = True):
+ """Perform linear assignment using either the scipy or lap.lapjv method.
+
+ Args:
+ cost_matrix (np.ndarray): The matrix containing cost values for assignments, with shape (N, M).
+ thresh (float): Threshold for considering an assignment valid.
+ use_lap (bool): Use lap.lapjv for the assignment. If False, scipy.optimize.linear_sum_assignment is used.
+
+ Returns:
+ matched_indices (list[list[int]] | np.ndarray): Matched indices of shape (K, 2), where K is the number of
+ matches.
+ unmatched_a (tuple | list | np.ndarray): Unmatched indices from the first set.
+ unmatched_b (tuple | list | np.ndarray): Unmatched indices from the second set.
+
+ Examples:
+ >>> cost_matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+ >>> thresh = 5.0
+ >>> matched_indices, unmatched_a, unmatched_b = linear_assignment(cost_matrix, thresh, use_lap=True)
+ """
+ if cost_matrix.size == 0:
+ return np.empty((0, 2), dtype=int), tuple(range(cost_matrix.shape[0])), tuple(range(cost_matrix.shape[1]))
+
+ if use_lap:
+ # Use lap.lapjv
+ # https://github.com/gatagat/lap
+ _, x, y = lap.lapjv(cost_matrix, extend_cost=True, cost_limit=thresh)
+ matches = [[ix, mx] for ix, mx in enumerate(x) if mx >= 0]
+ unmatched_a = np.where(x < 0)[0]
+ unmatched_b = np.where(y < 0)[0]
+ else:
+ # Use scipy.optimize.linear_sum_assignment
+ # https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linear_sum_assignment.html
+ from scipy.optimize import linear_sum_assignment
+
+ x, y = linear_sum_assignment(cost_matrix) # row x, col y
+ matches = np.asarray([[x[i], y[i]] for i in range(len(x)) if cost_matrix[x[i], y[i]] <= thresh])
+ if len(matches) == 0:
+ unmatched_a = list(np.arange(cost_matrix.shape[0]))
+ unmatched_b = list(np.arange(cost_matrix.shape[1]))
+ else:
+ unmatched_a = list(frozenset(np.arange(cost_matrix.shape[0])) - frozenset(matches[:, 0]))
+ unmatched_b = list(frozenset(np.arange(cost_matrix.shape[1])) - frozenset(matches[:, 1]))
+
+ return matches, unmatched_a, unmatched_b
+
+
+def iou_distance(atracks: list, btracks: list) -> np.ndarray:
+ """Compute cost based on Intersection over Union (IoU) between tracks.
+
+ Args:
+ atracks (list[STrack] | list[np.ndarray]): List of tracks 'a' or bounding boxes.
+ btracks (list[STrack] | list[np.ndarray]): List of tracks 'b' or bounding boxes.
+
+ Returns:
+ (np.ndarray): Cost matrix computed based on IoU with shape (len(atracks), len(btracks)).
+
+ Examples:
+ Compute IoU distance between two sets of tracks
+ >>> atracks = [np.array([0, 0, 10, 10]), np.array([20, 20, 30, 30])]
+ >>> btracks = [np.array([5, 5, 15, 15]), np.array([25, 25, 35, 35])]
+ >>> cost_matrix = iou_distance(atracks, btracks)
+ """
+ if (atracks and isinstance(atracks[0], np.ndarray)) or (btracks and isinstance(btracks[0], np.ndarray)):
+ atlbrs = atracks
+ btlbrs = btracks
+ else:
+ atlbrs = [track.xywha if track.angle is not None else track.xyxy for track in atracks]
+ btlbrs = [track.xywha if track.angle is not None else track.xyxy for track in btracks]
+
+ ious = np.zeros((len(atlbrs), len(btlbrs)), dtype=np.float32)
+ if len(atlbrs) and len(btlbrs):
+ if len(atlbrs[0]) == 5 and len(btlbrs[0]) == 5:
+ ious = batch_probiou(
+ np.ascontiguousarray(atlbrs, dtype=np.float32),
+ np.ascontiguousarray(btlbrs, dtype=np.float32),
+ ).numpy()
+ else:
+ ious = bbox_ioa(
+ np.ascontiguousarray(atlbrs, dtype=np.float32),
+ np.ascontiguousarray(btlbrs, dtype=np.float32),
+ iou=True,
+ )
+ return 1 - ious # cost matrix
+
+
+def embedding_distance(tracks: list, detections: list, metric: str = "cosine") -> np.ndarray:
+ """Compute distance between tracks and detections based on embeddings.
+
+ Args:
+ tracks (list[BOTrack]): List of tracks, where each track contains embedding features.
+ detections (list[BOTrack]): List of detections, where each detection contains embedding features.
+ metric (str): Metric for distance computation. Supported metrics include 'cosine', 'euclidean', etc.
+
+ Returns:
+ (np.ndarray): Cost matrix computed based on embeddings with shape (N, M), where N is the number of tracks and M
+ is the number of detections.
+
+ Examples:
+ Compute the embedding distance between tracks and detections using cosine metric
+ >>> tracks = [BOTrack(...), BOTrack(...)] # List of track objects with embedding features
+ >>> detections = [BOTrack(...), BOTrack(...)] # List of detection objects with embedding features
+ >>> cost_matrix = embedding_distance(tracks, detections, metric="cosine")
+ """
+ cost_matrix = np.zeros((len(tracks), len(detections)), dtype=np.float32)
+ if cost_matrix.size == 0:
+ return cost_matrix
+ # A zero-norm embedding is skipped upstream, leaving curr_feat/smooth_feat None. Stack a zero placeholder so the
+ # array isn't ragged, then (below) force any missing-feature pair to the maximum distance so callers ignore
+ # appearance and fall back to motion/IoU rather than crashing or treating it as a partial match.
+ track_feats = [t.smooth_feat for t in tracks]
+ det_feats = [d.curr_feat for d in detections]
+ feat_dim = next((len(f) for f in (*track_feats, *det_feats) if f is not None), 0)
+ zeros = np.zeros(feat_dim, dtype=np.float32)
+ track_features = np.asarray([f if f is not None else zeros for f in track_feats], dtype=np.float32)
+ det_features = np.asarray([f if f is not None else zeros for f in det_feats], dtype=np.float32)
+ if metric == "cosine":
+ track_norm = np.linalg.norm(track_features, axis=1, keepdims=True)
+ det_norm = np.linalg.norm(det_features, axis=1, keepdims=True).T
+ cost_matrix = 1 - track_features @ det_features.T / np.maximum(track_norm * det_norm, np.finfo(float).eps)
+ else:
+ from scipy.spatial.distance import cdist
+
+ cost_matrix = cdist(track_features, det_features, metric)
+ cost_matrix = np.maximum(0.0, cost_matrix) # Normalized features
+ missing_t = [i for i, f in enumerate(track_feats) if f is None]
+ missing_d = [j for j, f in enumerate(det_feats) if f is None]
+ if missing_t:
+ cost_matrix[missing_t] = 2.0 # max cosine distance -> caller's /2 then appearance gate ignores the pair
+ if missing_d:
+ cost_matrix[:, missing_d] = 2.0
+ return cost_matrix
+
+
+def fuse_score(cost_matrix: np.ndarray, detections: list) -> np.ndarray:
+ """Fuse cost matrix with detection scores to produce a single cost matrix.
+
+ Args:
+ cost_matrix (np.ndarray): The matrix containing cost values for assignments, with shape (N, M).
+ detections (list[BaseTrack]): List of detections, each containing a score attribute.
+
+ Returns:
+ (np.ndarray): Fused cost matrix with shape (N, M).
+
+ Examples:
+ Fuse a cost matrix with detection scores
+ >>> cost_matrix = np.random.rand(5, 10) # 5 tracks and 10 detections
+ >>> detections = [BaseTrack(score=np.random.rand()) for _ in range(10)]
+ >>> fused_matrix = fuse_score(cost_matrix, detections)
+ """
+ if cost_matrix.size == 0:
+ return cost_matrix
+ iou_sim = 1 - cost_matrix
+ det_scores = np.array([det.score for det in detections])
+ det_scores = det_scores[None].repeat(cost_matrix.shape[0], axis=0)
+ fuse_sim = iou_sim * det_scores
+ return 1 - fuse_sim # fuse_cost
diff --git a/models_related/ultralytics/ultralytics/trackers/utils/reid.py b/models_related/ultralytics/ultralytics/trackers/utils/reid.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdd5c753bafeafc08e3e4f21bc238ee1e85a6cb9
--- /dev/null
+++ b/models_related/ultralytics/ultralytics/trackers/utils/reid.py
@@ -0,0 +1,165 @@
+# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""Shared ReID encoder used by BoT-SORT, Deep OC-SORT, and TrackTrack.
+
+* `.pt` YOLO checkpoints — loaded via `YOLO()`; embeddings are pulled from the second-to-last
+layer through the predictor's `embed=[...]` argument (works with classification and ReID
+backbones).
+* Any other extension (`.torchscript`, `.onnx`, `.engine`, `.openvino`, …) — loaded via
+`AutoBackend`; the model is expected to output the embedding tensor directly.
+"""
+
+from __future__ import annotations
+
+import numpy as np
+import torch
+
+from models_related.ultralytics.ultralytics.nn.autobackend import AutoBackend
+from models_related.ultralytics.ultralytics.utils.ops import xywh2xyxy
+from models_related.ultralytics.ultralytics.utils.plotting import save_one_box
+
+REID_ASSETS = frozenset(f"yolo26{k}-reid.onnx" for k in "nsmlx")
+
+
+class ReID:
+ """ReID encoder. Routes `.pt` to the YOLO predictor path; everything else to `AutoBackend`."""
+
+ def __init__(self, model: str, imgsz: int = 224, device: str | torch.device | None = None, fp16: bool = False):
+ """Initialize encoder for re-identification.
+
+ Args:
+ model (str): Path to a ReID model. `.pt` runs through the YOLO predictor (embed-layer extraction); other
+ extensions go through `AutoBackend`.
+ imgsz (int): Square input size used for crop preprocessing on the AutoBackend path. Overridden by the
+ model's own static input size when one is detected.
+ device (str | torch.device | None): Inference device; defaults to CUDA if available.
+ fp16 (bool): Use half precision when the backend supports it.
+ """
+ self.imgsz = imgsz
+ self.batch_size = None
+ self.device = (
+ torch.device(device) if device is not None else torch.device("cuda" if torch.cuda.is_available() else "cpu")
+ )
+ self.is_pt = str(model).endswith(".pt")
+
+ if self.is_pt:
+ from models_related.ultralytics.ultralytics import YOLO
+
+ self.model = YOLO(model)
+ # Initialize predictor with embed=[idx] so subsequent calls return embeddings.
+ self.model(embed=[len(self.model.model.model) - 2], verbose=False, save=False)
+ self.fp16 = False
+ else:
+ from pathlib import Path
+
+ if Path(str(model)).name in REID_ASSETS:
+ from models_related.ultralytics.ultralytics.utils.downloads import attempt_download_asset
+
+ model = attempt_download_asset(str(model))
+ self.model = AutoBackend(str(model), device=self.device, fp16=fp16, verbose=False)
+ self.fp16 = self.model.fp16
+
+ # Get model's input size for a fixed batch and crop size or detect dynamic batch and crop sizes.
+ session = getattr(self.model, "session", None)
+ shape = session.get_inputs()[0].shape if session is not None else ()
+ if len(shape) == 4:
+ if isinstance(shape[0], int) and shape[0] > 0:
+ self.batch_size = shape[0]
+ if isinstance(shape[2], int) and shape[2] > 0:
+ self.imgsz = shape[2]
+
+ @staticmethod
+ def _crop_detections(img: np.ndarray, dets: np.ndarray) -> list[np.ndarray]:
+ """Crop detection regions from image, converting xywh to xyxy first.
+
+ Args:
+ img (np.ndarray): BGR image.
+ dets (np.ndarray): Detections in xywh format (first 4 columns used).
+
+ Returns:
+ (list[np.ndarray]): Cropped image patches.
+ """
+ return [save_one_box(det, img, save=False) for det in xywh2xyxy(torch.from_numpy(dets[:, :4]))]
+
+ def _crops_to_tensor(self, img: np.ndarray, dets: np.ndarray) -> torch.Tensor:
+ """Crop detections from img and stack into a normalized BCHW float tensor at self.imgsz."""
+ crops = self._crop_detections(img, dets)
+ batch = torch.empty(len(crops), 3, self.imgsz, self.imgsz, dtype=torch.float32)
+ for i, c in enumerate(crops):
+ t = torch.from_numpy(np.ascontiguousarray(c[..., ::-1])).permute(2, 0, 1).unsqueeze(0).float() / 255.0
+ batch[i] = torch.nn.functional.interpolate(
+ t, size=(self.imgsz, self.imgsz), mode="bilinear", align_corners=False
+ )[0]
+ batch = batch.to(self.device)
+ return batch.half() if self.fp16 else batch
+
+ @torch.no_grad()
+ def __call__(self, img: np.ndarray, dets: np.ndarray) -> list[np.ndarray]:
+ """Extract embeddings for detected objects."""
+ if self.is_pt:
+ crops = self._crop_detections(img, dets)
+ feats = self.model.predictor(crops)
+ if len(feats) != dets.shape[0] and feats[0].shape[0] == dets.shape[0]:
+ feats = feats[0] # batched prediction with non-PyTorch backend
+ return [f.cpu().numpy() for f in feats]
+ batch = self._crops_to_tensor(img, dets)
+ bs, n = self.batch_size, batch.shape[0]
+ if bs is None or n == bs:
+ feats = self.model(batch)
+ else: # fixed-batch model (e.g. static ONNX): run in chunks of bs, padding the last partial chunk
+ outs = []
+ for s in range(0, n, bs):
+ chunk = batch[s : s + bs]
+ if chunk.shape[0] < bs:
+ chunk = torch.cat([chunk, chunk[-1:].expand(bs - chunk.shape[0], *chunk.shape[1:])], 0)
+ outs.append(self.model(chunk))
+ feats = torch.cat(outs, 0)[:n]
+ return [f.cpu().numpy() for f in feats]
+
+
+def build_encoder(with_reid: bool, model: str | None):
+ """Return a ReID encoder, the native-features pass-through, or None.
+
+ Args:
+ with_reid (bool): Whether ReID is enabled at all.
+ model (str | None): `"auto"` returns a callable that converts pre-extracted backbone features to numpy arrays;
+ any other value loads a `ReID` model from that path. Ignored when `with_reid` is False.
+
+ Returns:
+ (Callable | None): A `(img, dets) -> list[np.ndarray]` encoder, or None when ReID is disabled.
+ """
+ if not with_reid:
+ return None
+ if model == "auto":
+
+ def _auto_encoder(feats, _dets):
+ if isinstance(feats, np.ndarray):
+ return [f for f in feats]
+ return [f.cpu().numpy() for f in feats]
+
+ return _auto_encoder
+ return ReID(model)
+
+
+def smooth_feature(
+ feat: np.ndarray, smooth: np.ndarray | None, alpha: float
+) -> tuple[np.ndarray | None, np.ndarray | None]:
+ """L2-normalize `feat` and blend it into `smooth` via exponential moving average.
+
+ Args:
+ feat (np.ndarray): New (un-normalized) appearance feature.
+ smooth (np.ndarray | None): Current smoothed feature, or None on the first update.
+ alpha (float): EMA weight on the existing `smooth` (``1.0`` keeps it unchanged).
+
+ Returns:
+ curr (np.ndarray | None): The normalized current feature, or None when `feat` is zero-norm (carries no
+ appearance information, so the caller should leave its features unchanged).
+ smooth (np.ndarray | None): The updated, renormalized smoothed feature.
+ """
+ norm = np.linalg.norm(feat)
+ if norm < 1e-12: # zero-norm feature has no appearance info; signal the caller to keep its current features
+ return None, smooth
+ feat = feat / norm
+ if smooth is None:
+ return feat, feat.copy()
+ smooth = alpha * smooth + (1 - alpha) * feat
+ return feat, smooth / np.linalg.norm(smooth)
diff --git a/models_related/ultralytics/ultralytics/trackers/utils/stracks.py b/models_related/ultralytics/ultralytics/trackers/utils/stracks.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c1ceaee1638061bef30e522d9bd55bb0535f0df
--- /dev/null
+++ b/models_related/ultralytics/ultralytics/trackers/utils/stracks.py
@@ -0,0 +1,175 @@
+# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""Shared helpers for operating on lists of track objects across trackers.
+
+These functions are intentionally generic: they only touch attributes that every track
+implementation exposes (`track_id`, `frame_id`, `start_frame`, `xyxy`, `mean`, `covariance`).
+"""
+
+from __future__ import annotations
+
+__all__ = ("joint_stracks", "merge_track_pools", "multi_gmc", "parse_bboxes", "remove_duplicate_stracks", "sub_stracks")
+
+import numpy as np
+
+from ..basetrack import TrackState
+from . import matching
+
+
+def merge_track_pools(
+ tracker,
+ activated: list,
+ refind: list,
+ lost: list,
+ removed: list,
+ removed_buffer: int = 1000,
+) -> None:
+ """Apply the standard end-of-frame bookkeeping to a tracker's persistent pools in place.
+
+ Merges newly activated and re-found tracks into `tracker.tracked_stracks`, moves the transitioned tracks into
+ `tracker.lost_stracks`, dedups by IoU, appends removals to `tracker.removed_stracks`, and trims the removed buffer
+ to `removed_buffer` entries.
+
+ Args:
+ tracker (Any): Object exposing `tracked_stracks`, `lost_stracks`, `removed_stracks` lists.
+ activated (list): Tracks updated from the Tracked state this frame.
+ refind (list): Tracks re-activated from the Lost state this frame.
+ lost (list): Tracks transitioned to Lost this frame.
+ removed (list): Tracks transitioned to Removed this frame.
+ removed_buffer (int): Maximum number of historical removed tracks to retain.
+
+ Examples:
+ Run end-of-frame bookkeeping inside a tracker's `update` method
+ >>> merge_track_pools(self, activated_stracks, refind_stracks, lost_stracks, removed_stracks)
+ """
+ tracker.tracked_stracks = [t for t in tracker.tracked_stracks if t.state == TrackState.Tracked]
+ tracker.tracked_stracks = joint_stracks(tracker.tracked_stracks, activated)
+ tracker.tracked_stracks = joint_stracks(tracker.tracked_stracks, refind)
+ tracker.lost_stracks = sub_stracks(tracker.lost_stracks, tracker.tracked_stracks)
+ tracker.lost_stracks.extend(lost)
+ tracker.lost_stracks = sub_stracks(tracker.lost_stracks, tracker.removed_stracks)
+ tracker.tracked_stracks, tracker.lost_stracks = remove_duplicate_stracks(
+ tracker.tracked_stracks, tracker.lost_stracks
+ )
+ tracker.removed_stracks.extend(removed)
+ if len(tracker.removed_stracks) > removed_buffer:
+ tracker.removed_stracks = tracker.removed_stracks[-removed_buffer:]
+
+
+def parse_bboxes(results) -> np.ndarray:
+ """Return detection bounding boxes with appended indices from a Results-like object.
+
+ Args:
+ results (Any): Object exposing ``xywh`` (or ``xywhr``), ``conf``, and ``cls``.
+
+ Returns:
+ (np.ndarray): Array of shape ``(N, 5)`` for ``xywh`` or ``(N, 6)`` for ``xywhr``, with the last column
+ containing the original detection index.
+ """
+ bboxes = results.xywhr if hasattr(results, "xywhr") else results.xywh
+ return np.concatenate([bboxes, np.arange(len(bboxes)).reshape(-1, 1)], axis=-1)
+
+
+def joint_stracks(atracks: list, btracks: list) -> list:
+ """Combine two track lists into one, de-duplicating by `track_id`.
+
+ Args:
+ atracks (list[STrack]): First list of tracks; entries win on `track_id` collisions.
+ btracks (list[STrack]): Second list of tracks.
+
+ Returns:
+ (list[STrack]): Union of `atracks` and `btracks` with duplicate `track_id`s removed.
+
+ Examples:
+ Merge the currently tracked pool with newly activated tracks
+ >>> merged = joint_stracks(tracked_stracks, activated_stracks)
+ """
+ a_ids = {t.track_id for t in atracks}
+ return atracks + [t for t in btracks if t.track_id not in a_ids]
+
+
+def sub_stracks(atracks: list, btracks: list) -> list:
+ """Filter out tracks from `atracks` whose `track_id` appears in `btracks`.
+
+ Args:
+ atracks (list[STrack]): Source list of tracks to filter.
+ btracks (list[STrack]): Tracks whose `track_id`s should be excluded from the output.
+
+ Returns:
+ (list[STrack]): Elements of `atracks` whose `track_id` is not present in `btracks`.
+
+ Examples:
+ Remove any re-tracked objects from the lost pool
+ >>> lost_stracks = sub_stracks(lost_stracks, tracked_stracks)
+ """
+ btrack_ids = {t.track_id for t in btracks}
+ return [t for t in atracks if t.track_id not in btrack_ids]
+
+
+def remove_duplicate_stracks(atracks: list, btracks: list, dup_thresh: float = 0.15) -> tuple[list, list]:
+ """Remove duplicate tracks across two lists based on Intersection over Union (IoU) distance.
+
+ Track pairs with IoU distance < `dup_thresh` (IoU > `1 - dup_thresh`) are treated as duplicates of the same
+ object. The shorter-lived track (smaller `frame_id - start_frame`) is dropped; ties drop
+ from `atracks`.
+
+ Args:
+ atracks (list[STrack]): First list of tracks; entries must expose `xyxy`, `frame_id`, and `start_frame`.
+ btracks (list[STrack]): Second list of tracks with the same attribute requirements.
+ dup_thresh (float): IoU-distance ceiling for treating two tracks as duplicates. Default 0.15 (IoU > 0.85).
+
+ Returns:
+ resa (list[STrack]): `atracks` with duplicate tracks removed.
+ resb (list[STrack]): `btracks` with duplicate tracks removed.
+
+ Examples:
+ De-duplicate the tracked and lost pools at the end of a frame
+ >>> tracked, lost = remove_duplicate_stracks(tracked_stracks, lost_stracks)
+ """
+ pdist = matching.iou_distance(atracks, btracks)
+ pairs = np.where(pdist < dup_thresh)
+ dupa, dupb = [], []
+ for p, q in zip(*pairs):
+ timep = atracks[p].frame_id - atracks[p].start_frame
+ timeq = btracks[q].frame_id - btracks[q].start_frame
+ if timep > timeq:
+ dupb.append(q)
+ else:
+ dupa.append(p)
+ dupa_set, dupb_set = set(dupa), set(dupb)
+ resa = [t for i, t in enumerate(atracks) if i not in dupa_set]
+ resb = [t for i, t in enumerate(btracks) if i not in dupb_set]
+ return resa, resb
+
+
+def multi_gmc(stracks: list, H: np.ndarray) -> None:
+ """Update multiple track positions and covariances using a 2x3 affine homography.
+
+ The Kalman state is assumed to be laid out as `(*box, *box_velocity)` with the box center `(x, y)` in the first two
+ dims. `R8x8` rotates all four 2-d pairs block-diagonally; the translation `t` is applied only to the position.
+ This assumes the state layout is four spatial/velocity pairs (e.g. XYWH); XYAH trackers must override this.
+
+ Args:
+ stracks (list[STrack]): Tracks to warp in place; each must expose `mean` (shape (8,)) and `covariance` (shape
+ (8, 8)).
+ H (np.ndarray): 2x3 affine homography mapping the previous frame to the current one.
+
+ Examples:
+ Apply camera-motion compensation to the active track pool
+ >>> warp = gmc.apply(frame, detection_boxes)
+ >>> multi_gmc(tracked_stracks, warp)
+ """
+ if not stracks:
+ return
+ multi_mean = np.asarray([st.mean.copy() for st in stracks])
+ multi_covariance = np.asarray([st.covariance for st in stracks])
+
+ R = H[:2, :2]
+ R8x8 = np.kron(np.eye(4, dtype=np.float32), R)
+ t = H[:2, 2]
+
+ for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):
+ mean = R8x8.dot(mean)
+ mean[:2] += t
+ cov = R8x8.dot(cov).dot(R8x8.transpose())
+ stracks[i].mean = mean
+ stracks[i].covariance = cov
diff --git a/models_related/ultralytics/ultralytics/utils/__init__.py b/models_related/ultralytics/ultralytics/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a99af46090fa393f63cdcc41ebf444dd8953f3d
--- /dev/null
+++ b/models_related/ultralytics/ultralytics/utils/__init__.py
@@ -0,0 +1,1497 @@
+# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+
+from __future__ import annotations
+
+import contextlib
+import importlib.metadata
+import inspect
+import json
+import logging
+import os
+import platform
+import re
+import socket
+import sys
+import threading
+import time
+import warnings
+from functools import lru_cache
+from pathlib import Path
+from threading import Lock
+from types import SimpleNamespace
+from urllib.parse import unquote
+
+import cv2
+import numpy as np
+import torch
+
+from models_related.ultralytics.ultralytics import __version__
+from models_related.ultralytics.ultralytics.utils.git import GitRepo
+from models_related.ultralytics.ultralytics.utils.patches import imread, imshow, imwrite, torch_save # for patches
+from models_related.ultralytics.ultralytics.utils.tqdm import TQDM # noqa
+
+# PyTorch Multi-GPU DDP Constants
+RANK = int(os.getenv("RANK", -1))
+LOCAL_RANK = int(os.getenv("LOCAL_RANK", -1)) # https://pytorch.org/docs/stable/elastic/run.html
+
+# Other Constants
+ARGV = sys.argv or ["", ""] # sometimes sys.argv = []
+FILE = Path(__file__).resolve()
+ROOT = FILE.parents[1] # YOLO
+ASSETS = ROOT / "assets" # default images
+ASSETS_URL = "https://github.com/ultralytics/assets/releases/download/v0.0.0" # assets GitHub URL
+DEFAULT_CFG_PATH = ROOT / "cfg/default.yaml"
+NUM_THREADS = min(8, max(1, os.cpu_count() - 1)) # number of YOLO multiprocessing threads
+AUTOINSTALL = str(os.getenv("YOLO_AUTOINSTALL", True)).lower() == "true" # global auto-install mode
+VERBOSE = str(os.getenv("YOLO_VERBOSE", True)).lower() == "true" # global verbose mode
+SAFE_LOAD = str(os.getenv("ULTRALYTICS_SAFE_LOAD", False)).lower() == "true" # opt-in weights_only model loading
+LOGGING_NAME = "ultralytics"
+MACOS, LINUX, WINDOWS = (platform.system() == x for x in ["Darwin", "Linux", "Windows"]) # environment booleans
+MACOS_VERSION = platform.mac_ver()[0] if MACOS else None
+NOT_MACOS14 = not (MACOS and MACOS_VERSION.startswith("14."))
+ARM64 = platform.machine() in {"arm64", "aarch64"} # ARM64 booleans
+PYTHON_VERSION = platform.python_version()
+TORCH_VERSION = str(torch.__version__) # Normalize torch.__version__ (PyTorch>1.9 returns TorchVersion objects)
+TORCHVISION_VERSION = importlib.metadata.version("torchvision") # faster than importing torchvision
+IS_VSCODE = os.environ.get("TERM_PROGRAM", False) == "vscode"
+RKNN_CHIPS = frozenset(
+ {
+ "rk3588",
+ "rk3576",
+ "rk3566",
+ "rk3568",
+ "rk3562",
+ "rv1103",
+ "rv1106",
+ "rv1103b",
+ "rv1106b",
+ "rk2118",
+ "rv1126b",
+ }
+) # Rockchip processors available for export
+QNN_HTP_ARCHS = frozenset(
+ {
+ "68", # Snapdragon 888
+ "69", # Snapdragon 8 Gen 1
+ "73", # Snapdragon 8 Gen 2 / X Elite
+ "75", # Snapdragon 8 Gen 3
+ "79", # Snapdragon 8 Elite
+ "81", # Snapdragon 8 Elite Gen 5
+ }
+) # Qualcomm Hexagon HTP architecture versions available for QNN export
+HELP_MSG = """
+ Examples for running Ultralytics:
+
+ 1. Install the ultralytics package:
+
+ pip install ultralytics
+
+ 2. Use the Python SDK:
+
+ from ultralytics import YOLO
+
+ # Load a model
+ model = YOLO("yolo26n.yaml") # build a new model from scratch
+ model = YOLO("yolo26n.pt") # load a pretrained model (recommended for training)
+
+ # Use the model
+ results = model.train(data="coco8.yaml", epochs=3) # train the model
+ results = model.val() # evaluate model performance on the validation set
+ results = model("https://ultralytics.com/images/bus.jpg") # predict on an image
+ success = model.export(format="onnx") # export the model to ONNX format
+
+ 3. Use the command line interface (CLI):
+
+ Ultralytics 'yolo' CLI commands use the following syntax:
+
+ yolo TASK MODE ARGS
+
+ Where TASK (optional) is one of [detect, segment, semantic, classify, pose, obb]
+ MODE (required) is one of [train, val, predict, export, track, benchmark]
+ ARGS (optional) are any number of custom "arg=value" pairs like "imgsz=320" that override defaults.
+ See all ARGS at https://docs.ultralytics.com/usage/cfg or with "yolo cfg"
+
+ - Train a detection model for 10 epochs with an initial learning_rate of 0.01
+ yolo detect train data=coco8.yaml model=yolo26n.pt epochs=10 lr0=0.01
+
+ - Predict a YouTube video using a pretrained segmentation model at image size 320:
+ yolo segment predict model=yolo26n-seg.pt source='https://youtu.be/LNwODJXcvt4' imgsz=320
+
+ - Val a pretrained detection model at batch-size 1 and image size 640:
+ yolo detect val model=yolo26n.pt data=coco8.yaml batch=1 imgsz=640
+
+ - Export a YOLO26n classification model to ONNX format at image size 224 by 128 (no TASK required)
+ yolo export model=yolo26n-cls.pt format=onnx imgsz=224,128
+
+ - Run special commands:
+ yolo help
+ yolo checks
+ yolo version
+ yolo settings
+ yolo copy-cfg
+ yolo cfg
+
+ Docs: https://docs.ultralytics.com
+ Community: https://community.ultralytics.com
+ GitHub: https://github.com/ultralytics/ultralytics
+ """
+
+# Settings and Environment Variables
+torch.set_printoptions(linewidth=320, precision=4, profile="default")
+np.set_printoptions(linewidth=320, formatter=dict(float_kind="{:11.5g}".format)) # format short g, %precision=5
+cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader)
+os.environ["NUMEXPR_MAX_THREADS"] = str(NUM_THREADS) # NumExpr max threads
+os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" # suppress verbose TF compiler warnings in Colab
+os.environ["TORCH_CPP_LOG_LEVEL"] = "ERROR" # suppress "NNPACK.cpp could not initialize NNPACK" warnings
+os.environ["KINETO_LOG_LEVEL"] = "5" # suppress verbose PyTorch profiler output when computing FLOPs
+
+# Centralized warning suppression
+warnings.filterwarnings("ignore", message="torch.distributed.reduce_op is deprecated") # PyTorch deprecation
+warnings.filterwarnings("ignore", message="The figure layout has changed to tight") # matplotlib>=3.7.2
+warnings.filterwarnings("ignore", category=FutureWarning, module="timm") # mobileclip timm.layers deprecation
+warnings.filterwarnings("ignore", category=torch.jit.TracerWarning) # ONNX/TorchScript export tracer warnings
+warnings.filterwarnings("ignore", category=UserWarning, message=".*prim::Constant.*") # ONNX shape warning
+warnings.filterwarnings("ignore", category=DeprecationWarning, module="coremltools") # CoreML np.bool deprecation
+logging.getLogger("coremltools").setLevel(logging.ERROR) # Suppress native binary load failures on non-macOS
+
+# Precompiled type tuples for faster isinstance() checks
+FLOAT_OR_INT = (float, int)
+STR_OR_PATH = (str, Path)
+
+
+class DataExportMixin:
+ """Mixin class for exporting validation metrics or prediction results in various formats.
+
+ This class provides utilities to export performance metrics (e.g., mAP, precision, recall) or prediction results
+ from classification, object detection, segmentation, or pose estimation tasks into various formats: Polars
+ DataFrame, CSV, and JSON.
+
+ Methods:
+ to_df: Convert summary to a Polars DataFrame.
+ to_csv: Export results as a CSV string.
+ to_json: Export results as a JSON string.
+ tojson: Deprecated alias for `to_json()`.
+
+ Examples:
+ >>> model = YOLO("yolo26n.pt")
+ >>> results = model("image.jpg")
+ >>> df = results.to_df()
+ >>> print(df)
+ >>> csv_data = results.to_csv()
+ """
+
+ def to_df(self, normalize=False, decimals=5):
+ """Create a Polars DataFrame from the prediction results summary or validation metrics.
+
+ Args:
+ normalize (bool, optional): Normalize numerical values for easier comparison.
+ decimals (int, optional): Decimal places to round floats.
+
+ Returns:
+ (polars.DataFrame): Polars DataFrame containing the summary data.
+ """
+ import polars as pl # scope for faster 'import ultralytics'
+
+ return pl.DataFrame(self.summary(normalize=normalize, decimals=decimals))
+
+ def to_csv(self, normalize=False, decimals=5):
+ """Export results or metrics to CSV string format.
+
+ Args:
+ normalize (bool, optional): Normalize numeric values.
+ decimals (int, optional): Decimal precision.
+
+ Returns:
+ (str): CSV content as string.
+ """
+ import polars as pl
+
+ df = self.to_df(normalize=normalize, decimals=decimals)
+
+ try:
+ return df.write_csv()
+ except Exception:
+ # Minimal string conversion for any remaining complex types
+ def _to_str_simple(v):
+ if v is None:
+ return ""
+ elif isinstance(v, (dict, list, tuple, set)):
+ return repr(v)
+ else:
+ return str(v)
+
+ df_str = df.select(
+ [pl.col(c).map_elements(_to_str_simple, return_dtype=pl.String).alias(c) for c in df.columns]
+ )
+ return df_str.write_csv()
+
+ def to_json(self, normalize=False, decimals=5):
+ """Export results to JSON format.
+
+ Args:
+ normalize (bool, optional): Normalize numeric values.
+ decimals (int, optional): Decimal precision.
+
+ Returns:
+ (str): JSON-formatted string of the results.
+ """
+ return self.to_df(normalize=normalize, decimals=decimals).write_json()
+
+
+class SimpleClass:
+ """A simple base class for creating objects with string representations of their attributes.
+
+ This class provides a foundation for creating objects that can be easily printed or represented as strings, showing
+ all their non-callable attributes. It's useful for debugging and introspection of object states.
+
+ Methods:
+ __str__: Return a human-readable string representation of the object.
+ __repr__: Return a machine-readable string representation of the object.
+ __getattr__: Provide a custom attribute access error message with helpful information.
+
+ Examples:
+ >>> class MyClass(SimpleClass):
+ ... def __init__(self):
+ ... self.x = 10
+ ... self.y = "hello"
+ >>> obj = MyClass()
+ >>> print(obj)
+ __main__.MyClass object with attributes:
+
+ x: 10
+ y: 'hello'
+
+ Notes:
+ - This class is designed to be subclassed. It provides a convenient way to inspect object attributes.
+ - The string representation includes the module and class name of the object.
+ - Callable attributes and attributes starting with an underscore are excluded from the string representation.
+ """
+
+ def __str__(self):
+ """Return a human-readable string representation of the object."""
+ attr = []
+ for a in dir(self):
+ v = getattr(self, a)
+ if not callable(v) and not a.startswith("_"):
+ if isinstance(v, SimpleClass):
+ # Display only the module and class name for subclasses
+ s = f"{a}: {v.__module__}.{v.__class__.__name__} object"
+ else:
+ s = f"{a}: {v!r}"
+ attr.append(s)
+ return f"{self.__module__}.{self.__class__.__name__} object with attributes:\n\n" + "\n".join(attr)
+
+ def __repr__(self):
+ """Return a machine-readable string representation of the object."""
+ return self.__str__()
+
+ def __getattr__(self, attr):
+ """Provide a custom attribute access error message with helpful information."""
+ name = self.__class__.__name__
+ raise AttributeError(f"'{name}' object has no attribute '{attr}'. See valid attributes below.\n{self.__doc__}")
+
+
+class IterableSimpleNamespace(SimpleNamespace):
+ """An iterable SimpleNamespace class that provides enhanced functionality for attribute access and iteration.
+
+ This class extends the SimpleNamespace class with additional methods for iteration, string representation, and
+ attribute access. It is designed to be used as a convenient container for storing and accessing configuration
+ parameters.
+
+ Methods:
+ __iter__: Return an iterator of key-value pairs from the namespace's attributes.
+ __str__: Return a human-readable string representation of the object.
+ __getattr__: Provide a custom attribute access error message with helpful information.
+ get: Retrieve the value of a specified key, or a default value if the key doesn't exist.
+
+ Examples:
+ >>> cfg = IterableSimpleNamespace(a=1, b=2, c=3)
+ >>> for k, v in cfg:
+ ... print(f"{k}: {v}")
+ a: 1
+ b: 2
+ c: 3
+ >>> print(cfg)
+ a=1
+ b=2
+ c=3
+ >>> cfg.get("b")
+ 2
+ >>> cfg.get("d", "default")
+ 'default'
+
+ Notes:
+ This class is particularly useful for storing configuration parameters in a more accessible
+ and iterable format compared to a standard dictionary.
+ """
+
+ def __iter__(self):
+ """Return an iterator of key-value pairs from the namespace's attributes."""
+ return iter(vars(self).items())
+
+ def __str__(self):
+ """Return a human-readable string representation of the object."""
+ return "\n".join(f"{k}={v}" for k, v in vars(self).items())
+
+ def __getattr__(self, attr):
+ """Provide a custom attribute access error message with helpful information."""
+ name = self.__class__.__name__
+ raise AttributeError(
+ f"""
+ '{name}' object has no attribute '{attr}'. This may be caused by a modified or out of date ultralytics
+ 'default.yaml' file.\nPlease update your code with 'pip install -U ultralytics' and if necessary replace
+ {DEFAULT_CFG_PATH} with the latest version from
+ https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/default.yaml
+ """
+ )
+
+ def get(self, key, default=None):
+ """Return the value of the specified key if it exists; otherwise, return the default value."""
+ return getattr(self, key, default)
+
+
+def plt_settings(rcparams=None, backend="Agg"):
+ """Decorator to temporarily set rc parameters and the backend for a plotting function.
+
+ Args:
+ rcparams (dict, optional): Dictionary of rc parameters to set.
+ backend (str, optional): Name of the backend to use.
+
+ Returns:
+ (Callable): Decorated function with temporarily set rc parameters and backend.
+
+ Examples:
+ >>> @plt_settings({"font.size": 12})
+ ... def plot_function():
+ ... plt.figure()
+ ... plt.plot([1, 2, 3])
+ ... plt.show()
+
+ >>> with plt_settings({"font.size": 12}):
+ ... plt.figure()
+ ... plt.plot([1, 2, 3])
+ ... plt.show()
+ """
+ if rcparams is None:
+ rcparams = {"font.size": 11}
+
+ def decorator(func):
+ """Decorator to apply temporary rc parameters and backend to a function."""
+
+ def wrapper(*args, **kwargs):
+ """Set rc parameters and backend, call the original function, and restore the settings."""
+ import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
+
+ # Prepend Arial Unicode for non-Latin text (CJK, Arabic, etc.); matplotlib falls back if missing
+ if "font.sans-serif" not in rcparams and not wrapper._fonts_registered:
+ from matplotlib import font_manager
+
+ # Register any fonts in Ultralytics config dir (e.g. Arial.Unicode.ttf) with matplotlib
+ known = {f.fname for f in font_manager.fontManager.ttflist}
+ for f in USER_CONFIG_DIR.glob("*.ttf"):
+ if str(f) not in known:
+ font_manager.fontManager.addfont(str(f))
+ wrapper._fonts_registered = True
+ rc = (
+ rcparams
+ if "font.sans-serif" in rcparams
+ else {**rcparams, "font.sans-serif": ["Arial Unicode MS", *plt.rcParams.get("font.sans-serif", [])]}
+ )
+
+ original_backend = plt.get_backend()
+ switch = backend.lower() != original_backend.lower()
+ if switch:
+ plt.close("all") # auto-close()ing of figures upon backend switching is deprecated since 3.8
+ plt.switch_backend(backend)
+
+ # Plot with backend and always revert to original backend
+ try:
+ with plt.rc_context(rc):
+ result = func(*args, **kwargs)
+ finally:
+ if switch:
+ plt.close("all")
+ plt.switch_backend(original_backend)
+ return result
+
+ wrapper._fonts_registered = False
+ return wrapper
+
+ return decorator
+
+
+def set_logging(name="LOGGING_NAME", verbose=True):
+ """Set up logging with UTF-8 encoding and configurable verbosity.
+
+ This function configures logging for the Ultralytics library, setting the appropriate logging level and formatter
+ based on the verbosity flag and the current process rank. It handles special cases for Windows environments where
+ UTF-8 encoding might not be the default.
+
+ Args:
+ name (str): Name of the logger.
+ verbose (bool): Flag to set logging level to INFO if True, ERROR otherwise.
+
+ Returns:
+ (logging.Logger): Configured logger object.
+
+ Examples:
+ >>> set_logging(name="ultralytics", verbose=True)
+ >>> logger = logging.getLogger("ultralytics")
+ >>> logger.info("This is an info message")
+
+ Notes:
+ - On Windows, this function attempts to reconfigure stdout to use UTF-8 encoding if possible.
+ - If reconfiguration is not possible, it falls back to a custom formatter that handles non-UTF-8 environments.
+ - The function sets up a StreamHandler with the appropriate formatter and level.
+ - The logger's propagate flag is set to False to prevent duplicate logging in parent loggers.
+ """
+ level = logging.INFO if verbose and RANK in {-1, 0} else logging.ERROR # rank in world for Multi-GPU trainings
+
+ class PrefixFormatter(logging.Formatter):
+ def format(self, record):
+ """Format log records with prefixes based on level."""
+ # Apply prefixes based on log level
+ if record.levelno == logging.WARNING:
+ prefix = "WARNING" if WINDOWS else "WARNING ⚠️"
+ record.msg = f"{prefix} {record.msg}"
+ elif record.levelno == logging.ERROR:
+ prefix = "ERROR" if WINDOWS else "ERROR ❌"
+ record.msg = f"{prefix} {record.msg}"
+
+ # Handle emojis in message based on platform
+ formatted_message = super().format(record)
+ return emojis(formatted_message)
+
+ formatter = PrefixFormatter("%(message)s")
+
+ # Handle Windows UTF-8 encoding issues
+ if WINDOWS and hasattr(sys.stdout, "encoding") and sys.stdout.encoding != "utf-8":
+ with contextlib.suppress(Exception):
+ # Attempt to reconfigure stdout to use UTF-8 encoding if possible
+ if hasattr(sys.stdout, "reconfigure"):
+ sys.stdout.reconfigure(encoding="utf-8")
+ # For environments where reconfigure is not available, wrap stdout in a TextIOWrapper
+ elif hasattr(sys.stdout, "buffer"):
+ import io
+
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
+
+ # Create and configure the StreamHandler with the appropriate formatter and level
+ stream_handler = logging.StreamHandler(sys.stdout)
+ stream_handler.setFormatter(formatter)
+ stream_handler.setLevel(level)
+
+ # Set up the logger
+ logger = logging.getLogger(name)
+ logger.setLevel(level)
+ logger.addHandler(stream_handler)
+ logger.propagate = False
+ return logger
+
+
+# Set logger
+LOGGER = set_logging(LOGGING_NAME, verbose=VERBOSE) # define globally (used in train.py, val.py, predict.py, etc.)
+logging.getLogger("sentry_sdk").setLevel(logging.CRITICAL + 1)
+
+
+def emojis(string=""):
+ """Return platform-dependent emoji-safe version of string."""
+ return string.encode().decode("ascii", "ignore") if WINDOWS else string
+
+
+class ThreadingLocked:
+ """A decorator class for ensuring thread-safe execution of a function or method.
+
+ This class can be used as a decorator to make sure that if the decorated function is called from multiple threads,
+ only one thread at a time will be able to execute the function.
+
+ Attributes:
+ lock (threading.Lock): A lock object used to manage access to the decorated function.
+
+ Examples:
+ >>> from ultralytics.utils import ThreadingLocked
+ >>> @ThreadingLocked()
+ ... def my_function():
+ ... # Your code here
+ """
+
+ def __init__(self):
+ """Initialize the decorator class with a threading lock."""
+ self.lock = threading.Lock()
+
+ def __call__(self, f):
+ """Run thread-safe execution of function or method."""
+ from functools import wraps
+
+ @wraps(f)
+ def decorated(*args, **kwargs):
+ """Apply thread-safety to the decorated function or method."""
+ with self.lock:
+ return f(*args, **kwargs)
+
+ return decorated
+
+
+class YAML:
+ """YAML utility class for efficient file operations with automatic C-implementation detection.
+
+ This class provides optimized YAML loading and saving operations using PyYAML's fastest available implementation
+ (C-based when possible). It implements a singleton pattern with lazy initialization, allowing direct class method
+ usage without explicit instantiation. The class handles file path creation, validation, and character encoding
+ issues automatically.
+
+ The implementation prioritizes performance through:
+ - Automatic C-based loader/dumper selection when available
+ - Singleton pattern to reuse the same instance
+ - Lazy initialization to defer import costs until needed
+ - Fallback mechanisms for handling problematic YAML content
+
+ Attributes:
+ _instance: Internal singleton instance storage.
+ yaml: Reference to the PyYAML module.
+ SafeLoader: Best available YAML loader (CSafeLoader if available).
+ SafeDumper: Best available YAML dumper (CSafeDumper if available).
+
+ Examples:
+ >>> data = YAML.load("config.yaml")
+ >>> data["new_value"] = 123
+ >>> YAML.save("updated_config.yaml", data)
+ >>> YAML.print(data)
+ """
+
+ _instance = None
+
+ @classmethod
+ def _get_instance(cls):
+ """Initialize singleton instance on first use."""
+ if cls._instance is None:
+ cls._instance = cls()
+ return cls._instance
+
+ def __init__(self):
+ """Initialize with optimal YAML implementation (C-based when available)."""
+ import yaml
+
+ self.yaml = yaml
+ # Use C-based implementation if available for better performance
+ try:
+ self.SafeLoader = yaml.CSafeLoader
+ self.SafeDumper = yaml.CSafeDumper
+ except (AttributeError, ImportError):
+ self.SafeLoader = yaml.SafeLoader
+ self.SafeDumper = yaml.SafeDumper
+
+ @classmethod
+ def save(cls, file="data.yaml", data=None, header=""):
+ """Save Python object as YAML file.
+
+ Args:
+ file (str | Path): Path to save YAML file.
+ data (dict | None): Dict or compatible object to save.
+ header (str): Optional string to add at file beginning.
+ """
+ instance = cls._get_instance()
+ if data is None:
+ data = {}
+
+ # Create parent directories if needed
+ file = Path(file)
+ file.parent.mkdir(parents=True, exist_ok=True)
+
+ # Convert non-serializable objects to strings
+ valid_types = int, float, str, bool, list, tuple, dict, type(None)
+ for k, v in data.items():
+ if not isinstance(v, valid_types):
+ data[k] = str(v)
+
+ # Write YAML file
+ with open(file, "w", errors="ignore", encoding="utf-8") as f:
+ if header:
+ f.write(header)
+ instance.yaml.dump(data, f, sort_keys=False, allow_unicode=True, Dumper=instance.SafeDumper)
+
+ @classmethod
+ def load(cls, file="data.yaml", append_filename=False):
+ """Load YAML file to Python object with robust error handling.
+
+ Args:
+ file (str | Path): Path to YAML file.
+ append_filename (bool): Whether to add filename to returned dict.
+
+ Returns:
+ (dict): Loaded YAML content.
+ """
+ instance = cls._get_instance()
+ assert str(file).endswith((".yaml", ".yml")), f"Not a YAML file: {file}"
+
+ # Read file content
+ with open(file, errors="ignore", encoding="utf-8") as f:
+ s = f.read()
+
+ # Try loading YAML with fallback for problematic characters
+ try:
+ data = instance.yaml.load(s, Loader=instance.SafeLoader) or {}
+ except Exception as e:
+ # Remove problematic characters and retry
+ s = re.sub(r"[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]+", "", s)
+ try:
+ data = instance.yaml.load(s, Loader=instance.SafeLoader) or {}
+ except Exception:
+ raise ValueError(
+ f"YAML syntax error in '{file}': {e}\nVerify YAML with https://ray.run/tools/yaml-formatter"
+ ) from None
+
+ # Check for accidental user-error None strings (should be 'null' in YAML)
+ if "None" in data.values():
+ data = {k: None if v == "None" else v for k, v in data.items()}
+
+ if append_filename:
+ data["yaml_file"] = str(file)
+ return data
+
+ @classmethod
+ def print(cls, yaml_file):
+ """Pretty print YAML file or object to console.
+
+ Args:
+ yaml_file (str | Path | dict): Path to YAML file or dict to print.
+ """
+ instance = cls._get_instance()
+
+ # Load file if path provided
+ yaml_dict = cls.load(yaml_file) if isinstance(yaml_file, (str, Path)) else yaml_file
+
+ # Use -1 for unlimited width in C implementation
+ dump = instance.yaml.dump(yaml_dict, sort_keys=False, allow_unicode=True, width=-1, Dumper=instance.SafeDumper)
+
+ LOGGER.info(f"Printing '{colorstr('bold', 'black', yaml_file)}'\n\n{dump}")
+
+
+# Default configuration
+DEFAULT_CFG_DICT = YAML.load(DEFAULT_CFG_PATH)
+DEFAULT_CFG_KEYS = DEFAULT_CFG_DICT.keys()
+DEFAULT_CFG = IterableSimpleNamespace(**DEFAULT_CFG_DICT)
+
+
+def read_device_model() -> str:
+ """Read the device model information from the system.
+
+ Returns:
+ (str): Platform release string in lowercase, used to identify device models like Jetson or Raspberry Pi.
+ """
+ return platform.release().lower()
+
+
+def is_ubuntu() -> bool:
+ """Check if the OS is Ubuntu.
+
+ Returns:
+ (bool): True if OS is Ubuntu, False otherwise.
+ """
+ try:
+ with open("/etc/os-release") as f:
+ return "ID=ubuntu" in f.read()
+ except FileNotFoundError:
+ return False
+
+
+def is_debian(codenames: list[str] | None | str = None) -> list[bool] | bool:
+ """Check if the OS is Debian.
+
+ Args:
+ codenames (list[str] | None | str): Specific Debian codename to check for (e.g., 'buster', 'bullseye'). If None,
+ only checks for Debian.
+
+ Returns:
+ (list[bool] | bool): List of booleans indicating if OS matches each Debian codename, or a single boolean if no
+ codenames provided.
+ """
+ try:
+ with open("/etc/os-release") as f:
+ content = f.read()
+ if codenames is None:
+ return "ID=debian" in content
+ if isinstance(codenames, str):
+ codenames = [codenames]
+ return [
+ f"VERSION_CODENAME={codename}" in content if codename else "ID=debian" in content
+ for codename in codenames
+ ]
+ except FileNotFoundError:
+ return [False] * len(codenames) if codenames else False
+
+
+def is_colab():
+ """Check if the current script is running inside a Google Colab notebook.
+
+ Returns:
+ (bool): True if running inside a Colab notebook, False otherwise.
+ """
+ return "COLAB_RELEASE_TAG" in os.environ or "COLAB_BACKEND_VERSION" in os.environ
+
+
+def is_kaggle():
+ """Check if the current script is running inside a Kaggle kernel.
+
+ Returns:
+ (bool): True if running inside a Kaggle kernel, False otherwise.
+ """
+ return os.environ.get("PWD") == "/kaggle/working" and os.environ.get("KAGGLE_URL_BASE") == "https://www.kaggle.com"
+
+
+def is_jupyter():
+ """Check if the current script is running inside a Jupyter Notebook.
+
+ Returns:
+ (bool): True if running inside a Jupyter Notebook, False otherwise.
+
+ Notes:
+ - Only works on Colab and Kaggle, other environments like Jupyterlab and Paperspace are not reliably detectable.
+ - "get_ipython" in globals() method suffers false positives when IPython package installed manually.
+ """
+ return IS_COLAB or IS_KAGGLE
+
+
+def is_runpod():
+ """Check if the current script is running inside a RunPod container.
+
+ Returns:
+ (bool): True if running in RunPod, False otherwise.
+ """
+ return "RUNPOD_POD_ID" in os.environ
+
+
+def is_docker() -> bool:
+ """Determine if the script is running inside a Docker container.
+
+ Returns:
+ (bool): True if the script is running inside a Docker container, False otherwise.
+ """
+ try:
+ return os.path.exists("/.dockerenv")
+ except Exception:
+ return False
+
+
+def is_raspberrypi() -> bool:
+ """Determine if the Python environment is running on a Raspberry Pi.
+
+ Returns:
+ (bool): True if running on a Raspberry Pi, False otherwise.
+ """
+ return "rpi" in DEVICE_MODEL
+
+
+@lru_cache(maxsize=3)
+def is_jetson(jetpack=None) -> bool:
+ """Determine if the Python environment is running on an NVIDIA Jetson device.
+
+ Args:
+ jetpack (int | None): If specified, check for specific JetPack version (4, 5, 6).
+
+ Returns:
+ (bool): True if running on an NVIDIA Jetson device, False otherwise.
+ """
+ jetson = "tegra" in DEVICE_MODEL
+ if jetson and jetpack:
+ try:
+ content = open("/etc/nv_tegra_release").read()
+ version_map = {4: "R32", 5: "R35", 6: "R36", 7: "R38"} # JetPack to L4T major version mapping
+ return jetpack in version_map and version_map[jetpack] in content
+ except Exception:
+ return False
+ return jetson
+
+
+def is_dgx() -> bool:
+ """Check if the current script is running inside a DGX (NVIDIA Data Center GPU), DGX-Ready or DGX Spark system.
+
+ Returns:
+ (bool): True if running in a DGX or DGX-Ready or DGX Spark system, False otherwise.
+ """
+ try:
+ with open("/etc/dgx-release") as f:
+ return "DGX" in f.read()
+ except FileNotFoundError:
+ return False
+
+
+def is_online() -> bool:
+ """Fast online check using DNS (v4/v6) resolution (Cloudflare + Google).
+
+ Returns:
+ (bool): True if connection is successful, False otherwise.
+ """
+ if str(os.getenv("YOLO_OFFLINE", "")).lower() == "true":
+ return False
+
+ for host in ("one.one.one.one", "dns.google"):
+ try:
+ socket.getaddrinfo(host, 0, socket.AF_UNSPEC, 0, 0, socket.AI_ADDRCONFIG)
+ return True
+ except OSError:
+ continue
+ return False
+
+
+def is_pip_package(filepath: str = __name__) -> bool:
+ """Determine if the file at the given filepath is part of a pip package.
+
+ Args:
+ filepath (str): The filepath to check.
+
+ Returns:
+ (bool): True if the file is part of a pip package, False otherwise.
+ """
+ import importlib.util
+
+ # Get the spec for the module
+ spec = importlib.util.find_spec(filepath)
+
+ # Return whether the spec is not None and the origin is not None (indicating it is a package)
+ return spec is not None and spec.origin is not None
+
+
+def is_dir_writeable(dir_path: str | Path) -> bool:
+ """Check if a directory is writable.
+
+ Args:
+ dir_path (str | Path): The path to the directory.
+
+ Returns:
+ (bool): True if the directory is writable, False otherwise.
+ """
+ return os.access(str(dir_path), os.W_OK)
+
+
+def is_pytest_running():
+ """Determine whether pytest is currently running or not.
+
+ Returns:
+ (bool): True if pytest is running, False otherwise.
+ """
+ return ("PYTEST_CURRENT_TEST" in os.environ) or ("pytest" in sys.modules) or ("pytest" in Path(ARGV[0]).stem)
+
+
+def is_github_action_running() -> bool:
+ """Determine if the current environment is a GitHub Actions runner.
+
+ Returns:
+ (bool): True if the current environment is a GitHub Actions runner, False otherwise.
+ """
+ return "GITHUB_ACTIONS" in os.environ and "GITHUB_WORKFLOW" in os.environ and "RUNNER_OS" in os.environ
+
+
+def get_default_args(func):
+ """Return a dictionary of default arguments for a function.
+
+ Args:
+ func (callable): The function to inspect.
+
+ Returns:
+ (dict): A dictionary where each key is a parameter name, and each value is the default value of that parameter.
+ """
+ signature = inspect.signature(func)
+ return {k: v.default for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty}
+
+
+def get_ubuntu_version():
+ """Retrieve the Ubuntu version if the OS is Ubuntu.
+
+ Returns:
+ (str): Ubuntu version or None if not an Ubuntu OS.
+ """
+ if is_ubuntu():
+ try:
+ with open("/etc/os-release") as f:
+ return re.search(r'VERSION_ID="(\d+\.\d+)"', f.read())[1]
+ except (FileNotFoundError, AttributeError):
+ return None
+
+
+def get_user_config_dir(sub_dir="Ultralytics"):
+ """Return a writable config dir, preferring YOLO_CONFIG_DIR and being OS-aware.
+
+ Args:
+ sub_dir (str): The name of the subdirectory to create.
+
+ Returns:
+ (Path): The path to the user config directory.
+ """
+ if env_dir := os.getenv("YOLO_CONFIG_DIR"):
+ p = Path(env_dir).expanduser() / sub_dir
+ elif LINUX:
+ p = Path(os.getenv("XDG_CONFIG_HOME", Path.home() / ".config")) / sub_dir
+ elif WINDOWS:
+ p = Path.home() / "AppData" / "Roaming" / sub_dir
+ elif MACOS:
+ p = Path.home() / "Library" / "Application Support" / sub_dir
+ else:
+ raise ValueError(f"Unsupported operating system: {platform.system()}")
+
+ if p.exists(): # already created → trust it
+ return p
+ if is_dir_writeable(p.parent): # create if possible
+ p.mkdir(parents=True, exist_ok=True)
+ return p
+
+ # Fallbacks for Docker, GCP/AWS functions where only /tmp is writable
+ for alt in [Path("/tmp") / sub_dir, Path.cwd() / sub_dir]:
+ if alt.exists():
+ return alt
+ if is_dir_writeable(alt.parent):
+ alt.mkdir(parents=True, exist_ok=True)
+ LOGGER.warning(
+ f"user config directory '{p}' is not writable, using '{alt}'. Set YOLO_CONFIG_DIR to override."
+ )
+ return alt
+
+ # Last fallback → CWD
+ p = Path.cwd() / sub_dir
+ p.mkdir(parents=True, exist_ok=True)
+ return p
+
+
+# Define constants (required below)
+DEVICE_MODEL = read_device_model() # is_jetson() and is_raspberrypi() depend on this constant
+ONLINE = is_online()
+IS_COLAB = is_colab()
+IS_KAGGLE = is_kaggle()
+IS_DOCKER = is_docker()
+IS_JETSON = is_jetson()
+IS_JUPYTER = is_jupyter()
+IS_PIP_PACKAGE = is_pip_package()
+IS_RASPBERRYPI = is_raspberrypi()
+IS_DEBIAN, IS_DEBIAN_BOOKWORM, IS_DEBIAN_TRIXIE = is_debian([None, "bookworm", "trixie"])
+IS_UBUNTU = is_ubuntu()
+GIT = GitRepo()
+USER_CONFIG_DIR = get_user_config_dir() # Ultralytics settings dir
+SETTINGS_FILE = USER_CONFIG_DIR / "settings.json"
+
+
+def colorstr(*input):
+ r"""Color a string based on the provided color and style arguments using ANSI escape codes.
+
+ This function can be called in two ways:
+ - colorstr('color', 'style', 'your string')
+ - colorstr('your string')
+
+ In the second form, 'blue' and 'bold' will be applied by default.
+
+ Args:
+ *input (str | Path): A sequence of strings where the first n-1 strings are color and style arguments, and the
+ last string is the one to be colored.
+
+ Returns:
+ (str): The input string wrapped with ANSI escape codes for the specified color and style.
+
+ Examples:
+ >>> colorstr("blue", "bold", "hello world")
+ "\033[34m\033[1mhello world\033[0m"
+
+ Notes:
+ Supported Colors and Styles:
+ - Basic Colors: 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
+ - Bright Colors: 'bright_black', 'bright_red', 'bright_green', 'bright_yellow',
+ 'bright_blue', 'bright_magenta', 'bright_cyan', 'bright_white'
+ - Misc: 'end', 'bold', 'underline'
+
+ References:
+ https://en.wikipedia.org/wiki/ANSI_escape_code
+ """
+ *args, string = input if len(input) > 1 else ("blue", "bold", input[0]) # color arguments, string
+ colors = {
+ "black": "\033[30m", # basic colors
+ "red": "\033[31m",
+ "green": "\033[32m",
+ "yellow": "\033[33m",
+ "blue": "\033[34m",
+ "magenta": "\033[35m",
+ "cyan": "\033[36m",
+ "white": "\033[37m",
+ "bright_black": "\033[90m", # bright colors
+ "bright_red": "\033[91m",
+ "bright_green": "\033[92m",
+ "bright_yellow": "\033[93m",
+ "bright_blue": "\033[94m",
+ "bright_magenta": "\033[95m",
+ "bright_cyan": "\033[96m",
+ "bright_white": "\033[97m",
+ "end": "\033[0m", # misc
+ "bold": "\033[1m",
+ "underline": "\033[4m",
+ }
+ return "".join(colors[x] for x in args) + f"{string}" + colors["end"]
+
+
+def remove_colorstr(input_string):
+ """Remove ANSI escape codes from a string, effectively un-coloring it.
+
+ Args:
+ input_string (str): The string to remove color and style from.
+
+ Returns:
+ (str): A new string with all ANSI escape codes removed.
+
+ Examples:
+ >>> remove_colorstr(colorstr("blue", "bold", "hello world"))
+ "hello world"
+ """
+ ansi_escape = re.compile(r"\x1B\[[0-9;]*[A-Za-z]")
+ return ansi_escape.sub("", input_string)
+
+
+class TryExcept(contextlib.ContextDecorator):
+ """Ultralytics TryExcept class for handling exceptions gracefully.
+
+ This class can be used as a decorator or context manager to catch exceptions and optionally print warning messages.
+ It allows code to continue execution even when exceptions occur, which is useful for non-critical operations.
+
+ Attributes:
+ msg (str): Optional message to display when an exception occurs.
+ verbose (bool): Whether to print the exception message.
+
+ Examples:
+ As a decorator:
+ >>> @TryExcept(msg="Error occurred in func", verbose=True)
+ ... def func():
+ ... # Function logic here
+ ... pass
+
+ As a context manager:
+ >>> with TryExcept(msg="Error occurred in block", verbose=True):
+ ... # Code block here
+ ... pass
+ """
+
+ def __init__(self, msg="", verbose=True):
+ """Initialize TryExcept class with optional message and verbosity settings."""
+ self.msg = msg
+ self.verbose = verbose
+
+ def __enter__(self):
+ """Execute when entering TryExcept context, initialize instance."""
+ pass
+
+ def __exit__(self, exc_type, value, traceback):
+ """Define behavior when exiting a 'with' block, print error message if necessary."""
+ if self.verbose and value:
+ LOGGER.warning(f"{self.msg}{': ' if self.msg else ''}{value}")
+ return True
+
+
+class Retry(contextlib.ContextDecorator):
+ """Retry class for function execution with exponential backoff.
+
+ This decorator can be used to retry a function on exceptions, up to a specified number of times with an
+ exponentially increasing delay between retries. It's useful for handling transient failures in network operations or
+ other unreliable processes.
+
+ Attributes:
+ times (int): Maximum number of retry attempts.
+ delay (int): Initial delay between retries in seconds.
+
+ Examples:
+ Example usage as a decorator:
+ >>> @Retry(times=3, delay=2)
+ ... def test_func():
+ ... # Replace with function logic that may raise exceptions
+ ... return True
+ """
+
+ def __init__(self, times=3, delay=2):
+ """Initialize Retry class with specified number of retries and delay."""
+ self.times = times
+ self.delay = delay
+ self._attempts = 0
+
+ def __call__(self, func):
+ """Decorator implementation for Retry with exponential backoff."""
+
+ def wrapped_func(*args, **kwargs):
+ """Apply retries to the decorated function or method."""
+ self._attempts = 0
+ while self._attempts < self.times:
+ try:
+ return func(*args, **kwargs)
+ except Exception as e:
+ self._attempts += 1
+ LOGGER.warning(f"Retry {self._attempts}/{self.times} failed: {e}")
+ if self._attempts >= self.times:
+ raise e
+ time.sleep(self.delay * (2**self._attempts)) # exponential backoff delay
+
+ return wrapped_func
+
+
+def threaded(func):
+ """Multi-thread a target function by default and return the thread or function result.
+
+ This decorator provides flexible execution of the target function, either in a separate thread or synchronously. By
+ default, the function runs in a thread, but this can be controlled via the 'threaded=False' keyword argument which
+ is removed from kwargs before calling the function.
+
+ Args:
+ func (callable): The function to be potentially executed in a separate thread.
+
+ Returns:
+ (callable): A wrapper function that either returns a daemon thread or the direct function result.
+
+ Examples:
+ >>> @threaded
+ ... def process_data(data):
+ ... return data
+ >>>
+ >>> thread = process_data(my_data) # Runs in background thread
+ >>> result = process_data(my_data, threaded=False) # Runs synchronously, returns function result
+ """
+
+ def wrapper(*args, **kwargs):
+ """Multi-thread a given function based on 'threaded' kwarg and return the thread or function result."""
+ if kwargs.pop("threaded", True): # run in thread
+ thread = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True)
+ thread.start()
+ return thread
+ else:
+ return func(*args, **kwargs)
+
+ return wrapper
+
+
+def set_sentry():
+ """Initialize the Sentry SDK for error tracking and reporting.
+
+ Only used if sentry_sdk package is installed and sync=True in settings. Run 'yolo settings' to see and update
+ settings.
+
+ Conditions required to send errors (ALL conditions must be met or no errors will be reported):
+ - sentry_sdk package is installed
+ - sync=True in YOLO settings
+ - pytest is not running
+ - running in a pip package installation
+ - running in a non-git directory
+ - running with rank -1 or 0
+ - online environment
+ - CLI used to run package (checked with 'yolo' as the name of the main CLI command)
+ """
+ if (
+ not SETTINGS["sync"]
+ or RANK not in {-1, 0}
+ or Path(ARGV[0]).name != "yolo"
+ or TESTS_RUNNING
+ or not ONLINE
+ or not IS_PIP_PACKAGE
+ or GIT.is_repo
+ ):
+ return
+ # If sentry_sdk package is not installed then return and do not use Sentry
+ try:
+ import sentry_sdk
+ except ImportError:
+ return
+
+ def before_send(event, hint):
+ """Modify the event before sending it to Sentry based on specific exception types and messages.
+
+ Args:
+ event (dict): The event dictionary containing information about the error.
+ hint (dict): A dictionary containing additional information about the error.
+
+ Returns:
+ (dict | None): The modified event or None if the event should not be sent to Sentry.
+ """
+ if "exc_info" in hint:
+ exc_type, exc_value, _ = hint["exc_info"]
+ if exc_type in {KeyboardInterrupt, FileNotFoundError} or "out of memory" in str(exc_value):
+ return None # do not send event
+
+ event["tags"] = {
+ "sys_argv": ARGV[0],
+ "sys_argv_name": Path(ARGV[0]).name,
+ "install": "git" if GIT.is_repo else "pip" if IS_PIP_PACKAGE else "other",
+ "os": ENVIRONMENT,
+ }
+ return event
+
+ sentry_sdk.init(
+ dsn="https://888e5a0778212e1d0314c37d4b9aae5d@o4504521589325824.ingest.us.sentry.io/4504521592406016",
+ debug=False,
+ auto_enabling_integrations=False,
+ traces_sample_rate=1.0,
+ release=__version__,
+ environment="runpod" if is_runpod() else "production",
+ before_send=before_send,
+ ignore_errors=[KeyboardInterrupt, FileNotFoundError],
+ )
+ sentry_sdk.set_user({"id": SETTINGS["uuid"]}) # SHA-256 anonymized UUID hash
+
+
+class JSONDict(dict):
+ """A dictionary-like class that provides JSON persistence for its contents.
+
+ This class extends the built-in dictionary to automatically save its contents to a JSON file whenever they are
+ modified. It ensures thread-safe operations using a lock and handles JSON serialization of Path objects.
+
+ Attributes:
+ file_path (Path): The path to the JSON file used for persistence.
+ lock (threading.Lock): A lock object to ensure thread-safe operations.
+
+ Methods:
+ _load: Load the data from the JSON file into the dictionary.
+ _save: Save the current state of the dictionary to the JSON file.
+ __setitem__: Store a key-value pair and persist it to disk.
+ __delitem__: Remove an item and update the persistent storage.
+ update: Update the dictionary and persist changes.
+ clear: Clear all entries and update the persistent storage.
+
+ Examples:
+ >>> json_dict = JSONDict("data.json")
+ >>> json_dict["key"] = "value"
+ >>> print(json_dict["key"])
+ value
+ >>> del json_dict["key"]
+ >>> json_dict.update({"new_key": "new_value"})
+ >>> json_dict.clear()
+ """
+
+ def __init__(self, file_path: str | Path = "data.json"):
+ """Initialize a JSONDict object with a specified file path for JSON persistence."""
+ super().__init__()
+ self.file_path = Path(file_path)
+ self.lock = Lock()
+ self._load()
+
+ def _load(self):
+ """Load the data from the JSON file into the dictionary."""
+ try:
+ if self.file_path.exists():
+ with open(self.file_path) as f:
+ # Use the base dict update to avoid persisting during reads
+ super().update(json.load(f))
+ except json.JSONDecodeError:
+ LOGGER.warning(f"Error decoding JSON from {self.file_path}. Starting with an empty dictionary.")
+ except Exception as e:
+ LOGGER.error(f"Error reading from {self.file_path}: {e}")
+
+ def _save(self):
+ """Save the current state of the dictionary to the JSON file."""
+ try:
+ self.file_path.parent.mkdir(parents=True, exist_ok=True)
+ with open(self.file_path, "w", encoding="utf-8") as f:
+ json.dump(dict(self), f, indent=2, default=self._json_default)
+ except Exception as e:
+ LOGGER.error(f"Error writing to {self.file_path}: {e}")
+
+ @staticmethod
+ def _json_default(obj):
+ """Handle JSON serialization of Path objects."""
+ if isinstance(obj, Path):
+ return str(obj)
+ raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
+
+ def __setitem__(self, key, value):
+ """Store a key-value pair and persist to disk."""
+ with self.lock:
+ super().__setitem__(key, value)
+ self._save()
+
+ def __delitem__(self, key):
+ """Remove an item and update the persistent storage."""
+ with self.lock:
+ super().__delitem__(key)
+ self._save()
+
+ def __str__(self):
+ """Return a pretty-printed JSON string representation of the dictionary."""
+ contents = json.dumps(dict(self), indent=2, ensure_ascii=False, default=self._json_default)
+ return f'JSONDict("{self.file_path}"):\n{contents}'
+
+ def update(self, *args, **kwargs):
+ """Update the dictionary and persist changes."""
+ with self.lock:
+ super().update(*args, **kwargs)
+ self._save()
+
+ def clear(self):
+ """Clear all entries and update the persistent storage."""
+ with self.lock:
+ super().clear()
+ self._save()
+
+
+class SettingsManager(JSONDict):
+ """SettingsManager class for managing and persisting Ultralytics settings.
+
+ This class extends JSONDict to provide JSON persistence for settings, ensuring thread-safe operations and default
+ values. It validates settings on initialization and provides methods to update or reset settings. The settings
+ include directories for datasets, weights, and runs, as well as various integration flags.
+
+ Attributes:
+ file (Path): The path to the JSON file used for persistence.
+ version (str): The version of the settings schema.
+ defaults (dict): A dictionary containing default settings.
+ help_msg (str): A help message for users on how to view and update settings.
+
+ Methods:
+ _validate_settings: Validate the current settings and reset if necessary.
+ update: Update settings, validating keys and types.
+ reset: Reset the settings to default and save them.
+
+ Examples:
+ Initialize and update settings:
+ >>> settings = SettingsManager()
+ >>> settings.update(runs_dir="/new/runs/dir")
+ >>> print(settings["runs_dir"])
+ /new/runs/dir
+ """
+
+ def __init__(self, file=SETTINGS_FILE, version="0.0.6"):
+ """Initialize the SettingsManager with default settings and load user settings."""
+ import hashlib
+ import uuid
+
+ from models_related.ultralytics.ultralytics.utils.torch_utils import torch_distributed_zero_first
+
+ root = GIT.root or Path()
+ datasets_root = (root.parent if GIT.root and is_dir_writeable(root.parent) else root).resolve()
+
+ self.file = Path(file)
+ self.version = version
+ self.defaults = {
+ "settings_version": version, # Settings schema version
+ "datasets_dir": str(datasets_root / "datasets"), # Datasets directory
+ "weights_dir": str(root / "weights"), # Model weights directory
+ "runs_dir": str(root / "runs"), # Experiment runs directory
+ "uuid": hashlib.sha256(str(uuid.getnode()).encode()).hexdigest(), # SHA-256 anonymized UUID hash
+ "sync": True, # Enable synchronization
+ "api_key": "", # Ultralytics API Key
+ "openai_api_key": "", # OpenAI API Key
+ "clearml": True, # ClearML integration
+ "comet": True, # Comet integration
+ "dvc": True, # DVC integration
+ "hub": True, # Ultralytics HUB integration
+ "mlflow": True, # MLflow integration
+ "neptune": True, # Neptune integration
+ "raytune": True, # Ray Tune integration
+ "tensorboard": False, # TensorBoard logging
+ "wandb": False, # Weights & Biases logging
+ "vscode_msg": True, # VSCode message
+ "openvino_msg": True, # OpenVINO export on Intel CPU message
+ }
+
+ self.help_msg = (
+ f"\nView Ultralytics Settings with 'yolo settings' or at '{self.file}'"
+ "\nUpdate Settings with 'yolo settings key=value', i.e. 'yolo settings runs_dir=path/to/dir'. "
+ "For help see https://docs.ultralytics.com/quickstart/#ultralytics-settings."
+ )
+
+ with torch_distributed_zero_first(LOCAL_RANK):
+ super().__init__(self.file)
+
+ if not self.file.exists() or not self: # Check if file doesn't exist or is empty
+ LOGGER.info(f"Creating new Ultralytics Settings v{version} file ✅ {self.help_msg}")
+ self.reset()
+
+ self._validate_settings()
+
+ def _validate_settings(self):
+ """Validate the current settings and reset if necessary."""
+ correct_keys = frozenset(self.keys()) == frozenset(self.defaults.keys())
+ correct_types = all(isinstance(self.get(k), type(v)) for k, v in self.defaults.items())
+ correct_version = self.get("settings_version", "") == self.version
+
+ if not (correct_keys and correct_types and correct_version):
+ LOGGER.warning(
+ "Ultralytics settings reset to default values. This may be due to a possible problem "
+ f"with your settings or a recent ultralytics package update. {self.help_msg}"
+ )
+ self.reset()
+
+ if self.get("datasets_dir") == self.get("runs_dir"):
+ LOGGER.warning(
+ f"Ultralytics setting 'datasets_dir: {self.get('datasets_dir')}' "
+ f"must be different than 'runs_dir: {self.get('runs_dir')}'. "
+ f"Please change one to avoid possible issues during training. {self.help_msg}"
+ )
+
+ def __setitem__(self, key, value):
+ """Update one key: value pair."""
+ self.update({key: value})
+
+ def update(self, *args, **kwargs):
+ """Update settings, validating keys and types."""
+ for arg in args:
+ if isinstance(arg, dict):
+ kwargs.update(arg)
+ for k, v in kwargs.items():
+ if k not in self.defaults:
+ raise KeyError(f"No Ultralytics setting '{k}'. {self.help_msg}")
+ t = type(self.defaults[k])
+ if not isinstance(v, t):
+ raise TypeError(
+ f"Ultralytics setting '{k}' must be '{t.__name__}' type, not '{type(v).__name__}'. {self.help_msg}"
+ )
+ super().update(*args, **kwargs)
+
+ def reset(self):
+ """Reset the settings to default and save them."""
+ self.clear()
+ self.update(self.defaults)
+
+
+def deprecation_warn(arg, new_arg=None):
+ """Issue a deprecation warning when a deprecated argument is used, suggesting an updated argument."""
+ msg = f"'{arg}' is deprecated and will be removed in the future."
+ if new_arg is not None:
+ msg += f" Use '{new_arg}' instead."
+ LOGGER.warning(msg)
+
+
+def clean_url(url):
+ """Strip auth from URL, i.e. `https://example.com/path/file.txt?auth` -> `https://example.com/path/file.txt`."""
+ url = Path(url).as_posix().replace(":/", "://") # Pathlib turns :// -> :/, as_posix() for Windows
+ return unquote(url).split("?", 1)[0] # '%2F' to '/', split authentication query strings
+
+
+def url2file(url):
+ """Convert URL to filename, i.e. `https://example.com/path/file.txt?auth` -> `file.txt`."""
+ return Path(clean_url(url)).name or "download"
+
+
+def vscode_msg(ext="ultralytics.ultralytics-snippets") -> str:
+ """Display a message to install Ultralytics-Snippets for VS Code if not already installed."""
+ path = (USER_CONFIG_DIR.parents[2] if WINDOWS else USER_CONFIG_DIR.parents[1]) / ".vscode/extensions"
+ obs_file = path / ".obsolete" # file tracks uninstalled extensions, while source directory remains
+ installed = any(path.glob(f"{ext}*")) and ext not in (obs_file.read_text("utf-8") if obs_file.exists() else "")
+ url = "https://docs.ultralytics.com/integrations/vscode"
+ return "" if installed else f"{colorstr('VS Code:')} view Ultralytics VS Code Extension ⚡ at {url}"
+
+
+# Run below code on utils init ------------------------------------------------------------------------------------
+
+# Check first-install steps
+PREFIX = colorstr("Ultralytics: ")
+SETTINGS = SettingsManager() # initialize settings
+PERSISTENT_CACHE = JSONDict(USER_CONFIG_DIR / "persistent_cache.json") # initialize persistent cache
+DATASETS_DIR = Path(SETTINGS["datasets_dir"]) # global datasets directory
+WEIGHTS_DIR = Path(SETTINGS["weights_dir"]) # global weights directory
+RUNS_DIR = Path(SETTINGS["runs_dir"]) # global runs directory
+ENVIRONMENT = (
+ "Colab"
+ if IS_COLAB
+ else "Kaggle"
+ if IS_KAGGLE
+ else "Jupyter"
+ if IS_JUPYTER
+ else "Docker"
+ if IS_DOCKER
+ else platform.system()
+)
+TESTS_RUNNING = is_pytest_running() or is_github_action_running()
+set_sentry()
+
+# Apply monkey patches
+torch.save = torch_save
+if WINDOWS:
+ # Apply cv2 patches for non-ASCII and non-UTF characters in image paths
+ cv2.imread, cv2.imwrite, cv2.imshow = imread, imwrite, imshow
diff --git a/models_related/ultralytics/ultralytics/utils/autobatch.py b/models_related/ultralytics/ultralytics/utils/autobatch.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba750636676ad03e406d2046240673468beafeda
--- /dev/null
+++ b/models_related/ultralytics/ultralytics/utils/autobatch.py
@@ -0,0 +1,131 @@
+# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""Functions for estimating the best YOLO batch size to use a fraction of the available CUDA memory in PyTorch."""
+
+from __future__ import annotations
+
+import os
+from copy import deepcopy
+
+import numpy as np
+import torch
+
+from models_related.ultralytics.ultralytics.utils import DEFAULT_CFG, LOGGER, colorstr
+from models_related.ultralytics.ultralytics.utils.torch_utils import autocast, profile_ops
+
+
+def check_train_batch_size(
+ model: torch.nn.Module,
+ imgsz: int = 640,
+ amp: bool = True,
+ batch: int | float = -1,
+ max_num_obj: int = 1,
+ dataset_size: int = 0,
+) -> int:
+ """Compute optimal YOLO training batch size using the autobatch() function.
+
+ Args:
+ model (torch.nn.Module): YOLO model to check batch size for.
+ imgsz (int, optional): Image size used for training.
+ amp (bool, optional): Use automatic mixed precision if True.
+ batch (int | float, optional): Fraction of GPU memory to use. If -1, use default.
+ max_num_obj (int, optional): The maximum number of objects from dataset.
+ dataset_size (int, optional): Total number of training images. If > 0, batch size will not exceed this value.
+
+ Returns:
+ (int): Optimal batch size computed using the autobatch() function.
+
+ Notes:
+ If 0.0 < batch < 1.0, it's used as the fraction of GPU memory to use.
+ Otherwise, a default fraction of 0.6 is used.
+ """
+ with autocast(enabled=amp):
+ return autobatch(
+ deepcopy(model).train(),
+ imgsz,
+ fraction=batch if 0.0 < batch < 1.0 else 0.6,
+ max_num_obj=max_num_obj,
+ dataset_size=dataset_size,
+ )
+
+
+def autobatch(
+ model: torch.nn.Module,
+ imgsz: int = 640,
+ fraction: float = 0.60,
+ batch_size: int = DEFAULT_CFG.batch,
+ max_num_obj: int = 1,
+ dataset_size: int = 0,
+) -> int:
+ """Automatically estimate the best YOLO batch size to use a fraction of the available CUDA memory.
+
+ Args:
+ model (torch.nn.Module): YOLO model to compute batch size for.
+ imgsz (int, optional): The image size used as input for the YOLO model.
+ fraction (float, optional): The fraction of available CUDA memory to use.
+ batch_size (int, optional): The default batch size to use if an error is detected.
+ max_num_obj (int, optional): The maximum number of objects from dataset.
+ dataset_size (int, optional): Total number of training images. If > 0, batch size will not exceed this value.
+
+ Returns:
+ (int): The optimal batch size.
+ """
+ # Check device
+ prefix = colorstr("AutoBatch: ")
+ LOGGER.info(f"{prefix}Computing optimal batch size for imgsz={imgsz} at {fraction * 100}% CUDA memory utilization.")
+ device = next(model.parameters()).device # get model device
+ if device.type in {"cpu", "mps"}:
+ LOGGER.warning(f"{prefix}intended for CUDA devices, using default batch-size {batch_size}")
+ return batch_size
+ if torch.backends.cudnn.benchmark:
+ LOGGER.warning(f"{prefix}Requires torch.backends.cudnn.benchmark=False, using default batch-size {batch_size}")
+ return batch_size
+
+ # Inspect CUDA memory
+ gb = 1 << 30 # bytes to GiB (1024 ** 3)
+ d = f"CUDA:{os.getenv('CUDA_VISIBLE_DEVICES', '0').strip()[0]}" # 'CUDA:0'
+ properties = torch.cuda.get_device_properties(device) # device properties
+ t = properties.total_memory / gb # GiB total
+ r = torch.cuda.memory_reserved(device) / gb # GiB reserved
+ a = torch.cuda.memory_allocated(device) / gb # GiB allocated
+ f = t - (r + a) # GiB free
+ LOGGER.info(f"{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free")
+
+ # Profile batch sizes
+ batch_sizes = [1, 2, 4, 8, 16] if t < 16 else [1, 2, 4, 8, 16, 32, 64]
+ if dataset_size > 0:
+ batch_sizes = [b for b in batch_sizes if b <= dataset_size]
+ ch = model.yaml.get("channels", 3)
+ try:
+ img = [torch.empty(b, ch, imgsz, imgsz) for b in batch_sizes]
+ results = profile_ops(img, model, n=1, device=device, max_num_obj=max_num_obj)
+
+ # Fit a solution
+ xy = [
+ [x, y[2]]
+ for i, (x, y) in enumerate(zip(batch_sizes, results))
+ if y # valid result
+ and isinstance(y[2], (int, float)) # is numeric
+ and 0 < y[2] < t # between 0 and GPU limit
+ and (i == 0 or not results[i - 1] or y[2] > results[i - 1][2]) # first item or increasing memory
+ ]
+ fit_x, fit_y = zip(*xy) if xy else ([], [])
+ p = np.polyfit(fit_x, fit_y, deg=1) # first-degree (linear) polynomial fit
+ b = int((round(f * fraction) - p[1]) / p[0]) # y intercept (optimal batch size)
+ if None in results: # some sizes failed
+ i = results.index(None) # first fail index
+ if b >= batch_sizes[i]: # y intercept above failure point
+ b = batch_sizes[max(i - 1, 0)] # select prior safe point
+ if b < 1 or b > 1024: # b outside of safe range
+ LOGGER.warning(f"{prefix}batch={b} outside safe range, using default batch-size {batch_size}.")
+ b = batch_size
+ if dataset_size > 0:
+ b = min(b, dataset_size)
+
+ fraction = (np.polyval(p, b) + r + a) / t # predicted fraction
+ LOGGER.info(f"{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%) ✅")
+ return b
+ except Exception as e:
+ LOGGER.warning(f"{prefix}error detected: {e}, using default batch-size {batch_size}.")
+ return batch_size
+ finally:
+ torch.cuda.empty_cache()
diff --git a/models_related/ultralytics/ultralytics/utils/autodevice.py b/models_related/ultralytics/ultralytics/utils/autodevice.py
new file mode 100644
index 0000000000000000000000000000000000000000..e656ba1d196a99535425483cf075447aa353fde3
--- /dev/null
+++ b/models_related/ultralytics/ultralytics/utils/autodevice.py
@@ -0,0 +1,207 @@
+# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+
+from __future__ import annotations
+
+import random
+from typing import Any
+
+from models_related.ultralytics.ultralytics.utils import LOGGER
+
+
+class GPUInfo:
+ """Manages NVIDIA GPU information via pynvml with robust error handling.
+
+ Provides methods to query detailed GPU statistics (utilization, memory, temp, power) and select the most idle GPUs
+ based on configurable criteria. It safely handles the absence or initialization failure of the pynvml library by
+ logging warnings and disabling related features, preventing application crashes.
+
+ Includes fallback logic using `torch.cuda` for basic device counting if NVML is unavailable during GPU
+ selection. Manages NVML initialization and shutdown internally.
+
+ Attributes:
+ pynvml (module | None): The `pynvml` module if successfully imported and initialized, otherwise `None`.
+ nvml_available (bool): Indicates if `pynvml` is ready for use. True if `nvmlInit()` succeeded, False otherwise.
+ gpu_stats (list[dict[str, Any]]): A list of dictionaries, each holding stats for one GPU, populated on
+ initialization and by `refresh_stats()`. Keys include: 'index', 'name', 'utilization' (%), 'memory_used' (MiB),
+ 'memory_total' (MiB), 'memory_free' (MiB), 'temperature' (C), 'power_draw' (W), 'power_limit' (W or 'N/A').
+ Empty if NVML is unavailable or queries fail.
+
+ Methods:
+ refresh_stats: Refresh the internal gpu_stats list by querying NVML.
+ print_status: Print GPU status in a compact table format using current stats.
+ select_idle_gpu: Select the most idle GPUs based on utilization and free memory.
+ shutdown: Shut down NVML if it was initialized.
+
+ Examples:
+ Initialize GPUInfo and print status
+ >>> gpu_info = GPUInfo()
+ >>> gpu_info.print_status()
+
+ Select idle GPUs with minimum memory requirements
+ >>> selected = gpu_info.select_idle_gpu(count=2, min_memory_fraction=0.2)
+ >>> print(f"Selected GPU indices: {selected}")
+ """
+
+ def __init__(self):
+ """Initialize GPUInfo, attempting to import and initialize pynvml."""
+ self.pynvml: Any | None = None
+ self.nvml_available: bool = False
+ self.gpu_stats: list[dict[str, Any]] = []
+
+ try:
+ import pynvml # scoped as slow import
+
+ self.pynvml = pynvml
+ pynvml.nvmlInit()
+ self.nvml_available = True
+ self.refresh_stats()
+ except Exception as e:
+ LOGGER.warning(f"Failed to initialize pynvml, GPU stats disabled: {e}")
+
+ def __del__(self):
+ """Ensure NVML is shut down when the object is garbage collected."""
+ self.shutdown()
+
+ def shutdown(self):
+ """Shut down NVML if it was initialized."""
+ if self.nvml_available and self.pynvml:
+ try:
+ self.pynvml.nvmlShutdown()
+ except Exception:
+ pass
+ self.nvml_available = False
+
+ def refresh_stats(self):
+ """Refresh the internal gpu_stats list by querying NVML."""
+ self.gpu_stats = []
+ if not self.nvml_available or not self.pynvml:
+ return
+
+ try:
+ device_count = self.pynvml.nvmlDeviceGetCount()
+ self.gpu_stats.extend(self._get_device_stats(i) for i in range(device_count))
+ except Exception as e:
+ LOGGER.warning(f"Error during device query: {e}")
+ self.gpu_stats = []
+
+ def _get_device_stats(self, index: int) -> dict[str, Any]:
+ """Get stats for a single GPU device."""
+ handle = self.pynvml.nvmlDeviceGetHandleByIndex(index)
+ memory = self.pynvml.nvmlDeviceGetMemoryInfo(handle)
+ util = self.pynvml.nvmlDeviceGetUtilizationRates(handle)
+
+ def safe_get(func, *args, default=-1, divisor=1):
+ try:
+ val = func(*args)
+ return val // divisor if divisor != 1 and isinstance(val, (int, float)) else val
+ except Exception:
+ return default
+
+ temp_type = getattr(self.pynvml, "NVML_TEMPERATURE_GPU", -1)
+
+ return {
+ "index": index,
+ "name": self.pynvml.nvmlDeviceGetName(handle),
+ "utilization": util.gpu if util else -1,
+ "memory_used": memory.used >> 20 if memory else -1, # Convert bytes to MiB
+ "memory_total": memory.total >> 20 if memory else -1,
+ "memory_free": memory.free >> 20 if memory else -1,
+ "temperature": safe_get(self.pynvml.nvmlDeviceGetTemperature, handle, temp_type),
+ "power_draw": safe_get(self.pynvml.nvmlDeviceGetPowerUsage, handle, divisor=1000), # Convert mW to W
+ "power_limit": safe_get(self.pynvml.nvmlDeviceGetEnforcedPowerLimit, handle, divisor=1000),
+ }
+
+ def print_status(self):
+ """Print GPU status in a compact table format using current stats."""
+ self.refresh_stats()
+ if not self.gpu_stats:
+ LOGGER.warning("No GPU stats available.")
+ return
+
+ stats = self.gpu_stats
+ name_len = max(len(gpu.get("name", "N/A")) for gpu in stats)
+ hdr = f"{'Idx':<3} {'Name':<{name_len}} {'Util':>6} {'Mem (MiB)':>15} {'Temp':>5} {'Pwr (W)':>10}"
+ LOGGER.info(f"\n--- GPU Status ---\n{hdr}\n{'-' * len(hdr)}")
+
+ for gpu in stats:
+ u = f"{gpu['utilization']:>5}%" if gpu["utilization"] >= 0 else " N/A "
+ m = f"{gpu['memory_used']:>6}/{gpu['memory_total']:<6}" if gpu["memory_used"] >= 0 else " N/A / N/A "
+ t = f"{gpu['temperature']}C" if gpu["temperature"] >= 0 else " N/A "
+ p = f"{gpu['power_draw']:>3}/{gpu['power_limit']:<3}" if gpu["power_draw"] >= 0 else " N/A "
+
+ LOGGER.info(f"{gpu.get('index'):<3d} {gpu.get('name', 'N/A'):<{name_len}} {u:>6} {m:>15} {t:>5} {p:>10}")
+
+ LOGGER.info(f"{'-' * len(hdr)}\n")
+
+ def select_idle_gpu(
+ self, count: int = 1, min_memory_fraction: float = 0, min_util_fraction: float = 0
+ ) -> list[int]:
+ """Select the most idle GPUs based on utilization and free memory.
+
+ Args:
+ count (int): The number of idle GPUs to select.
+ min_memory_fraction (float): Minimum free memory required as a fraction of total memory.
+ min_util_fraction (float): Minimum free utilization rate required from 0.0 - 1.0.
+
+ Returns:
+ (list[int]): Indices of the selected GPUs, sorted by idleness (lowest utilization first).
+
+ Notes:
+ Returns fewer than 'count' if not enough qualify or exist.
+ Returns empty list if NVML stats are unavailable or no GPUs meet the criteria.
+ """
+ assert min_memory_fraction <= 1.0, f"min_memory_fraction must be <= 1.0, got {min_memory_fraction}"
+ assert min_util_fraction <= 1.0, f"min_util_fraction must be <= 1.0, got {min_util_fraction}"
+ criteria = (
+ f"free memory >= {min_memory_fraction * 100:.1f}% and free utilization >= {min_util_fraction * 100:.1f}%"
+ )
+ LOGGER.info(f"Searching for {count} idle GPUs with {criteria}...")
+
+ if count <= 0:
+ return []
+
+ self.refresh_stats()
+ if not self.gpu_stats:
+ LOGGER.warning("NVML stats unavailable.")
+ return []
+
+ # Filter and sort eligible GPUs
+ eligible_gpus = [
+ gpu
+ for gpu in self.gpu_stats
+ if gpu.get("memory_free", 0) / gpu.get("memory_total", 1) >= min_memory_fraction
+ and (100 - gpu.get("utilization", 100)) >= min_util_fraction * 100
+ ]
+ # Random tiebreaker prevents race conditions when multiple processes start simultaneously
+ # and all GPUs appear equally idle (same utilization and free memory)
+ eligible_gpus.sort(key=lambda x: (x.get("utilization", 101), -x.get("memory_free", 0), random.random()))
+
+ # Select top 'count' indices
+ selected = [gpu["index"] for gpu in eligible_gpus[:count]]
+
+ if selected:
+ if len(selected) < count:
+ LOGGER.warning(f"Requested {count} GPUs but only {len(selected)} met the idle criteria.")
+ LOGGER.info(f"Selected idle CUDA devices {selected}")
+ else:
+ LOGGER.warning(f"No GPUs met criteria ({criteria}).")
+
+ return selected
+
+
+if __name__ == "__main__":
+ required_free_mem_fraction = 0.2 # Require 20% free VRAM
+ required_free_util_fraction = 0.2 # Require 20% free utilization
+ num_gpus_to_select = 1
+
+ gpu_info = GPUInfo()
+ gpu_info.print_status()
+
+ if selected := gpu_info.select_idle_gpu(
+ count=num_gpus_to_select,
+ min_memory_fraction=required_free_mem_fraction,
+ min_util_fraction=required_free_util_fraction,
+ ):
+ print(f"\n==> Using selected GPU indices: {selected}")
+ devices = [f"cuda:{idx}" for idx in selected]
+ print(f" Target devices: {devices}")
diff --git a/models_related/ultralytics/ultralytics/utils/benchmarks.py b/models_related/ultralytics/ultralytics/utils/benchmarks.py
new file mode 100644
index 0000000000000000000000000000000000000000..016655e49bd08ca04ca3b891d72efac469093758
--- /dev/null
+++ b/models_related/ultralytics/ultralytics/utils/benchmarks.py
@@ -0,0 +1,769 @@
+# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""
+Benchmark YOLO model formats for speed and accuracy.
+
+Usage:
+ from ultralytics.utils.benchmarks import ProfileModels, benchmark
+ ProfileModels(['yolo26n.yaml', 'yolov8s.yaml']).run()
+ benchmark(model='yolo26n.pt', imgsz=160)
+
+Format | `format=argument` | Model
+--- | --- | ---
+PyTorch | - | yolo26n.pt
+TorchScript | `torchscript` | yolo26n.torchscript
+ONNX | `onnx` | yolo26n.onnx
+OpenVINO | `openvino` | yolo26n_openvino_model/
+TensorRT | `engine` | yolo26n.engine
+CoreML | `coreml` | yolo26n.mlpackage
+TensorFlow SavedModel | `saved_model` | yolo26n_saved_model/
+TensorFlow GraphDef | `pb` | yolo26n.pb
+TensorFlow Lite | `tflite` | yolo26n.tflite
+TensorFlow Edge TPU | `edgetpu` | yolo26n_edgetpu.tflite
+TensorFlow.js | `tfjs` | yolo26n_web_model/
+PaddlePaddle | `paddle` | yolo26n_paddle_model/
+MNN | `mnn` | yolo26n.mnn
+NCNN | `ncnn` | yolo26n_ncnn_model/
+IMX | `imx` | yolo26n_imx_model/
+RKNN | `rknn` | yolo26n_rknn_model/
+ExecuTorch | `executorch` | yolo26n_executorch_model/
+Axelera AI | `axelera` | yolo26n_axelera_model/
+"""
+
+from __future__ import annotations
+
+import glob
+import os
+import platform
+import re
+import shutil
+import time
+from copy import deepcopy
+from pathlib import Path
+
+import numpy as np
+import torch.cuda
+
+from models_related.ultralytics.ultralytics import YOLO, YOLOWorld
+from models_related.ultralytics.ultralytics.cfg import TASK2DATA, TASK2METRIC
+from models_related.ultralytics.ultralytics.engine.exporter import export_formats
+from models_related.ultralytics.ultralytics.nn.modules import Segment26
+from models_related.ultralytics.ultralytics.utils import (
+ ARM64,
+ ASSETS,
+ ASSETS_URL,
+ IS_DOCKER,
+ IS_JETSON,
+ LINUX,
+ LOGGER,
+ MACOS,
+ TQDM,
+ WEIGHTS_DIR,
+ YAML,
+)
+from models_related.ultralytics.ultralytics.utils.checks import IS_PYTHON_MINIMUM_3_13, check_imgsz, check_requirements, check_yolo, is_rockchip
+from models_related.ultralytics.ultralytics.utils.downloads import safe_download
+from models_related.ultralytics.ultralytics.utils.files import file_size
+from models_related.ultralytics.ultralytics.utils.torch_utils import get_cpu_info, select_device
+
+
+def benchmark(
+ model=WEIGHTS_DIR / "yolo26n.pt",
+ data=None,
+ imgsz=160,
+ half=False,
+ int8=False,
+ device="cpu",
+ verbose=False,
+ eps=1e-3,
+ format="",
+ **kwargs,
+):
+ """Benchmark a YOLO model across different formats for speed and accuracy.
+
+ Args:
+ model (str | Path): Path to the model file or directory.
+ data (str | None): Dataset to evaluate on, inherited from TASK2DATA if not passed.
+ imgsz (int): Image size for the benchmark.
+ half (bool): Use half-precision for the model if True.
+ int8 (bool): Use int8-precision for the model if True.
+ device (str): Device to run the benchmark on, either 'cpu' or 'cuda'.
+ verbose (bool | float): If True or a float, assert benchmarks pass with given metric.
+ eps (float): Epsilon value for divide by zero prevention.
+ format (str): Export format for benchmarking. If not supplied all formats are benchmarked.
+ **kwargs (Any): Additional keyword arguments for exporter.
+
+ Returns:
+ (polars.DataFrame): A Polars DataFrame with benchmark results for each format, including file size, metric, and
+ inference time.
+
+ Examples:
+ Benchmark a YOLO model with default settings:
+ >>> from ultralytics.utils.benchmarks import benchmark
+ >>> benchmark(model="yolo26n.pt", imgsz=640)
+ """
+ imgsz = check_imgsz(imgsz)
+ assert imgsz[0] == imgsz[1] if isinstance(imgsz, list) else True, "benchmark() only supports square imgsz."
+
+ import polars as pl # scope for faster 'import ultralytics'
+
+ pl.Config.set_tbl_cols(-1) # Show all columns
+ pl.Config.set_tbl_rows(-1) # Show all rows
+ pl.Config.set_tbl_width_chars(-1) # No width limit
+ pl.Config.set_tbl_hide_column_data_types(True) # Hide data types
+ pl.Config.set_tbl_hide_dataframe_shape(True) # Hide shape info
+ pl.Config.set_tbl_formatting("ASCII_BORDERS_ONLY_CONDENSED")
+
+ device = select_device(device, verbose=False)
+ if isinstance(model, (str, Path)):
+ model = YOLO(model)
+ data = data or TASK2DATA[model.task] # task to dataset, i.e. coco8.yaml for task=detect
+ key = TASK2METRIC[model.task] # task to metric, i.e. metrics/mAP50-95(B) for task=detect
+
+ y = []
+ t0 = time.time()
+
+ format_arg = format.lower()
+ if format_arg:
+ formats = frozenset(export_formats()["Argument"])
+ assert format in formats, f"Expected format to be one of {formats}, but got '{format_arg}'."
+ for name, format, suffix, cpu, gpu, valid_args, _ in zip(*export_formats().values()):
+ emoji, filename = "❌", None # export defaults
+ try:
+ if format_arg and format_arg != format:
+ continue
+ if (
+ IS_PYTHON_MINIMUM_3_13
+ and not format_arg
+ and format in {"saved_model", "pb", "tflite", "edgetpu", "tfjs"}
+ ):
+ continue
+
+ # Checks
+ if format == "pb":
+ assert model.task != "obb", "TensorFlow GraphDef not supported for OBB task"
+ elif format == "edgetpu":
+ assert LINUX and not ARM64, "Edge TPU export only supported on non-aarch64 Linux"
+ assert shutil.which("edgetpu_compiler"), "Edge TPU benchmark requires edgetpu_compiler"
+ elif format == "tfjs":
+ assert not (LINUX and ARM64), "TF.js export not supported on ARM64 Linux"
+ elif format == "coreml":
+ assert MACOS or (LINUX and not ARM64), "CoreML export only supported on macOS and non-aarch64 Linux"
+ # coremltools deadlocks after OpenVINO on macOS Python 3.13 (conflicting OpenMP runtimes); CoreML
+ # is still benchmarked on non-aarch64 Linux Python 3.13.
+ assert not (MACOS and IS_PYTHON_MINIMUM_3_13), (
+ "CoreML not benchmarked on macOS Python>=3.13 (coremltools/OpenVINO OpenMP deadlock)"
+ )
+ if format in {"saved_model", "pb", "tflite", "edgetpu", "tfjs"}:
+ assert not isinstance(model, YOLOWorld), "YOLOWorldv2 TensorFlow exports not supported by onnx2tf yet"
+ # assert not IS_PYTHON_MINIMUM_3_12, "TFLite exports not supported on Python>=3.12 yet"
+ if format == "paddle":
+ assert not isinstance(model, YOLOWorld), "YOLOWorldv2 Paddle exports not supported yet"
+ assert model.task != "obb", "Paddle OBB bug https://github.com/PaddlePaddle/Paddle/issues/72024"
+ assert (LINUX and not IS_JETSON) or MACOS, "Windows and Jetson Paddle exports not supported yet"
+ # PaddlePaddle export works standalone on Python 3.13 but its native protobuf clashes with the
+ # protobuf>=6.31.1 that TensorFlow loads earlier in this shared benchmark process, causing a segfault.
+ assert not IS_PYTHON_MINIMUM_3_13, (
+ "PaddlePaddle not benchmarked on Python>=3.13 (protobuf ABI conflict with TensorFlow)"
+ )
+ if format == "mnn":
+ assert not isinstance(model, YOLOWorld), "YOLOWorldv2 MNN exports not supported yet"
+ # MNN export works standalone on Python 3.13 but its ONNX-parsing protobuf clashes with the
+ # protobuf>=6.31.1 that TensorFlow loads earlier in this shared benchmark process, aborting the run.
+ assert not IS_PYTHON_MINIMUM_3_13, (
+ "MNN not benchmarked on Python>=3.13 (protobuf ABI conflict with TensorFlow)"
+ )
+ if format == "ncnn":
+ assert not isinstance(model, YOLOWorld), "YOLOWorldv2 NCNN exports not supported yet"
+ if format == "imx":
+ assert not isinstance(model, YOLOWorld), "YOLOWorldv2 IMX exports not supported"
+ assert model.task in {"detect", "classify", "pose", "segment"}, (
+ "IMX export is only supported for detection, classification, pose estimation and segmentation tasks"
+ )
+ assert "C2f" in model.__str__(), "IMX only supported for YOLOv8n and YOLO11n"
+ if format == "rknn":
+ assert not isinstance(model, YOLOWorld), "YOLOWorldv2 RKNN exports not supported yet"
+ assert LINUX, "RKNN only supported on Linux"
+ assert not is_rockchip(), "RKNN Inference only supported on Rockchip devices"
+ if format == "executorch":
+ assert not isinstance(model, YOLOWorld), "YOLOWorldv2 ExecuTorch exports not supported yet"
+ if format == "axelera":
+ assert not isinstance(model, YOLOWorld), "YOLOWorldv2 Axelera exports not supported"
+ assert LINUX and not (ARM64 and IS_DOCKER), (
+ "export is only supported on Linux and is not supported on ARM64 Docker."
+ )
+ assert not (model.task == "segment" and any(isinstance(m, Segment26) for m in model.model.modules())), (
+ "Axelera export does not currently support YOLO26 segmentation models"
+ )
+ if "cpu" in device.type:
+ assert cpu, "inference not supported on CPU"
+ if "cuda" in device.type:
+ assert gpu, "inference not supported on GPU"
+
+ # Export
+ if format == "-":
+ filename = model.pt_path or model.ckpt_path or model.model_name
+ exported_model = deepcopy(model) # PyTorch format
+ else:
+ export_data = data if "data" in valid_args else None
+ filename = deepcopy(model).export(
+ imgsz=imgsz,
+ format=format,
+ half=half,
+ int8=int8,
+ data=export_data,
+ device=device,
+ verbose=False,
+ **kwargs,
+ )
+ exported_model = YOLO(filename, task=model.task)
+ assert suffix in str(filename), "export failed"
+ emoji = "❎" # indicates export succeeded
+
+ # Predict
+ assert model.task != "pose" or format != "pb", "GraphDef Pose inference is not supported"
+ assert format not in {"edgetpu", "tfjs"}, "inference not supported"
+ assert format != "coreml" or platform.system() == "Darwin", "inference only supported on macOS>=10.13"
+ assert format != "axelera", "inference only supported on Axelera hardware"
+ exported_model.predict(ASSETS / "bus.jpg", imgsz=imgsz, device=device, half=half, verbose=False)
+
+ # Validate
+ results = exported_model.val(
+ data=data,
+ batch=1,
+ imgsz=imgsz,
+ plots=False,
+ device=device,
+ half=half,
+ int8=int8,
+ verbose=False,
+ conf=0.001, # all the pre-set benchmark mAP values are based on conf=0.001
+ )
+ metric, speed = results.results_dict[key], results.speed["inference"]
+ fps = round(1000 / (speed + eps), 2) # frames per second
+ y.append([name, "✅", round(file_size(filename), 1), round(metric, 4), round(speed, 2), fps])
+ except Exception as e:
+ if verbose:
+ assert type(e) is AssertionError, f"Benchmark failure for {name}: {e}"
+ LOGGER.error(f"Benchmark failure for {name}: {e}")
+ y.append([name, emoji, round(file_size(filename), 1), None, None, None]) # mAP, t_inference
+
+ # Print results
+ check_yolo(device=device) # print system info
+ df = pl.DataFrame(y, schema=["Format", "Status❔", "Size (MB)", key, "Inference time (ms/im)", "FPS"], orient="row")
+ df = df.with_row_index(" ", offset=1) # add index info
+ df_display = df.with_columns(pl.all().cast(pl.String).fill_null("-"))
+
+ name = model.model_name
+ dt = time.time() - t0
+ legend = "Benchmarks legend: - ✅ Success - ❎ Export passed but validation failed - ❌️ Export failed"
+ s = f"\nBenchmarks complete for {name} on {data} at imgsz={imgsz} ({dt:.2f}s)\n{legend}\n{df_display}\n"
+ LOGGER.info(s)
+ with open("benchmarks.log", "a", errors="ignore", encoding="utf-8") as f:
+ f.write(s)
+
+ if verbose and isinstance(verbose, float):
+ metrics = df[key].to_numpy() # values to compare to floor
+ floor = verbose # minimum metric floor to pass, i.e. = 0.29 mAP for YOLOv5n
+ assert all(x > floor for x in metrics if not np.isnan(x)), f"Benchmark failure: metric(s) < floor {floor}"
+
+ return df_display
+
+
+class RF100Benchmark:
+ """Benchmark YOLO model performance on the RF100 dataset collection.
+
+ This class provides functionality to download, process, and evaluate YOLO models on the RF100 datasets.
+
+ Attributes:
+ ds_names (list[str]): Names of datasets used for benchmarking.
+ ds_cfg_list (list[Path]): List of paths to dataset configuration files.
+ rf (Roboflow | None): Roboflow instance for accessing datasets.
+ val_metrics (list[str]): Metrics used for validation.
+
+ Methods:
+ set_key: Set Roboflow API key for accessing datasets.
+ parse_dataset: Parse dataset links and download datasets.
+ fix_yaml: Fix train and validation paths in YAML files.
+ evaluate: Evaluate model performance on validation results.
+ """
+
+ def __init__(self):
+ """Initialize the RF100Benchmark class for benchmarking YOLO model performance on RF100 datasets."""
+ self.ds_names = []
+ self.ds_cfg_list = []
+ self.rf = None
+ self.val_metrics = ["class", "images", "targets", "precision", "recall", "map50", "map95"]
+
+ def set_key(self, api_key: str):
+ """Set Roboflow API key for processing.
+
+ Args:
+ api_key (str): The API key.
+
+ Examples:
+ Set the Roboflow API key for accessing datasets:
+ >>> benchmark = RF100Benchmark()
+ >>> benchmark.set_key("your_roboflow_api_key")
+ """
+ check_requirements("roboflow")
+ from roboflow import Roboflow
+
+ self.rf = Roboflow(api_key=api_key)
+
+ def parse_dataset(self, ds_link_txt: str = "datasets_links.txt"):
+ """Parse dataset links and download datasets.
+
+ Args:
+ ds_link_txt (str): Path to the file containing dataset links.
+
+ Returns:
+ (tuple[list[str], list[Path]]): List of dataset names and list of paths to dataset configuration files.
+
+ Examples:
+ >>> benchmark = RF100Benchmark()
+ >>> benchmark.set_key("api_key")
+ >>> benchmark.parse_dataset("datasets_links.txt")
+ """
+ (shutil.rmtree("rf-100"), os.mkdir("rf-100")) if os.path.exists("rf-100") else os.mkdir("rf-100")
+ os.chdir("rf-100")
+ os.mkdir("ultralytics-benchmarks")
+ safe_download(f"{ASSETS_URL}/datasets_links.txt")
+
+ with open(ds_link_txt, encoding="utf-8") as file:
+ for line in file:
+ try:
+ _, _url, workspace, project, version = re.split("/+", line.strip())
+ self.ds_names.append(project)
+ proj_version = f"{project}-{version}"
+ if not Path(proj_version).exists():
+ self.rf.workspace(workspace).project(project).version(version).download("yolov8")
+ else:
+ LOGGER.info("Dataset already downloaded.")
+ self.ds_cfg_list.append(Path.cwd() / proj_version / "data.yaml")
+ except Exception:
+ continue
+
+ return self.ds_names, self.ds_cfg_list
+
+ @staticmethod
+ def fix_yaml(path: Path):
+ """Fix the train and validation paths in a given YAML file."""
+ yaml_data = YAML.load(path)
+ yaml_data["train"] = "train/images"
+ yaml_data["val"] = "valid/images"
+ YAML.save(path, yaml_data)
+
+ def evaluate(self, yaml_path: str, val_log_file: str, eval_log_file: str, list_ind: int):
+ """Evaluate model performance on validation results.
+
+ Args:
+ yaml_path (str): Path to the YAML configuration file.
+ val_log_file (str): Path to the validation log file.
+ eval_log_file (str): Path to the evaluation log file.
+ list_ind (int): Index of the current dataset in the list.
+
+ Returns:
+ (float): The mean average precision (mAP) value for the evaluated model.
+
+ Examples:
+ Evaluate a model on a specific dataset
+ >>> benchmark = RF100Benchmark()
+ >>> benchmark.evaluate("path/to/data.yaml", "path/to/val_log.txt", "path/to/eval_log.txt", 0)
+ """
+ skip_symbols = ["🚀", "⚠️", "💡", "❌"]
+ class_names = YAML.load(yaml_path)["names"]
+ with open(val_log_file, encoding="utf-8") as f:
+ lines = f.readlines()
+ eval_lines = []
+ for line in lines:
+ if any(symbol in line for symbol in skip_symbols):
+ continue
+ entries = line.split(" ")
+ entries = list(filter(lambda val: val != "", entries))
+ entries = [e.strip("\n") for e in entries]
+ eval_lines.extend(
+ {
+ "class": entries[0],
+ "images": entries[1],
+ "targets": entries[2],
+ "precision": entries[3],
+ "recall": entries[4],
+ "map50": entries[5],
+ "map95": entries[6],
+ }
+ for e in entries
+ if e in class_names or (e == "all" and "(AP)" not in entries and "(AR)" not in entries)
+ )
+ map_val = 0.0
+ if len(eval_lines) > 1:
+ LOGGER.info("Multiple dicts found")
+ for lst in eval_lines:
+ if lst["class"] == "all":
+ map_val = lst["map50"]
+ else:
+ LOGGER.info("Single dict found")
+ map_val = next(res["map50"] for res in eval_lines)
+
+ with open(eval_log_file, "a", encoding="utf-8") as f:
+ f.write(f"{self.ds_names[list_ind]}: {map_val}\n")
+
+ return float(map_val)
+
+
+class ProfileModels:
+ """ProfileModels class for profiling different models on ONNX and TensorRT.
+
+ This class profiles the performance of different models, returning results such as model speed and FLOPs.
+
+ Attributes:
+ paths (list[str]): Paths of the models to profile.
+ num_timed_runs (int): Number of timed runs for the profiling.
+ num_warmup_runs (int): Number of warmup runs before profiling.
+ min_time (float): Minimum number of seconds to profile for.
+ imgsz (int): Image size used in the models.
+ half (bool): Flag to indicate whether to use FP16 half-precision for TensorRT profiling.
+ trt (bool): Flag to indicate whether to profile using TensorRT.
+ device (torch.device): Device used for profiling.
+
+ Methods:
+ run: Profile YOLO models for speed and accuracy across various formats.
+ get_files: Get all relevant model files.
+ get_onnx_model_info: Extract metadata from an ONNX model.
+ iterative_sigma_clipping: Apply sigma clipping to remove outliers.
+ profile_tensorrt_model: Profile a TensorRT model.
+ profile_onnx_model: Profile an ONNX model.
+ generate_table_row: Generate a table row with model metrics.
+ generate_results_dict: Generate a dictionary of profiling results.
+ print_table: Print a formatted table of results.
+
+ Examples:
+ Profile models and print results
+ >>> from ultralytics.utils.benchmarks import ProfileModels
+ >>> profiler = ProfileModels(["yolo26n.yaml", "yolov8s.yaml"], imgsz=640)
+ >>> profiler.run()
+ """
+
+ def __init__(
+ self,
+ paths: list[str],
+ num_timed_runs: int = 100,
+ num_warmup_runs: int = 10,
+ min_time: float = 60,
+ imgsz: int = 640,
+ half: bool = True,
+ trt: bool = True,
+ device: torch.device | str | None = None,
+ ):
+ """Initialize the ProfileModels class for profiling models.
+
+ Args:
+ paths (list[str]): List of paths of the models to be profiled.
+ num_timed_runs (int): Number of timed runs for the profiling.
+ num_warmup_runs (int): Number of warmup runs before the actual profiling starts.
+ min_time (float): Minimum time in seconds for profiling a model.
+ imgsz (int): Size of the image used during profiling.
+ half (bool): Flag to indicate whether to use FP16 half-precision for TensorRT profiling.
+ trt (bool): Flag to indicate whether to profile using TensorRT.
+ device (torch.device | str | None): Device used for profiling. If None, it is determined automatically.
+
+ Notes:
+ FP16 'half' argument option removed for ONNX as slower on CPU than FP32.
+ """
+ self.paths = paths
+ self.num_timed_runs = num_timed_runs
+ self.num_warmup_runs = num_warmup_runs
+ self.min_time = min_time
+ self.imgsz = imgsz
+ self.half = half
+ self.trt = trt # run TensorRT profiling
+ self.device = device if isinstance(device, torch.device) else select_device(device)
+
+ def run(self):
+ """Profile YOLO models for speed and accuracy across various formats including ONNX and TensorRT.
+
+ Returns:
+ (list[dict]): List of dictionaries containing profiling results for each model.
+
+ Examples:
+ Profile models and print results
+ >>> from ultralytics.utils.benchmarks import ProfileModels
+ >>> profiler = ProfileModels(["yolo26n.yaml", "yolo11s.yaml"])
+ >>> results = profiler.run()
+ """
+ files = self.get_files()
+
+ if not files:
+ LOGGER.warning("No matching *.pt or *.onnx files found.")
+ return []
+
+ table_rows = []
+ output = []
+ for file in files:
+ engine_file = file.with_suffix(".engine")
+ if file.suffix in {".pt", ".yaml", ".yml"}:
+ model = YOLO(str(file))
+ model.fuse() # to report correct params and GFLOPs in model.info()
+ model_info = model.info(imgsz=self.imgsz)
+ if self.trt and self.device.type != "cpu" and not engine_file.is_file():
+ engine_file = model.export(
+ format="engine",
+ half=self.half,
+ imgsz=self.imgsz,
+ device=self.device,
+ verbose=False,
+ )
+ onnx_file = model.export(
+ format="onnx",
+ imgsz=self.imgsz,
+ device=self.device,
+ verbose=False,
+ )
+ elif file.suffix == ".onnx":
+ model_info = self.get_onnx_model_info(file)
+ onnx_file = file
+ else:
+ continue
+
+ t_engine = self.profile_tensorrt_model(str(engine_file))
+ t_onnx = self.profile_onnx_model(str(onnx_file))
+ table_rows.append(self.generate_table_row(file.stem, t_onnx, t_engine, model_info))
+ output.append(self.generate_results_dict(file.stem, t_onnx, t_engine, model_info))
+
+ self.print_table(table_rows)
+ return output
+
+ def get_files(self):
+ """Return a list of paths for all relevant model files given by the user.
+
+ Returns:
+ (list[Path]): List of Path objects for the model files.
+ """
+ files = []
+ for path in self.paths:
+ path = Path(path)
+ if path.is_dir():
+ extensions = ["*.pt", "*.onnx", "*.yaml"]
+ files.extend([file for ext in extensions for file in glob.glob(str(path / ext))])
+ elif path.suffix in {".pt", ".yaml", ".yml"}: # add non-existing
+ files.append(str(path))
+ else:
+ files.extend(glob.glob(str(path)))
+
+ LOGGER.info(f"Profiling: {sorted(files)}")
+ return [Path(file) for file in sorted(files)]
+
+ @staticmethod
+ def get_onnx_model_info(onnx_file: str):
+ """Extract metadata from an ONNX model file including layers, parameters, gradients, and FLOPs."""
+ return 0.0, 0.0, 0.0, 0.0 # return (num_layers, num_params, num_gradients, num_flops)
+
+ @staticmethod
+ def iterative_sigma_clipping(data: np.ndarray, sigma: float = 2, max_iters: int = 3):
+ """Apply iterative sigma clipping to data to remove outliers.
+
+ Args:
+ data (np.ndarray): Input data array.
+ sigma (float): Number of standard deviations to use for clipping.
+ max_iters (int): Maximum number of iterations for the clipping process.
+
+ Returns:
+ (np.ndarray): Clipped data array with outliers removed.
+ """
+ data = np.array(data)
+ for _ in range(max_iters):
+ mean, std = np.mean(data), np.std(data)
+ clipped_data = data[(data > mean - sigma * std) & (data < mean + sigma * std)]
+ if len(clipped_data) == len(data):
+ break
+ data = clipped_data
+ return data
+
+ def profile_tensorrt_model(self, engine_file: str, eps: float = 1e-3):
+ """Profile YOLO model performance with TensorRT, measuring average run time and standard deviation.
+
+ Args:
+ engine_file (str): Path to the TensorRT engine file.
+ eps (float): Small epsilon value to prevent division by zero.
+
+ Returns:
+ (tuple[float, float]): Mean and standard deviation of inference time in milliseconds.
+ """
+ if not self.trt or not Path(engine_file).is_file():
+ return 0.0, 0.0
+
+ # Model and input
+ model = YOLO(engine_file)
+ input_data = np.zeros((self.imgsz, self.imgsz, 3), dtype=np.uint8) # use uint8 for Classify
+
+ # Warmup runs
+ elapsed = 0.0
+ for _ in range(3):
+ start_time = time.time()
+ for _ in range(self.num_warmup_runs):
+ model(input_data, imgsz=self.imgsz, verbose=False)
+ elapsed = time.time() - start_time
+
+ # Compute number of runs as higher of min_time or num_timed_runs
+ num_runs = max(round(self.min_time / (elapsed + eps) * self.num_warmup_runs), self.num_timed_runs * 50)
+
+ # Timed runs
+ run_times = []
+ for _ in TQDM(range(num_runs), desc=engine_file):
+ results = model(input_data, imgsz=self.imgsz, verbose=False)
+ run_times.append(results[0].speed["inference"]) # Convert to milliseconds
+
+ run_times = self.iterative_sigma_clipping(np.array(run_times), sigma=2, max_iters=3) # sigma clipping
+ return np.mean(run_times), np.std(run_times)
+
+ @staticmethod
+ def check_dynamic(tensor_shape):
+ """Check whether the tensor shape in the ONNX model is dynamic."""
+ return not all(isinstance(dim, int) and dim >= 0 for dim in tensor_shape)
+
+ def profile_onnx_model(self, onnx_file: str, eps: float = 1e-3):
+ """Profile an ONNX model, measuring average inference time and standard deviation across multiple runs.
+
+ Args:
+ onnx_file (str): Path to the ONNX model file.
+ eps (float): Small epsilon value to prevent division by zero.
+
+ Returns:
+ (tuple[float, float]): Mean and standard deviation of inference time in milliseconds.
+ """
+ check_requirements([("onnxruntime", "onnxruntime-gpu")]) # either package meets requirements
+ import onnxruntime as ort
+
+ # Session with either 'TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'
+ sess_options = ort.SessionOptions()
+ sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
+ sess_options.intra_op_num_threads = 8 # Limit the number of threads
+ sess = ort.InferenceSession(onnx_file, sess_options, providers=["CPUExecutionProvider"])
+
+ input_data_dict = {}
+ for input_tensor in sess.get_inputs():
+ input_type = input_tensor.type
+ if self.check_dynamic(input_tensor.shape):
+ if len(input_tensor.shape) != 4 and self.check_dynamic(input_tensor.shape[1:]):
+ raise ValueError(f"Unsupported dynamic shape {input_tensor.shape} of {input_tensor.name}")
+ input_shape = (
+ (1, 3, self.imgsz, self.imgsz) if len(input_tensor.shape) == 4 else (1, *input_tensor.shape[1:])
+ )
+ else:
+ input_shape = input_tensor.shape
+
+ # Mapping ONNX datatype to numpy datatype
+ if "float16" in input_type:
+ input_dtype = np.float16
+ elif "float" in input_type:
+ input_dtype = np.float32
+ elif "double" in input_type:
+ input_dtype = np.float64
+ elif "int64" in input_type:
+ input_dtype = np.int64
+ elif "int32" in input_type:
+ input_dtype = np.int32
+ else:
+ raise ValueError(f"Unsupported ONNX datatype {input_type}")
+
+ input_data = np.random.rand(*input_shape).astype(input_dtype)
+ input_name = input_tensor.name
+ input_data_dict[input_name] = input_data
+
+ output_name = sess.get_outputs()[0].name
+
+ # Warmup runs
+ elapsed = 0.0
+ for _ in range(3):
+ start_time = time.time()
+ for _ in range(self.num_warmup_runs):
+ sess.run([output_name], input_data_dict)
+ elapsed = time.time() - start_time
+
+ # Compute number of runs as higher of min_time or num_timed_runs
+ num_runs = max(round(self.min_time / (elapsed + eps) * self.num_warmup_runs), self.num_timed_runs)
+
+ # Timed runs
+ run_times = []
+ for _ in TQDM(range(num_runs), desc=onnx_file):
+ start_time = time.time()
+ sess.run([output_name], input_data_dict)
+ run_times.append((time.time() - start_time) * 1000) # Convert to milliseconds
+
+ run_times = self.iterative_sigma_clipping(np.array(run_times), sigma=2, max_iters=5) # sigma clipping
+ return np.mean(run_times), np.std(run_times)
+
+ def generate_table_row(
+ self,
+ model_name: str,
+ t_onnx: tuple[float, float],
+ t_engine: tuple[float, float],
+ model_info: tuple[float, float, float, float],
+ ):
+ """Generate a table row string with model performance metrics.
+
+ Args:
+ model_name (str): Name of the model.
+ t_onnx (tuple): ONNX model inference time statistics (mean, std).
+ t_engine (tuple): TensorRT engine inference time statistics (mean, std).
+ model_info (tuple): Model information (layers, params, gradients, flops).
+
+ Returns:
+ (str): Formatted table row string with model metrics.
+ """
+ _layers, params, _gradients, flops = model_info
+ return (
+ f"| {model_name:18s} | {self.imgsz} | - | {t_onnx[0]:.1f}±{t_onnx[1]:.1f} ms | {t_engine[0]:.1f}±"
+ f"{t_engine[1]:.1f} ms | {params / 1e6:.1f} | {flops:.1f} |"
+ )
+
+ @staticmethod
+ def generate_results_dict(
+ model_name: str,
+ t_onnx: tuple[float, float],
+ t_engine: tuple[float, float],
+ model_info: tuple[float, float, float, float],
+ ):
+ """Generate a dictionary of profiling results.
+
+ Args:
+ model_name (str): Name of the model.
+ t_onnx (tuple): ONNX model inference time statistics (mean, std).
+ t_engine (tuple): TensorRT engine inference time statistics (mean, std).
+ model_info (tuple): Model information (layers, params, gradients, flops).
+
+ Returns:
+ (dict): Dictionary containing profiling results.
+ """
+ _layers, params, _gradients, flops = model_info
+ return {
+ "model/name": model_name,
+ "model/parameters": params,
+ "model/GFLOPs": round(flops, 3),
+ "model/speed_ONNX(ms)": round(t_onnx[0], 3),
+ "model/speed_TensorRT(ms)": round(t_engine[0], 3),
+ }
+
+ @staticmethod
+ def print_table(table_rows: list[str]):
+ """Print a formatted table of model profiling results.
+
+ Args:
+ table_rows (list[str]): List of formatted table row strings.
+ """
+ gpu = torch.cuda.get_device_name(0) if torch.cuda.is_available() else "GPU"
+ headers = [
+ "Model",
+ "size