mirror of
https://github.com/THU-MIG/yolov10.git
synced 2025-05-24 05:55:51 +08:00
ultralytics 8.0.178
PyPI deployment fix (#4891)
Co-authored-by: Eduardo Farinati <afxph8fc@duck.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
parent
dd2262e89a
commit
32f7c522b5
2
.github/workflows/publish.yml
vendored
2
.github/workflows/publish.yml
vendored
@ -47,7 +47,7 @@ jobs:
|
|||||||
print(f'Local version is {v_local}')
|
print(f'Local version is {v_local}')
|
||||||
print(f'PyPI version is {v_pypi}')
|
print(f'PyPI version is {v_pypi}')
|
||||||
d = [a - b for a, b in zip(v_local, v_pypi)] # diff
|
d = [a - b for a, b in zip(v_local, v_pypi)] # diff
|
||||||
increment = (d[0] == d[1] == 0) and d[2] == 1 # only publish if patch version increments by 1
|
increment = (d[0] == d[1] == 0) and (0 < d[2] < 3) # only publish if patch version increments by 1 or 2
|
||||||
os.system(f'echo "increment={increment}" >> $GITHUB_OUTPUT')
|
os.system(f'echo "increment={increment}" >> $GITHUB_OUTPUT')
|
||||||
os.system(f'echo "version={ultralytics.__version__}" >> $GITHUB_OUTPUT')
|
os.system(f'echo "version={ultralytics.__version__}" >> $GITHUB_OUTPUT')
|
||||||
if increment:
|
if increment:
|
||||||
|
@ -138,7 +138,7 @@ For a comprehensive list of tracking arguments, refer to the [ultralytics/cfg/tr
|
|||||||
|
|
||||||
### Persisting Tracks Loop
|
### Persisting Tracks Loop
|
||||||
|
|
||||||
Here is a Python script using OpenCV (`cv2`) and YOLOv8 to run object tracking on video frames. This script still assumes you have already installed the necessary packages (`opencv-python` and `ultralytics`).
|
Here is a Python script using OpenCV (`cv2`) and YOLOv8 to run object tracking on video frames. This script still assumes you have already installed the necessary packages (`opencv-python` and `ultralytics`). The `persist=True` argument tells the tracker than the current image or frame is the next in a sequence and to expect tracks from the previous image in the current image.
|
||||||
|
|
||||||
!!! example "Streaming for-loop with tracking"
|
!!! example "Streaming for-loop with tracking"
|
||||||
|
|
||||||
@ -312,3 +312,13 @@ Finally, after all threads have completed their task, the windows displaying the
|
|||||||
```
|
```
|
||||||
|
|
||||||
This example can easily be extended to handle more video files and models by creating more threads and applying the same methodology.
|
This example can easily be extended to handle more video files and models by creating more threads and applying the same methodology.
|
||||||
|
|
||||||
|
## Contribute New Trackers
|
||||||
|
|
||||||
|
Are you proficient in multi-object tracking and have successfully implemented or adapted a tracking algorithm with Ultralytics YOLO? We invite you to contribute to our Trackers section in [ultralytics/cfg/trackers](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/cfg/trackers)! Your real-world applications and solutions could be invaluable for users working on tracking tasks.
|
||||||
|
|
||||||
|
By contributing to this section, you help expand the scope of tracking solutions available within the Ultralytics YOLO framework, adding another layer of functionality and utility for the community.
|
||||||
|
|
||||||
|
To initiate your contribution, please refer to our [Contributing Guide](https://docs.ultralytics.com/help/contributing) for comprehensive instructions on submitting a Pull Request (PR) 🛠️. We are excited to see what you bring to the table!
|
||||||
|
|
||||||
|
Together, let's enhance the tracking capabilities of the Ultralytics YOLO ecosystem 🙏!
|
@ -189,7 +189,7 @@ Training settings for YOLO models refer to the various hyperparameters and confi
|
|||||||
| `project` | `None` | project name |
|
| `project` | `None` | project name |
|
||||||
| `name` | `None` | experiment name |
|
| `name` | `None` | experiment name |
|
||||||
| `exist_ok` | `False` | whether to overwrite existing experiment |
|
| `exist_ok` | `False` | whether to overwrite existing experiment |
|
||||||
| `pretrained` | `False` | whether to use a pretrained model |
|
| `pretrained` | `True` | (bool | str) whether to use a pretrained model (bool) or a model to load weights from (str) |
|
||||||
| `optimizer` | `'auto'` | optimizer to use, choices=[SGD, Adam, Adamax, AdamW, NAdam, RAdam, RMSProp, auto] |
|
| `optimizer` | `'auto'` | optimizer to use, choices=[SGD, Adam, Adamax, AdamW, NAdam, RAdam, RMSProp, auto] |
|
||||||
| `verbose` | `False` | whether to print verbose output |
|
| `verbose` | `False` | whether to print verbose output |
|
||||||
| `seed` | `0` | random seed for reproducibility |
|
| `seed` | `0` | random seed for reproducibility |
|
||||||
|
@ -88,7 +88,7 @@ The training settings for YOLO models encompass various hyperparameters and conf
|
|||||||
| `project` | `None` | project name |
|
| `project` | `None` | project name |
|
||||||
| `name` | `None` | experiment name |
|
| `name` | `None` | experiment name |
|
||||||
| `exist_ok` | `False` | whether to overwrite existing experiment |
|
| `exist_ok` | `False` | whether to overwrite existing experiment |
|
||||||
| `pretrained` | `False` | whether to use a pretrained model |
|
| `pretrained` | `True` | (bool | str) whether to use a pretrained model (bool) or a model to load weights from (str) |
|
||||||
| `optimizer` | `'auto'` | optimizer to use, choices=[SGD, Adam, Adamax, AdamW, NAdam, RAdam, RMSProp, auto] |
|
| `optimizer` | `'auto'` | optimizer to use, choices=[SGD, Adam, Adamax, AdamW, NAdam, RAdam, RMSProp, auto] |
|
||||||
| `verbose` | `False` | whether to print verbose output |
|
| `verbose` | `False` | whether to print verbose output |
|
||||||
| `seed` | `0` | random seed for reproducibility |
|
| `seed` | `0` | random seed for reproducibility |
|
||||||
|
55
setup.py
55
setup.py
@ -3,14 +3,12 @@
|
|||||||
import re
|
import re
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import pkg_resources as pkg
|
from setuptools import setup
|
||||||
from setuptools import find_namespace_packages, setup
|
|
||||||
|
|
||||||
# Settings
|
# Settings
|
||||||
FILE = Path(__file__).resolve()
|
FILE = Path(__file__).resolve()
|
||||||
PARENT = FILE.parent # root directory
|
PARENT = FILE.parent # root directory
|
||||||
README = (PARENT / 'README.md').read_text(encoding='utf-8')
|
README = (PARENT / 'README.md').read_text(encoding='utf-8')
|
||||||
REQUIREMENTS = [f'{x.name}{x.specifier}' for x in pkg.parse_requirements((PARENT / 'requirements.txt').read_text())]
|
|
||||||
|
|
||||||
|
|
||||||
def get_version():
|
def get_version():
|
||||||
@ -18,6 +16,53 @@ def get_version():
|
|||||||
return re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', file.read_text(encoding='utf-8'), re.M)[1]
|
return re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', file.read_text(encoding='utf-8'), re.M)[1]
|
||||||
|
|
||||||
|
|
||||||
|
def parse_requirements(file_path: Path):
|
||||||
|
"""
|
||||||
|
Parse a requirements.txt file, ignoring lines that start with '#' and any text after '#'.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
file_path (str | Path): Path to the requirements.txt file.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
List[str]: List of parsed requirements.
|
||||||
|
"""
|
||||||
|
|
||||||
|
requirements = []
|
||||||
|
for line in Path(file_path).read_text().splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
if line and not line.startswith('#'):
|
||||||
|
requirements.append(line.split('#')[0].strip()) # ignore inline comments
|
||||||
|
|
||||||
|
return requirements
|
||||||
|
|
||||||
|
|
||||||
|
def find_packages(start_dir, exclude=()):
|
||||||
|
"""
|
||||||
|
Custom implementation of setuptools.find_packages(). Finds all Python packages in a directory.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
start_dir (str | Path, optional): The directory where the search will start. Defaults to the current directory.
|
||||||
|
exclude (list | tuple, optional): List of package names to exclude. Defaults to None.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
List[str]: List of package names.
|
||||||
|
"""
|
||||||
|
|
||||||
|
packages = []
|
||||||
|
start_dir = Path(start_dir)
|
||||||
|
root_package = start_dir.name
|
||||||
|
|
||||||
|
if '__init__.py' in [child.name for child in start_dir.iterdir()]:
|
||||||
|
packages.append(root_package)
|
||||||
|
for package in start_dir.rglob('*'):
|
||||||
|
if package.is_dir() and '__init__.py' in [child.name for child in package.iterdir()]:
|
||||||
|
package_name = f"{root_package}.{package.relative_to(start_dir).as_posix().replace('/', '.')}"
|
||||||
|
if package_name not in exclude:
|
||||||
|
packages.append(package_name)
|
||||||
|
|
||||||
|
return packages
|
||||||
|
|
||||||
|
|
||||||
setup(
|
setup(
|
||||||
name='ultralytics', # name of pypi package
|
name='ultralytics', # name of pypi package
|
||||||
version=get_version(), # version of pypi package
|
version=get_version(), # version of pypi package
|
||||||
@ -34,9 +79,9 @@ setup(
|
|||||||
'Source': 'https://github.com/ultralytics/ultralytics'},
|
'Source': 'https://github.com/ultralytics/ultralytics'},
|
||||||
author='Ultralytics',
|
author='Ultralytics',
|
||||||
author_email='hello@ultralytics.com',
|
author_email='hello@ultralytics.com',
|
||||||
packages=find_namespace_packages(include=['ultralytics.*']),
|
packages=find_packages(start_dir='ultralytics'), # required
|
||||||
include_package_data=True,
|
include_package_data=True,
|
||||||
install_requires=REQUIREMENTS,
|
install_requires=parse_requirements(PARENT / 'requirements.txt'),
|
||||||
extras_require={
|
extras_require={
|
||||||
'dev': [
|
'dev': [
|
||||||
'ipython',
|
'ipython',
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
# Ultralytics YOLO 🚀, AGPL-3.0 license
|
# Ultralytics YOLO 🚀, AGPL-3.0 license
|
||||||
|
|
||||||
__version__ = '8.0.177'
|
__version__ = '8.0.178'
|
||||||
|
|
||||||
from ultralytics.models import RTDETR, SAM, YOLO
|
from ultralytics.models import RTDETR, SAM, YOLO
|
||||||
from ultralytics.models.fastsam import FastSAM
|
from ultralytics.models.fastsam import FastSAM
|
||||||
|
@ -1,91 +1,322 @@
|
|||||||
# Tracker
|
______________________________________________________________________
|
||||||
|
|
||||||
## Supported Trackers
|
## comments: true description: Learn how to use Ultralytics YOLO for object tracking in video streams. Guides to use different trackers and customise tracker configurations. keywords: Ultralytics, YOLO, object tracking, video streams, BoT-SORT, ByteTrack, Python guide, CLI guide
|
||||||
|
|
||||||
- [x] ByteTracker
|
# Multi-Object Tracking with Ultralytics YOLO
|
||||||
- [x] BoT-SORT
|
|
||||||
|
|
||||||
## Usage
|
<img width="1024" src="https://user-images.githubusercontent.com/26833433/243418637-1d6250fd-1515-4c10-a844-a32818ae6d46.png">
|
||||||
|
|
||||||
### python interface:
|
Object tracking in the realm of video analytics is a critical task that not only identifies the location and class of objects within the frame but also maintains a unique ID for each detected object as the video progresses. The applications are limitless—ranging from surveillance and security to real-time sports analytics.
|
||||||
|
|
||||||
You can use the Python interface to track objects using the YOLO model.
|
## Why Choose Ultralytics YOLO for Object Tracking?
|
||||||
|
|
||||||
|
The output from Ultralytics trackers is consistent with standard object detection but has the added value of object IDs. This makes it easy to track objects in video streams and perform subsequent analytics. Here's why you should consider using Ultralytics YOLO for your object tracking needs:
|
||||||
|
|
||||||
|
- **Efficiency:** Process video streams in real-time without compromising accuracy.
|
||||||
|
- **Flexibility:** Supports multiple tracking algorithms and configurations.
|
||||||
|
- **Ease of Use:** Simple Python API and CLI options for quick integration and deployment.
|
||||||
|
- **Customizability:** Easy to use with custom trained YOLO models, allowing integration into domain-specific applications.
|
||||||
|
|
||||||
|
**Video Tutorial:** [Object Detection and Tracking with Ultralytics YOLOv8](https://www.youtube.com/embed/hHyHmOtmEgs?si=VNZtXmm45Nb9s-N-).
|
||||||
|
|
||||||
|
## Features at a Glance
|
||||||
|
|
||||||
|
Ultralytics YOLO extends its object detection features to provide robust and versatile object tracking:
|
||||||
|
|
||||||
|
- **Real-Time Tracking:** Seamlessly track objects in high-frame-rate videos.
|
||||||
|
- **Multiple Tracker Support:** Choose from a variety of established tracking algorithms.
|
||||||
|
- **Customizable Tracker Configurations:** Tailor the tracking algorithm to meet specific requirements by adjusting various parameters.
|
||||||
|
|
||||||
|
## Available Trackers
|
||||||
|
|
||||||
|
Ultralytics YOLO supports the following tracking algorithms. They can be enabled by passing the relevant YAML configuration file such as `tracker=tracker_type.yaml`:
|
||||||
|
|
||||||
|
- [BoT-SORT](https://github.com/NirAharon/BoT-SORT) - Use `botsort.yaml` to enable this tracker.
|
||||||
|
- [ByteTrack](https://github.com/ifzhang/ByteTrack) - Use `bytetrack.yaml` to enable this tracker.
|
||||||
|
|
||||||
|
The default tracker is BoT-SORT.
|
||||||
|
|
||||||
|
## Tracking
|
||||||
|
|
||||||
|
To run the tracker on video streams, use a trained Detect, Segment or Pose model such as YOLOv8n, YOLOv8n-seg and YOLOv8n-pose.
|
||||||
|
|
||||||
|
#### Python
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from ultralytics import YOLO
|
from ultralytics import YOLO
|
||||||
|
|
||||||
model = YOLO("yolov8n.pt") # or a segmentation model .i.e yolov8n-seg.pt
|
# Load an official or custom model
|
||||||
model.track(
|
model = YOLO("yolov8n.pt") # Load an official Detect model
|
||||||
source="video/streams",
|
model = YOLO("yolov8n-seg.pt") # Load an official Segment model
|
||||||
stream=True,
|
model = YOLO("yolov8n-pose.pt") # Load an official Pose model
|
||||||
tracker="botsort.yaml", # or 'bytetrack.yaml'
|
model = YOLO("path/to/best.pt") # Load a custom trained model
|
||||||
show=True,
|
|
||||||
|
# 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
|
||||||
|
```
|
||||||
|
|
||||||
|
#### CLI
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Perform tracking with various models using the command line interface
|
||||||
|
yolo track model=yolov8n.pt source="https://youtu.be/LNwODJXcvt4" # Official Detect model
|
||||||
|
yolo track model=yolov8n-seg.pt source="https://youtu.be/LNwODJXcvt4" # Official Segment model
|
||||||
|
yolo track model=yolov8n-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 can be seen in the above usage, tracking is available for all Detect, Segment and Pose models run on videos or streaming sources.
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
### Tracking Arguments
|
||||||
|
|
||||||
|
Tracking configuration shares properties with Predict mode, such as `conf`, `iou`, and `show`. For further configurations, refer to the [Predict](https://docs.ultralytics.com/modes/predict/) model page.
|
||||||
|
|
||||||
|
#### Python
|
||||||
|
|
||||||
|
```python
|
||||||
|
from ultralytics import YOLO
|
||||||
|
|
||||||
|
# Configure the tracking parameters and run the tracker
|
||||||
|
model = YOLO("yolov8n.pt")
|
||||||
|
results = model.track(
|
||||||
|
source="https://youtu.be/LNwODJXcvt4", conf=0.3, iou=0.5, show=True
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
You can get the IDs of the tracked objects using the following code:
|
#### CLI
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Configure tracking parameters and run the tracker using the command line interface
|
||||||
|
yolo track model=yolov8n.pt source="https://youtu.be/LNwODJXcvt4" conf=0.3, iou=0.5 show
|
||||||
|
```
|
||||||
|
|
||||||
|
### Tracker Selection
|
||||||
|
|
||||||
|
Ultralytics also allows you to use a modified tracker configuration file. To do this, simply make a copy of a tracker config file (for example, `custom_tracker.yaml`) from [ultralytics/cfg/trackers](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/cfg/trackers) and modify any configurations (except the `tracker_type`) as per your needs.
|
||||||
|
|
||||||
|
#### Python
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from ultralytics import YOLO
|
from ultralytics import YOLO
|
||||||
|
|
||||||
|
# Load the model and run the tracker with a custom configuration file
|
||||||
model = YOLO("yolov8n.pt")
|
model = YOLO("yolov8n.pt")
|
||||||
|
results = model.track(
|
||||||
for result in model.track(source="video.mp4"):
|
source="https://youtu.be/LNwODJXcvt4", tracker="custom_tracker.yaml"
|
||||||
print(
|
)
|
||||||
result.boxes.id.cpu().numpy().astype(int)
|
|
||||||
) # this will print the IDs of the tracked objects in the frame
|
|
||||||
```
|
```
|
||||||
|
|
||||||
If you want to use the tracker with a folder of images or when you loop on the video frames, you should use the `persist` parameter to tell the model that these frames are related to each other so the IDs will be fixed for the same objects. Otherwise, the IDs will be different in each frame because in each loop, the model creates a new object for tracking, but the `persist` parameter makes it use the same object for tracking.
|
#### CLI
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Load the model and run the tracker with a custom configuration file using the command line interface
|
||||||
|
yolo track model=yolov8n.pt source="https://youtu.be/LNwODJXcvt4" tracker='custom_tracker.yaml'
|
||||||
|
```
|
||||||
|
|
||||||
|
For a comprehensive list of tracking arguments, refer to the [ultralytics/cfg/trackers](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/cfg/trackers) page.
|
||||||
|
|
||||||
|
## Python Examples
|
||||||
|
|
||||||
|
### Persisting Tracks Loop
|
||||||
|
|
||||||
|
Here is a Python script using OpenCV (`cv2`) and YOLOv8 to run object tracking on video frames. This script still assumes you have already installed the necessary packages (`opencv-python` and `ultralytics`). The `persist=True` argument tells the tracker than the current image or frame is the next in a sequence and to expect tracks from the previous image in the current image.
|
||||||
|
|
||||||
|
#### Python
|
||||||
|
|
||||||
```python
|
```python
|
||||||
import cv2
|
import cv2
|
||||||
from ultralytics import YOLO
|
from ultralytics import YOLO
|
||||||
|
|
||||||
cap = cv2.VideoCapture("video.mp4")
|
# Load the YOLOv8 model
|
||||||
model = YOLO("yolov8n.pt")
|
model = YOLO("yolov8n.pt")
|
||||||
while True:
|
|
||||||
ret, frame = cap.read()
|
# Open the video file
|
||||||
if not ret:
|
video_path = "path/to/video.mp4"
|
||||||
break
|
cap = cv2.VideoCapture(video_path)
|
||||||
results = model.track(frame, persist=True)
|
|
||||||
boxes = results[0].boxes.xyxy.cpu().numpy().astype(int)
|
# Loop through the video frames
|
||||||
ids = results[0].boxes.id.cpu().numpy().astype(int)
|
while cap.isOpened():
|
||||||
for box, id in zip(boxes, ids):
|
# Read a frame from the video
|
||||||
cv2.rectangle(frame, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 2)
|
success, frame = cap.read()
|
||||||
cv2.putText(
|
|
||||||
frame,
|
if success:
|
||||||
f"Id {id}",
|
# Run YOLOv8 tracking on the frame, persisting tracks between frames
|
||||||
(box[0], box[1]),
|
results = model.track(frame, persist=True)
|
||||||
cv2.FONT_HERSHEY_SIMPLEX,
|
|
||||||
1,
|
# Visualize the results on the frame
|
||||||
(0, 0, 255),
|
annotated_frame = results[0].plot()
|
||||||
2,
|
|
||||||
)
|
# Display the annotated frame
|
||||||
cv2.imshow("frame", frame)
|
cv2.imshow("YOLOv8 Tracking", annotated_frame)
|
||||||
if cv2.waitKey(1) & 0xFF == ord("q"):
|
|
||||||
|
# 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
|
break
|
||||||
|
|
||||||
|
# Release the video capture object and close the display window
|
||||||
|
cap.release()
|
||||||
|
cv2.destroyAllWindows()
|
||||||
```
|
```
|
||||||
|
|
||||||
## Change tracker parameters
|
Please note the change from `model(frame)` to `model.track(frame)`, which enables object tracking instead of simple detection. This modified script will run the tracker on each frame of the video, visualize the results, and display them in a window. The loop can be exited by pressing 'q'.
|
||||||
|
|
||||||
You can change the tracker parameters by editing the `tracker.yaml` file which is located in the ultralytics/cfg/trackers folder.
|
### Plotting Tracks Over Time
|
||||||
|
|
||||||
## Command Line Interface (CLI)
|
Visualizing object tracks over consecutive frames can provide valuable insights into the movement patterns and behavior of detected objects within a video. With Ultralytics YOLOv8, plotting these tracks is a seamless and efficient process.
|
||||||
|
|
||||||
You can also use the command line interface to track objects using the YOLO model.
|
In the following example, we demonstrate how to utilize YOLOv8's tracking capabilities to plot the movement of detected objects across multiple video frames. This script involves opening a video file, reading it frame by frame, and utilizing the YOLO model to identify and track various objects. By retaining the center points of the detected bounding boxes and connecting them, we can draw lines that represent the paths followed by the tracked objects.
|
||||||
|
|
||||||
```bash
|
#### Python
|
||||||
yolo detect track source=... tracker=...
|
|
||||||
yolo segment track source=... tracker=...
|
```python
|
||||||
yolo pose track source=... tracker=...
|
from collections import defaultdict
|
||||||
|
|
||||||
|
import cv2
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from ultralytics import YOLO
|
||||||
|
|
||||||
|
# Load the YOLOv8 model
|
||||||
|
model = YOLO("yolov8n.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 YOLOv8 tracking on the frame, persisting tracks between frames
|
||||||
|
results = model.track(frame, persist=True)
|
||||||
|
|
||||||
|
# Get the boxes and track IDs
|
||||||
|
boxes = results[0].boxes.xywh.cpu()
|
||||||
|
track_ids = results[0].boxes.id.int().cpu().tolist()
|
||||||
|
|
||||||
|
# Visualize the results on the frame
|
||||||
|
annotated_frame = results[0].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 90 tracks for 90 frames
|
||||||
|
track.pop(0)
|
||||||
|
|
||||||
|
# Draw the tracking lines
|
||||||
|
points = np.hstack(track).astype(np.int32).reshape((-1, 1, 2))
|
||||||
|
cv2.polylines(
|
||||||
|
annotated_frame,
|
||||||
|
[points],
|
||||||
|
isClosed=False,
|
||||||
|
color=(230, 230, 230),
|
||||||
|
thickness=10,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Display the annotated frame
|
||||||
|
cv2.imshow("YOLOv8 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()
|
||||||
```
|
```
|
||||||
|
|
||||||
By default, trackers will use the configuration in `ultralytics/cfg/trackers`. We also support using a modified tracker config file. Please refer to the tracker config files in `ultralytics/cfg/trackers`.
|
### Multithreaded Tracking
|
||||||
|
|
||||||
## Contribute to Our Trackers Section
|
Multithreaded tracking provides the capability to run object tracking on multiple video streams simultaneously. This is particularly useful when handling multiple video inputs, such as from multiple surveillance cameras, where concurrent processing can greatly enhance efficiency and performance.
|
||||||
|
|
||||||
Are you proficient in multi-object tracking and have successfully implemented or adapted a tracking algorithm with Ultralytics YOLO? We invite you to contribute to our Trackers section! Your real-world applications and solutions could be invaluable for users working on tracking tasks.
|
In the provided Python script, we make use of Python's `threading` module to run multiple instances of the tracker concurrently. Each thread is responsible for running the tracker on one video file, and all the threads run simultaneously in the background.
|
||||||
|
|
||||||
|
To ensure that each thread receives the correct parameters (the video file and the model to use), we define a function `run_tracker_in_thread` that accepts these parameters and contains the main tracking loop. This function reads the video frame by frame, runs the tracker, and displays the results.
|
||||||
|
|
||||||
|
Two different models are used in this example: `yolov8n.pt` and `yolov8n-seg.pt`, each tracking objects in a different video file. The video files are specified in `video_file1` and `video_file2`.
|
||||||
|
|
||||||
|
The `daemon=True` parameter in `threading.Thread` means that these threads will be closed as soon as the main program finishes. We then start the threads with `start()` and use `join()` to make the main thread wait until both tracker threads have finished.
|
||||||
|
|
||||||
|
Finally, after all threads have completed their task, the windows displaying the results are closed using `cv2.destroyAllWindows()`.
|
||||||
|
|
||||||
|
#### Python
|
||||||
|
|
||||||
|
```python
|
||||||
|
import threading
|
||||||
|
|
||||||
|
import cv2
|
||||||
|
from ultralytics import YOLO
|
||||||
|
|
||||||
|
|
||||||
|
def run_tracker_in_thread(filename, model):
|
||||||
|
video = cv2.VideoCapture(filename)
|
||||||
|
frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
|
||||||
|
for _ in range(frames):
|
||||||
|
ret, frame = video.read()
|
||||||
|
if ret:
|
||||||
|
results = model.track(source=frame, persist=True)
|
||||||
|
res_plotted = results[0].plot()
|
||||||
|
cv2.imshow("p", res_plotted)
|
||||||
|
if cv2.waitKey(1) == ord("q"):
|
||||||
|
break
|
||||||
|
|
||||||
|
|
||||||
|
# Load the models
|
||||||
|
model1 = YOLO("yolov8n.pt")
|
||||||
|
model2 = YOLO("yolov8n-seg.pt")
|
||||||
|
|
||||||
|
# Define the video files for the trackers
|
||||||
|
video_file1 = "path/to/video1.mp4"
|
||||||
|
video_file2 = "path/to/video2.mp4"
|
||||||
|
|
||||||
|
# Create the tracker threads
|
||||||
|
tracker_thread1 = threading.Thread(
|
||||||
|
target=run_tracker_in_thread, args=(video_file1, model1), daemon=True
|
||||||
|
)
|
||||||
|
tracker_thread2 = threading.Thread(
|
||||||
|
target=run_tracker_in_thread, args=(video_file2, model2), daemon=True
|
||||||
|
)
|
||||||
|
|
||||||
|
# Start the tracker threads
|
||||||
|
tracker_thread1.start()
|
||||||
|
tracker_thread2.start()
|
||||||
|
|
||||||
|
# Wait for the tracker threads to finish
|
||||||
|
tracker_thread1.join()
|
||||||
|
tracker_thread2.join()
|
||||||
|
|
||||||
|
# Clean up and close windows
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
```
|
||||||
|
|
||||||
|
This example can easily be extended to handle more video files and models by creating more threads and applying the same methodology.
|
||||||
|
|
||||||
|
## Contribute New Trackers
|
||||||
|
|
||||||
|
Are you proficient in multi-object tracking and have successfully implemented or adapted a tracking algorithm with Ultralytics YOLO? We invite you to contribute to our Trackers section in [ultralytics/cfg/trackers](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/cfg/trackers)! Your real-world applications and solutions could be invaluable for users working on tracking tasks.
|
||||||
|
|
||||||
By contributing to this section, you help expand the scope of tracking solutions available within the Ultralytics YOLO framework, adding another layer of functionality and utility for the community.
|
By contributing to this section, you help expand the scope of tracking solutions available within the Ultralytics YOLO framework, adding another layer of functionality and utility for the community.
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user