Add Chinese Modes and Tasks Docs (#6274)
Signed-off-by: Glenn Jocher <glenn.jocher@ultralytics.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
parent
795b95bdcb
commit
e3a538bbde
293 changed files with 3681 additions and 736 deletions
94
docs/en/modes/benchmark.md
Normal file
94
docs/en/modes/benchmark.md
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
---
|
||||
comments: true
|
||||
description: Learn how to profile speed and accuracy of YOLOv8 across various export formats; get insights on mAP50-95, accuracy_top5 metrics, and more.
|
||||
keywords: Ultralytics, YOLOv8, benchmarking, speed profiling, accuracy profiling, mAP50-95, accuracy_top5, ONNX, OpenVINO, TensorRT, YOLO export formats
|
||||
---
|
||||
|
||||
# Model Benchmarking with Ultralytics YOLO
|
||||
|
||||
<img width="1024" src="https://github.com/ultralytics/assets/raw/main/yolov8/banner-integrations.png" alt="Ultralytics YOLO ecosystem and integrations">
|
||||
|
||||
## Introduction
|
||||
|
||||
Once your model is trained and validated, the next logical step is to evaluate its performance in various real-world scenarios. Benchmark mode in Ultralytics YOLOv8 serves this purpose by providing a robust framework for assessing the speed and accuracy of your model across a range of export formats.
|
||||
|
||||
## Why Is Benchmarking Crucial?
|
||||
|
||||
- **Informed Decisions:** Gain insights into the trade-offs between speed and accuracy.
|
||||
- **Resource Allocation:** Understand how different export formats perform on different hardware.
|
||||
- **Optimization:** Learn which export format offers the best performance for your specific use case.
|
||||
- **Cost Efficiency:** Make more efficient use of hardware resources based on benchmark results.
|
||||
|
||||
### Key Metrics in Benchmark Mode
|
||||
|
||||
- **mAP50-95:** For object detection, segmentation, and pose estimation.
|
||||
- **accuracy_top5:** For image classification.
|
||||
- **Inference Time:** Time taken for each image in milliseconds.
|
||||
|
||||
### Supported Export Formats
|
||||
|
||||
- **ONNX:** For optimal CPU performance
|
||||
- **TensorRT:** For maximal GPU efficiency
|
||||
- **OpenVINO:** For Intel hardware optimization
|
||||
- **CoreML, TensorFlow SavedModel, and More:** For diverse deployment needs.
|
||||
|
||||
!!! tip "Tip"
|
||||
|
||||
* Export to ONNX or OpenVINO for up to 3x CPU speedup.
|
||||
* Export to TensorRT for up to 5x GPU speedup.
|
||||
|
||||
## Usage Examples
|
||||
|
||||
Run YOLOv8n benchmarks on all supported export formats including ONNX, TensorRT etc. See Arguments section below for a full list of export arguments.
|
||||
|
||||
!!! example ""
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python
|
||||
from ultralytics.utils.benchmarks import benchmark
|
||||
|
||||
# Benchmark on GPU
|
||||
benchmark(model='yolov8n.pt', data='coco8.yaml', imgsz=640, half=False, device=0)
|
||||
```
|
||||
=== "CLI"
|
||||
|
||||
```bash
|
||||
yolo benchmark model=yolov8n.pt data='coco8.yaml' imgsz=640 half=False device=0
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
Arguments such as `model`, `data`, `imgsz`, `half`, `device`, and `verbose` provide users with the flexibility to fine-tune the benchmarks to their specific needs and compare the performance of different export formats with ease.
|
||||
|
||||
| Key | Value | Description |
|
||||
|-----------|---------|-----------------------------------------------------------------------|
|
||||
| `model` | `None` | path to model file, i.e. yolov8n.pt, yolov8n.yaml |
|
||||
| `data` | `None` | path to YAML referencing the benchmarking dataset (under `val` label) |
|
||||
| `imgsz` | `640` | image size as scalar or (h, w) list, i.e. (640, 480) |
|
||||
| `half` | `False` | FP16 quantization |
|
||||
| `int8` | `False` | INT8 quantization |
|
||||
| `device` | `None` | device to run on, i.e. cuda device=0 or device=0,1,2,3 or device=cpu |
|
||||
| `verbose` | `False` | do not continue on error (bool), or val floor threshold (float) |
|
||||
|
||||
## Export Formats
|
||||
|
||||
Benchmarks will attempt to run automatically on all possible export formats below.
|
||||
|
||||
| Format | `format` Argument | Model | Metadata | Arguments |
|
||||
|--------------------------------------------------------------------|-------------------|---------------------------|----------|-----------------------------------------------------|
|
||||
| [PyTorch](https://pytorch.org/) | - | `yolov8n.pt` | ✅ | - |
|
||||
| [TorchScript](https://pytorch.org/docs/stable/jit.html) | `torchscript` | `yolov8n.torchscript` | ✅ | `imgsz`, `optimize` |
|
||||
| [ONNX](https://onnx.ai/) | `onnx` | `yolov8n.onnx` | ✅ | `imgsz`, `half`, `dynamic`, `simplify`, `opset` |
|
||||
| [OpenVINO](https://docs.openvino.ai/latest/index.html) | `openvino` | `yolov8n_openvino_model/` | ✅ | `imgsz`, `half` |
|
||||
| [TensorRT](https://developer.nvidia.com/tensorrt) | `engine` | `yolov8n.engine` | ✅ | `imgsz`, `half`, `dynamic`, `simplify`, `workspace` |
|
||||
| [CoreML](https://github.com/apple/coremltools) | `coreml` | `yolov8n.mlpackage` | ✅ | `imgsz`, `half`, `int8`, `nms` |
|
||||
| [TF SavedModel](https://www.tensorflow.org/guide/saved_model) | `saved_model` | `yolov8n_saved_model/` | ✅ | `imgsz`, `keras` |
|
||||
| [TF GraphDef](https://www.tensorflow.org/api_docs/python/tf/Graph) | `pb` | `yolov8n.pb` | ❌ | `imgsz` |
|
||||
| [TF Lite](https://www.tensorflow.org/lite) | `tflite` | `yolov8n.tflite` | ✅ | `imgsz`, `half`, `int8` |
|
||||
| [TF Edge TPU](https://coral.ai/docs/edgetpu/models-intro/) | `edgetpu` | `yolov8n_edgetpu.tflite` | ✅ | `imgsz` |
|
||||
| [TF.js](https://www.tensorflow.org/js) | `tfjs` | `yolov8n_web_model/` | ✅ | `imgsz` |
|
||||
| [PaddlePaddle](https://github.com/PaddlePaddle) | `paddle` | `yolov8n_paddle_model/` | ✅ | `imgsz` |
|
||||
| [ncnn](https://github.com/Tencent/ncnn) | `ncnn` | `yolov8n_ncnn_model/` | ✅ | `imgsz`, `half` |
|
||||
|
||||
See full `export` details in the [Export](https://docs.ultralytics.com/modes/export/) page.
|
||||
108
docs/en/modes/export.md
Normal file
108
docs/en/modes/export.md
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
---
|
||||
comments: true
|
||||
description: Step-by-step guide on exporting your YOLOv8 models to various format like ONNX, TensorRT, CoreML and more for deployment. Explore now!.
|
||||
keywords: YOLO, YOLOv8, Ultralytics, Model export, ONNX, TensorRT, CoreML, TensorFlow SavedModel, OpenVINO, PyTorch, export model
|
||||
---
|
||||
|
||||
# Model Export with Ultralytics YOLO
|
||||
|
||||
<img width="1024" src="https://github.com/ultralytics/assets/raw/main/yolov8/banner-integrations.png" alt="Ultralytics YOLO ecosystem and integrations">
|
||||
|
||||
## Introduction
|
||||
|
||||
The ultimate goal of training a model is to deploy it for real-world applications. Export mode in Ultralytics YOLOv8 offers a versatile range of options for exporting your trained model to different formats, making it deployable across various platforms and devices. This comprehensive guide aims to walk you through the nuances of model exporting, showcasing how to achieve maximum compatibility and performance.
|
||||
|
||||
<p align="center">
|
||||
<br>
|
||||
<iframe width="720" height="405" src="https://www.youtube.com/embed/WbomGeoOT_k?si=aGmuyooWftA0ue9X"
|
||||
title="YouTube video player" frameborder="0"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
|
||||
allowfullscreen>
|
||||
</iframe>
|
||||
<br>
|
||||
<strong>Watch:</strong> How To Export Custom Trained Ultralytics YOLOv8 Model and Run Live Inference on Webcam.
|
||||
</p>
|
||||
|
||||
## Why Choose YOLOv8's Export Mode?
|
||||
|
||||
- **Versatility:** Export to multiple formats including ONNX, TensorRT, CoreML, and more.
|
||||
- **Performance:** Gain up to 5x GPU speedup with TensorRT and 3x CPU speedup with ONNX or OpenVINO.
|
||||
- **Compatibility:** Make your model universally deployable across numerous hardware and software environments.
|
||||
- **Ease of Use:** Simple CLI and Python API for quick and straightforward model exporting.
|
||||
|
||||
### Key Features of Export Mode
|
||||
|
||||
Here are some of the standout functionalities:
|
||||
|
||||
- **One-Click Export:** Simple commands for exporting to different formats.
|
||||
- **Batch Export:** Export batched-inference capable models.
|
||||
- **Optimized Inference:** Exported models are optimized for quicker inference times.
|
||||
- **Tutorial Videos:** In-depth guides and tutorials for a smooth exporting experience.
|
||||
|
||||
!!! tip "Tip"
|
||||
|
||||
* Export to ONNX or OpenVINO for up to 3x CPU speedup.
|
||||
* Export to TensorRT for up to 5x GPU speedup.
|
||||
|
||||
## Usage Examples
|
||||
|
||||
Export a YOLOv8n model to a different format like ONNX or TensorRT. See Arguments section below for a full list of export arguments.
|
||||
|
||||
!!! example ""
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a model
|
||||
model = YOLO('yolov8n.pt') # load an official model
|
||||
model = YOLO('path/to/best.pt') # load a custom trained model
|
||||
|
||||
# Export the model
|
||||
model.export(format='onnx')
|
||||
```
|
||||
=== "CLI"
|
||||
|
||||
```bash
|
||||
yolo export model=yolov8n.pt format=onnx # export official model
|
||||
yolo export model=path/to/best.pt format=onnx # export custom trained model
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
Export settings for YOLO models refer to the various configurations and options used to save or export the model for use in other environments or platforms. These settings can affect the model's performance, size, and compatibility with different systems. Some common YOLO export settings include the format of the exported model file (e.g. ONNX, TensorFlow SavedModel), the device on which the model will be run (e.g. CPU, GPU), and the presence of additional features such as masks or multiple labels per box. Other factors that may affect the export process include the specific task the model is being used for and the requirements or constraints of the target environment or platform. It is important to carefully consider and configure these settings to ensure that the exported model is optimized for the intended use case and can be used effectively in the target environment.
|
||||
|
||||
| Key | Value | Description |
|
||||
|-------------|-----------------|------------------------------------------------------|
|
||||
| `format` | `'torchscript'` | format to export to |
|
||||
| `imgsz` | `640` | image size as scalar or (h, w) list, i.e. (640, 480) |
|
||||
| `keras` | `False` | use Keras for TF SavedModel export |
|
||||
| `optimize` | `False` | TorchScript: optimize for mobile |
|
||||
| `half` | `False` | FP16 quantization |
|
||||
| `int8` | `False` | INT8 quantization |
|
||||
| `dynamic` | `False` | ONNX/TensorRT: dynamic axes |
|
||||
| `simplify` | `False` | ONNX/TensorRT: simplify model |
|
||||
| `opset` | `None` | ONNX: opset version (optional, defaults to latest) |
|
||||
| `workspace` | `4` | TensorRT: workspace size (GB) |
|
||||
| `nms` | `False` | CoreML: add NMS |
|
||||
|
||||
## Export Formats
|
||||
|
||||
Available YOLOv8 export formats are in the table below. You can export to any format using the `format` argument, i.e. `format='onnx'` or `format='engine'`.
|
||||
|
||||
| Format | `format` Argument | Model | Metadata | Arguments |
|
||||
|--------------------------------------------------------------------|-------------------|---------------------------|----------|-----------------------------------------------------|
|
||||
| [PyTorch](https://pytorch.org/) | - | `yolov8n.pt` | ✅ | - |
|
||||
| [TorchScript](https://pytorch.org/docs/stable/jit.html) | `torchscript` | `yolov8n.torchscript` | ✅ | `imgsz`, `optimize` |
|
||||
| [ONNX](https://onnx.ai/) | `onnx` | `yolov8n.onnx` | ✅ | `imgsz`, `half`, `dynamic`, `simplify`, `opset` |
|
||||
| [OpenVINO](https://docs.openvino.ai/latest/index.html) | `openvino` | `yolov8n_openvino_model/` | ✅ | `imgsz`, `half` |
|
||||
| [TensorRT](https://developer.nvidia.com/tensorrt) | `engine` | `yolov8n.engine` | ✅ | `imgsz`, `half`, `dynamic`, `simplify`, `workspace` |
|
||||
| [CoreML](https://github.com/apple/coremltools) | `coreml` | `yolov8n.mlpackage` | ✅ | `imgsz`, `half`, `int8`, `nms` |
|
||||
| [TF SavedModel](https://www.tensorflow.org/guide/saved_model) | `saved_model` | `yolov8n_saved_model/` | ✅ | `imgsz`, `keras` |
|
||||
| [TF GraphDef](https://www.tensorflow.org/api_docs/python/tf/Graph) | `pb` | `yolov8n.pb` | ❌ | `imgsz` |
|
||||
| [TF Lite](https://www.tensorflow.org/lite) | `tflite` | `yolov8n.tflite` | ✅ | `imgsz`, `half`, `int8` |
|
||||
| [TF Edge TPU](https://coral.ai/docs/edgetpu/models-intro/) | `edgetpu` | `yolov8n_edgetpu.tflite` | ✅ | `imgsz` |
|
||||
| [TF.js](https://www.tensorflow.org/js) | `tfjs` | `yolov8n_web_model/` | ✅ | `imgsz` |
|
||||
| [PaddlePaddle](https://github.com/PaddlePaddle) | `paddle` | `yolov8n_paddle_model/` | ✅ | `imgsz` |
|
||||
| [ncnn](https://github.com/Tencent/ncnn) | `ncnn` | `yolov8n_ncnn_model/` | ✅ | `imgsz`, `half` |
|
||||
74
docs/en/modes/index.md
Normal file
74
docs/en/modes/index.md
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
---
|
||||
comments: true
|
||||
description: From training to tracking, make the most of YOLOv8 with Ultralytics. Get insights and examples for each supported mode including validation, export, and benchmarking.
|
||||
keywords: Ultralytics, YOLOv8, Machine Learning, Object Detection, Training, Validation, Prediction, Export, Tracking, Benchmarking
|
||||
---
|
||||
|
||||
# Ultralytics YOLOv8 Modes
|
||||
|
||||
<img width="1024" src="https://github.com/ultralytics/assets/raw/main/yolov8/banner-integrations.png" alt="Ultralytics YOLO ecosystem and integrations">
|
||||
|
||||
## Introduction
|
||||
|
||||
Ultralytics YOLOv8 is not just another object detection model; it's a versatile framework designed to cover the entire lifecycle of machine learning models—from data ingestion and model training to validation, deployment, and real-world tracking. Each mode serves a specific purpose and is engineered to offer you the flexibility and efficiency required for different tasks and use-cases.
|
||||
|
||||
<p align="center">
|
||||
<br>
|
||||
<iframe width="720" height="405" src="https://www.youtube.com/embed/j8uQc0qB91s?si=dhnGKgqvs7nPgeaM"
|
||||
title="YouTube video player" frameborder="0"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
|
||||
allowfullscreen>
|
||||
</iframe>
|
||||
<br>
|
||||
<strong>Watch:</strong> Ultralytics Modes Tutorial: Train, Validate, Predict, Export & Benchmark.
|
||||
</p>
|
||||
|
||||
### Modes at a Glance
|
||||
|
||||
Understanding the different **modes** that Ultralytics YOLOv8 supports is critical to getting the most out of your models:
|
||||
|
||||
- **Train** mode: Fine-tune your model on custom or preloaded datasets.
|
||||
- **Val** mode: A post-training checkpoint to validate model performance.
|
||||
- **Predict** mode: Unleash the predictive power of your model on real-world data.
|
||||
- **Export** mode: Make your model deployment-ready in various formats.
|
||||
- **Track** mode: Extend your object detection model into real-time tracking applications.
|
||||
- **Benchmark** mode: Analyze the speed and accuracy of your model in diverse deployment environments.
|
||||
|
||||
This comprehensive guide aims to give you an overview and practical insights into each mode, helping you harness the full potential of YOLOv8.
|
||||
|
||||
## [Train](train.md)
|
||||
|
||||
Train mode is used for training a YOLOv8 model on a custom dataset. In this mode, the model is trained using the specified dataset and hyperparameters. The training process involves optimizing the model's parameters so that it can accurately predict the classes and locations of objects in an image.
|
||||
|
||||
[Train Examples](train.md){ .md-button .md-button--primary}
|
||||
|
||||
## [Val](val.md)
|
||||
|
||||
Val mode is used for validating a YOLOv8 model after it has been trained. In this mode, the model is evaluated on a validation set to measure its accuracy and generalization performance. This mode can be used to tune the hyperparameters of the model to improve its performance.
|
||||
|
||||
[Val Examples](val.md){ .md-button .md-button--primary}
|
||||
|
||||
## [Predict](predict.md)
|
||||
|
||||
Predict mode is used for making predictions using a trained YOLOv8 model on new images or videos. In this mode, the model is loaded from a checkpoint file, and the user can provide images or videos to perform inference. The model predicts the classes and locations of objects in the input images or videos.
|
||||
|
||||
[Predict Examples](predict.md){ .md-button .md-button--primary}
|
||||
|
||||
## [Export](export.md)
|
||||
|
||||
Export mode is used for exporting a YOLOv8 model to a format that can be used for deployment. In this mode, the model is converted to a format that can be used by other software applications or hardware devices. This mode is useful when deploying the model to production environments.
|
||||
|
||||
[Export Examples](export.md){ .md-button .md-button--primary}
|
||||
|
||||
## [Track](track.md)
|
||||
|
||||
Track mode is used for tracking objects in real-time using a YOLOv8 model. In this mode, the model is loaded from a checkpoint file, and the user can provide a live video stream to perform real-time object tracking. This mode is useful for applications such as surveillance systems or self-driving cars.
|
||||
|
||||
[Track Examples](track.md){ .md-button .md-button--primary}
|
||||
|
||||
## [Benchmark](benchmark.md)
|
||||
|
||||
Benchmark mode is used to profile the speed and accuracy of various export formats for YOLOv8. The benchmarks provide information on the size of the exported format, its `mAP50-95` metrics (for object detection, segmentation and pose)
|
||||
or `accuracy_top5` metrics (for classification), and the inference time in milliseconds per image across various export formats like ONNX, OpenVINO, TensorRT and others. This information can help users choose the optimal export format for their specific use case based on their requirements for speed and accuracy.
|
||||
|
||||
[Benchmark Examples](benchmark.md){ .md-button .md-button--primary}
|
||||
715
docs/en/modes/predict.md
Normal file
715
docs/en/modes/predict.md
Normal file
|
|
@ -0,0 +1,715 @@
|
|||
---
|
||||
comments: true
|
||||
description: Discover how to use YOLOv8 predict mode for various tasks. Learn about different inference sources like images, videos, and data formats.
|
||||
keywords: Ultralytics, YOLOv8, predict mode, inference sources, prediction tasks, streaming mode, image processing, video processing, machine learning, AI
|
||||
---
|
||||
|
||||
# Model Prediction with Ultralytics YOLO
|
||||
|
||||
<img width="1024" src="https://github.com/ultralytics/assets/raw/main/yolov8/banner-integrations.png" alt="Ultralytics YOLO ecosystem and integrations">
|
||||
|
||||
## Introduction
|
||||
|
||||
In the world of machine learning and computer vision, the process of making sense out of visual data is called 'inference' or 'prediction'. Ultralytics YOLOv8 offers a powerful feature known as **predict mode** that is tailored for high-performance, real-time inference on a wide range of data sources.
|
||||
|
||||
<p align="center">
|
||||
<br>
|
||||
<iframe width="720" height="405" src="https://www.youtube.com/embed/QtsI0TnwDZs?si=ljesw75cMO2Eas14"
|
||||
title="YouTube video player" frameborder="0"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
|
||||
allowfullscreen>
|
||||
</iframe>
|
||||
<br>
|
||||
<strong>Watch:</strong> How to Extract the Outputs from Ultralytics YOLOv8 Model for Custom Projects.
|
||||
</p>
|
||||
|
||||
## Real-world Applications
|
||||
|
||||
| Manufacturing | Sports | Safety |
|
||||
|:-----------------------------------------------------------------------------------------------------------------------------------:|:-------------------------------------------------------------------------------------------------------------------------------:|:---------------------------------------------------------------------------------------------------------------------------:|
|
||||
|  |  |  |
|
||||
| Vehicle Spare Parts Detection | Football Player Detection | People Fall Detection |
|
||||
|
||||
## Why Use Ultralytics YOLO for Inference?
|
||||
|
||||
Here's why you should consider YOLOv8's predict mode for your various inference needs:
|
||||
|
||||
- **Versatility:** Capable of making inferences on images, videos, and even live streams.
|
||||
- **Performance:** Engineered for real-time, high-speed processing without sacrificing accuracy.
|
||||
- **Ease of Use:** Intuitive Python and CLI interfaces for rapid deployment and testing.
|
||||
- **Highly Customizable:** Various settings and parameters to tune the model's inference behavior according to your specific requirements.
|
||||
|
||||
### Key Features of Predict Mode
|
||||
|
||||
YOLOv8's predict mode is designed to be robust and versatile, featuring:
|
||||
|
||||
- **Multiple Data Source Compatibility:** Whether your data is in the form of individual images, a collection of images, video files, or real-time video streams, predict mode has you covered.
|
||||
- **Streaming Mode:** Use the streaming feature to generate a memory-efficient generator of `Results` objects. Enable this by setting `stream=True` in the predictor's call method.
|
||||
- **Batch Processing:** The ability to process multiple images or video frames in a single batch, further speeding up inference time.
|
||||
- **Integration Friendly:** Easily integrate with existing data pipelines and other software components, thanks to its flexible API.
|
||||
|
||||
Ultralytics YOLO models return either a Python list of `Results` objects, or a memory-efficient Python generator of `Results` objects when `stream=True` is passed to the model during inference:
|
||||
|
||||
!!! example "Predict"
|
||||
|
||||
=== "Return a list with `stream=False`"
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a model
|
||||
model = YOLO('yolov8n.pt') # pretrained YOLOv8n model
|
||||
|
||||
# Run batched inference on a list of images
|
||||
results = model(['im1.jpg', 'im2.jpg']) # return a list of Results objects
|
||||
|
||||
# Process results list
|
||||
for result in results:
|
||||
boxes = result.boxes # Boxes object for bbox outputs
|
||||
masks = result.masks # Masks object for segmentation masks outputs
|
||||
keypoints = result.keypoints # Keypoints object for pose outputs
|
||||
probs = result.probs # Probs object for classification outputs
|
||||
```
|
||||
|
||||
=== "Return a generator with `stream=True`"
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a model
|
||||
model = YOLO('yolov8n.pt') # pretrained YOLOv8n model
|
||||
|
||||
# Run batched inference on a list of images
|
||||
results = model(['im1.jpg', 'im2.jpg'], stream=True) # return a generator of Results objects
|
||||
|
||||
# Process results generator
|
||||
for result in results:
|
||||
boxes = result.boxes # Boxes object for bbox outputs
|
||||
masks = result.masks # Masks object for segmentation masks outputs
|
||||
keypoints = result.keypoints # Keypoints object for pose outputs
|
||||
probs = result.probs # Probs object for classification outputs
|
||||
```
|
||||
|
||||
## Inference Sources
|
||||
|
||||
YOLOv8 can process different types of input sources for inference, as shown in the table below. The sources include static images, video streams, and various data formats. The table also indicates whether each source can be used in streaming mode with the argument `stream=True` ✅. Streaming mode is beneficial for processing videos or live streams as it creates a generator of results instead of loading all frames into memory.
|
||||
|
||||
!!! tip "Tip"
|
||||
|
||||
Use `stream=True` for processing long videos or large datasets to efficiently manage memory. When `stream=False`, the results for all frames or data points are stored in memory, which can quickly add up and cause out-of-memory errors for large inputs. In contrast, `stream=True` utilizes a generator, which only keeps the results of the current frame or data point in memory, significantly reducing memory consumption and preventing out-of-memory issues.
|
||||
|
||||
| Source | Argument | Type | Notes |
|
||||
|----------------|--------------------------------------------|-----------------|---------------------------------------------------------------------------------------------|
|
||||
| image | `'image.jpg'` | `str` or `Path` | Single image file. |
|
||||
| URL | `'https://ultralytics.com/images/bus.jpg'` | `str` | URL to an image. |
|
||||
| screenshot | `'screen'` | `str` | Capture a screenshot. |
|
||||
| PIL | `Image.open('im.jpg')` | `PIL.Image` | HWC format with RGB channels. |
|
||||
| OpenCV | `cv2.imread('im.jpg')` | `np.ndarray` | HWC format with BGR channels `uint8 (0-255)`. |
|
||||
| numpy | `np.zeros((640,1280,3))` | `np.ndarray` | HWC format with BGR channels `uint8 (0-255)`. |
|
||||
| torch | `torch.zeros(16,3,320,640)` | `torch.Tensor` | BCHW format with RGB channels `float32 (0.0-1.0)`. |
|
||||
| CSV | `'sources.csv'` | `str` or `Path` | CSV file containing paths to images, videos, or directories. |
|
||||
| video ✅ | `'video.mp4'` | `str` or `Path` | Video file in formats like MP4, AVI, etc. |
|
||||
| directory ✅ | `'path/'` | `str` or `Path` | Path to a directory containing images or videos. |
|
||||
| glob ✅ | `'path/*.jpg'` | `str` | Glob pattern to match multiple files. Use the `*` character as a wildcard. |
|
||||
| YouTube ✅ | `'https://youtu.be/LNwODJXcvt4'` | `str` | URL to a YouTube video. |
|
||||
| stream ✅ | `'rtsp://example.com/media.mp4'` | `str` | URL for streaming protocols such as RTSP, RTMP, TCP, or an IP address. |
|
||||
| multi-stream ✅ | `'list.streams'` | `str` or `Path` | `*.streams` text file with one stream URL per row, i.e. 8 streams will run at batch-size 8. |
|
||||
|
||||
Below are code examples for using each source type:
|
||||
|
||||
!!! example "Prediction sources"
|
||||
|
||||
=== "image"
|
||||
Run inference on an image file.
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a pretrained YOLOv8n model
|
||||
model = YOLO('yolov8n.pt')
|
||||
|
||||
# Define path to the image file
|
||||
source = 'path/to/image.jpg'
|
||||
|
||||
# Run inference on the source
|
||||
results = model(source) # list of Results objects
|
||||
```
|
||||
|
||||
=== "screenshot"
|
||||
Run inference on the current screen content as a screenshot.
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a pretrained YOLOv8n model
|
||||
model = YOLO('yolov8n.pt')
|
||||
|
||||
# Define current screenshot as source
|
||||
source = 'screen'
|
||||
|
||||
# Run inference on the source
|
||||
results = model(source) # list of Results objects
|
||||
```
|
||||
|
||||
=== "URL"
|
||||
Run inference on an image or video hosted remotely via URL.
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a pretrained YOLOv8n model
|
||||
model = YOLO('yolov8n.pt')
|
||||
|
||||
# Define remote image or video URL
|
||||
source = 'https://ultralytics.com/images/bus.jpg'
|
||||
|
||||
# Run inference on the source
|
||||
results = model(source) # list of Results objects
|
||||
```
|
||||
|
||||
=== "PIL"
|
||||
Run inference on an image opened with Python Imaging Library (PIL).
|
||||
```python
|
||||
from PIL import Image
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a pretrained YOLOv8n model
|
||||
model = YOLO('yolov8n.pt')
|
||||
|
||||
# Open an image using PIL
|
||||
source = Image.open('path/to/image.jpg')
|
||||
|
||||
# Run inference on the source
|
||||
results = model(source) # list of Results objects
|
||||
```
|
||||
|
||||
=== "OpenCV"
|
||||
Run inference on an image read with OpenCV.
|
||||
```python
|
||||
import cv2
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a pretrained YOLOv8n model
|
||||
model = YOLO('yolov8n.pt')
|
||||
|
||||
# Read an image using OpenCV
|
||||
source = cv2.imread('path/to/image.jpg')
|
||||
|
||||
# Run inference on the source
|
||||
results = model(source) # list of Results objects
|
||||
```
|
||||
|
||||
=== "numpy"
|
||||
Run inference on an image represented as a numpy array.
|
||||
```python
|
||||
import numpy as np
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a pretrained YOLOv8n model
|
||||
model = YOLO('yolov8n.pt')
|
||||
|
||||
# Create a random numpy array of HWC shape (640, 640, 3) with values in range [0, 255] and type uint8
|
||||
source = np.random.randint(low=0, high=255, size=(640, 640, 3), dtype='uint8')
|
||||
|
||||
# Run inference on the source
|
||||
results = model(source) # list of Results objects
|
||||
```
|
||||
|
||||
=== "torch"
|
||||
Run inference on an image represented as a PyTorch tensor.
|
||||
```python
|
||||
import torch
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a pretrained YOLOv8n model
|
||||
model = YOLO('yolov8n.pt')
|
||||
|
||||
# Create a random torch tensor of BCHW shape (1, 3, 640, 640) with values in range [0, 1] and type float32
|
||||
source = torch.rand(1, 3, 640, 640, dtype=torch.float32)
|
||||
|
||||
# Run inference on the source
|
||||
results = model(source) # list of Results objects
|
||||
```
|
||||
|
||||
=== "CSV"
|
||||
Run inference on a collection of images, URLs, videos and directories listed in a CSV file.
|
||||
```python
|
||||
import torch
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a pretrained YOLOv8n model
|
||||
model = YOLO('yolov8n.pt')
|
||||
|
||||
# Define a path to a CSV file with images, URLs, videos and directories
|
||||
source = 'path/to/file.csv'
|
||||
|
||||
# Run inference on the source
|
||||
results = model(source) # list of Results objects
|
||||
```
|
||||
|
||||
=== "video"
|
||||
Run inference on a video file. By using `stream=True`, you can create a generator of Results objects to reduce memory usage.
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a pretrained YOLOv8n model
|
||||
model = YOLO('yolov8n.pt')
|
||||
|
||||
# Define path to video file
|
||||
source = 'path/to/video.mp4'
|
||||
|
||||
# Run inference on the source
|
||||
results = model(source, stream=True) # generator of Results objects
|
||||
```
|
||||
|
||||
=== "directory"
|
||||
Run inference on all images and videos in a directory. To also capture images and videos in subdirectories use a glob pattern, i.e. `path/to/dir/**/*`.
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a pretrained YOLOv8n model
|
||||
model = YOLO('yolov8n.pt')
|
||||
|
||||
# Define path to directory containing images and videos for inference
|
||||
source = 'path/to/dir'
|
||||
|
||||
# Run inference on the source
|
||||
results = model(source, stream=True) # generator of Results objects
|
||||
```
|
||||
|
||||
=== "glob"
|
||||
Run inference on all images and videos that match a glob expression with `*` characters.
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a pretrained YOLOv8n model
|
||||
model = YOLO('yolov8n.pt')
|
||||
|
||||
# Define a glob search for all JPG files in a directory
|
||||
source = 'path/to/dir/*.jpg'
|
||||
|
||||
# OR define a recursive glob search for all JPG files including subdirectories
|
||||
source = 'path/to/dir/**/*.jpg'
|
||||
|
||||
# Run inference on the source
|
||||
results = model(source, stream=True) # generator of Results objects
|
||||
```
|
||||
|
||||
=== "YouTube"
|
||||
Run inference on a YouTube video. By using `stream=True`, you can create a generator of Results objects to reduce memory usage for long videos.
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a pretrained YOLOv8n model
|
||||
model = YOLO('yolov8n.pt')
|
||||
|
||||
# Define source as YouTube video URL
|
||||
source = 'https://youtu.be/LNwODJXcvt4'
|
||||
|
||||
# Run inference on the source
|
||||
results = model(source, stream=True) # generator of Results objects
|
||||
```
|
||||
|
||||
=== "Streams"
|
||||
Run inference on remote streaming sources using RTSP, RTMP, TCP and IP address protocols. If multiple streams are provided in a `*.streams` text file then batched inference will run, i.e. 8 streams will run at batch-size 8, otherwise single streams will run at batch-size 1.
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a pretrained YOLOv8n model
|
||||
model = YOLO('yolov8n.pt')
|
||||
|
||||
# Single stream with batch-size 1 inference
|
||||
source = 'rtsp://example.com/media.mp4' # RTSP, RTMP, TCP or IP streaming address
|
||||
|
||||
# Multiple streams with batched inference (i.e. batch-size 8 for 8 streams)
|
||||
source = 'path/to/list.streams' # *.streams text file with one streaming address per row
|
||||
|
||||
# Run inference on the source
|
||||
results = model(source, stream=True) # generator of Results objects
|
||||
```
|
||||
|
||||
## Inference Arguments
|
||||
|
||||
`model.predict()` accepts multiple arguments that can be passed at inference time to override defaults:
|
||||
|
||||
!!! example
|
||||
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a pretrained YOLOv8n model
|
||||
model = YOLO('yolov8n.pt')
|
||||
|
||||
# Run inference on 'bus.jpg' with arguments
|
||||
model.predict('bus.jpg', save=True, imgsz=320, conf=0.5)
|
||||
```
|
||||
|
||||
All supported arguments:
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
|-----------------|----------------|------------------------|--------------------------------------------------------------------------------|
|
||||
| `source` | `str` | `'ultralytics/assets'` | source directory for images or videos |
|
||||
| `conf` | `float` | `0.25` | object confidence threshold for detection |
|
||||
| `iou` | `float` | `0.7` | intersection over union (IoU) threshold for NMS |
|
||||
| `imgsz` | `int or tuple` | `640` | image size as scalar or (h, w) list, i.e. (640, 480) |
|
||||
| `half` | `bool` | `False` | use half precision (FP16) |
|
||||
| `device` | `None or str` | `None` | device to run on, i.e. cuda device=0/1/2/3 or device=cpu |
|
||||
| `show` | `bool` | `False` | show results if possible |
|
||||
| `save` | `bool` | `False` | save images with results |
|
||||
| `save_txt` | `bool` | `False` | save results as .txt file |
|
||||
| `save_conf` | `bool` | `False` | save results with confidence scores |
|
||||
| `save_crop` | `bool` | `False` | save cropped images with results |
|
||||
| `hide_labels` | `bool` | `False` | hide labels |
|
||||
| `hide_conf` | `bool` | `False` | hide confidence scores |
|
||||
| `max_det` | `int` | `300` | maximum number of detections per image |
|
||||
| `vid_stride` | `bool` | `False` | video frame-rate stride |
|
||||
| `stream_buffer` | `bool` | `False` | buffer all streaming frames (True) or return the most recent frame (False) |
|
||||
| `line_width` | `None or int` | `None` | The line width of the bounding boxes. If None, it is scaled to the image size. |
|
||||
| `visualize` | `bool` | `False` | visualize model features |
|
||||
| `augment` | `bool` | `False` | apply image augmentation to prediction sources |
|
||||
| `agnostic_nms` | `bool` | `False` | class-agnostic NMS |
|
||||
| `retina_masks` | `bool` | `False` | use high-resolution segmentation masks |
|
||||
| `classes` | `None or list` | `None` | filter results by class, i.e. classes=0, or classes=[0,2,3] |
|
||||
| `boxes` | `bool` | `True` | Show boxes in segmentation predictions |
|
||||
|
||||
## Image and Video Formats
|
||||
|
||||
YOLOv8 supports various image and video formats, as specified in [data/utils.py](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/data/utils.py). See the tables below for the valid suffixes and example predict commands.
|
||||
|
||||
### Images
|
||||
|
||||
The below table contains valid Ultralytics image formats.
|
||||
|
||||
| Image Suffixes | Example Predict Command | Reference |
|
||||
|----------------|----------------------------------|-------------------------------------------------------------------------------|
|
||||
| .bmp | `yolo predict source=image.bmp` | [Microsoft BMP File Format](https://en.wikipedia.org/wiki/BMP_file_format) |
|
||||
| .dng | `yolo predict source=image.dng` | [Adobe DNG](https://www.adobe.com/products/photoshop/extend.displayTab2.html) |
|
||||
| .jpeg | `yolo predict source=image.jpeg` | [JPEG](https://en.wikipedia.org/wiki/JPEG) |
|
||||
| .jpg | `yolo predict source=image.jpg` | [JPEG](https://en.wikipedia.org/wiki/JPEG) |
|
||||
| .mpo | `yolo predict source=image.mpo` | [Multi Picture Object](https://fileinfo.com/extension/mpo) |
|
||||
| .png | `yolo predict source=image.png` | [Portable Network Graphics](https://en.wikipedia.org/wiki/PNG) |
|
||||
| .tif | `yolo predict source=image.tif` | [Tag Image File Format](https://en.wikipedia.org/wiki/TIFF) |
|
||||
| .tiff | `yolo predict source=image.tiff` | [Tag Image File Format](https://en.wikipedia.org/wiki/TIFF) |
|
||||
| .webp | `yolo predict source=image.webp` | [WebP](https://en.wikipedia.org/wiki/WebP) |
|
||||
| .pfm | `yolo predict source=image.pfm` | [Portable FloatMap](https://en.wikipedia.org/wiki/Netpbm#File_formats) |
|
||||
|
||||
### Videos
|
||||
|
||||
The below table contains valid Ultralytics video formats.
|
||||
|
||||
| Video Suffixes | Example Predict Command | Reference |
|
||||
|----------------|----------------------------------|----------------------------------------------------------------------------------|
|
||||
| .asf | `yolo predict source=video.asf` | [Advanced Systems Format](https://en.wikipedia.org/wiki/Advanced_Systems_Format) |
|
||||
| .avi | `yolo predict source=video.avi` | [Audio Video Interleave](https://en.wikipedia.org/wiki/Audio_Video_Interleave) |
|
||||
| .gif | `yolo predict source=video.gif` | [Graphics Interchange Format](https://en.wikipedia.org/wiki/GIF) |
|
||||
| .m4v | `yolo predict source=video.m4v` | [MPEG-4 Part 14](https://en.wikipedia.org/wiki/M4V) |
|
||||
| .mkv | `yolo predict source=video.mkv` | [Matroska](https://en.wikipedia.org/wiki/Matroska) |
|
||||
| .mov | `yolo predict source=video.mov` | [QuickTime File Format](https://en.wikipedia.org/wiki/QuickTime_File_Format) |
|
||||
| .mp4 | `yolo predict source=video.mp4` | [MPEG-4 Part 14 - Wikipedia](https://en.wikipedia.org/wiki/MPEG-4_Part_14) |
|
||||
| .mpeg | `yolo predict source=video.mpeg` | [MPEG-1 Part 2](https://en.wikipedia.org/wiki/MPEG-1) |
|
||||
| .mpg | `yolo predict source=video.mpg` | [MPEG-1 Part 2](https://en.wikipedia.org/wiki/MPEG-1) |
|
||||
| .ts | `yolo predict source=video.ts` | [MPEG Transport Stream](https://en.wikipedia.org/wiki/MPEG_transport_stream) |
|
||||
| .wmv | `yolo predict source=video.wmv` | [Windows Media Video](https://en.wikipedia.org/wiki/Windows_Media_Video) |
|
||||
| .webm | `yolo predict source=video.webm` | [WebM Project](https://en.wikipedia.org/wiki/WebM) |
|
||||
|
||||
## Working with Results
|
||||
|
||||
All Ultralytics `predict()` calls will return a list of `Results` objects:
|
||||
|
||||
!!! example "Results"
|
||||
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a pretrained YOLOv8n model
|
||||
model = YOLO('yolov8n.pt')
|
||||
|
||||
# Run inference on an image
|
||||
results = model('bus.jpg') # list of 1 Results object
|
||||
results = model(['bus.jpg', 'zidane.jpg']) # list of 2 Results objects
|
||||
```
|
||||
|
||||
`Results` objects have the following attributes:
|
||||
|
||||
| Attribute | Type | Description |
|
||||
|--------------|-----------------------|------------------------------------------------------------------------------------------|
|
||||
| `orig_img` | `numpy.ndarray` | The original image as a numpy array. |
|
||||
| `orig_shape` | `tuple` | The original image shape in (height, width) format. |
|
||||
| `boxes` | `Boxes, optional` | A Boxes object containing the detection bounding boxes. |
|
||||
| `masks` | `Masks, optional` | A Masks object containing the detection masks. |
|
||||
| `probs` | `Probs, optional` | A Probs object containing probabilities of each class for classification task. |
|
||||
| `keypoints` | `Keypoints, optional` | A Keypoints object containing detected keypoints for each object. |
|
||||
| `speed` | `dict` | A dictionary of preprocess, inference, and postprocess speeds in milliseconds per image. |
|
||||
| `names` | `dict` | A dictionary of class names. |
|
||||
| `path` | `str` | The path to the image file. |
|
||||
|
||||
`Results` objects have the following methods:
|
||||
|
||||
| Method | Return Type | Description |
|
||||
|-----------------|-----------------|-------------------------------------------------------------------------------------|
|
||||
| `__getitem__()` | `Results` | Return a Results object for the specified index. |
|
||||
| `__len__()` | `int` | Return the number of detections in the Results object. |
|
||||
| `update()` | `None` | Update the boxes, masks, and probs attributes of the Results object. |
|
||||
| `cpu()` | `Results` | Return a copy of the Results object with all tensors on CPU memory. |
|
||||
| `numpy()` | `Results` | Return a copy of the Results object with all tensors as numpy arrays. |
|
||||
| `cuda()` | `Results` | Return a copy of the Results object with all tensors on GPU memory. |
|
||||
| `to()` | `Results` | Return a copy of the Results object with tensors on the specified device and dtype. |
|
||||
| `new()` | `Results` | Return a new Results object with the same image, path, and names. |
|
||||
| `keys()` | `List[str]` | Return a list of non-empty attribute names. |
|
||||
| `plot()` | `numpy.ndarray` | Plots the detection results. Returns a numpy array of the annotated image. |
|
||||
| `verbose()` | `str` | Return log string for each task. |
|
||||
| `save_txt()` | `None` | Save predictions into a txt file. |
|
||||
| `save_crop()` | `None` | Save cropped predictions to `save_dir/cls/file_name.jpg`. |
|
||||
| `tojson()` | `None` | Convert the object to JSON format. |
|
||||
|
||||
For more details see the `Results` class [documentation](../reference/engine/results.md).
|
||||
|
||||
### Boxes
|
||||
|
||||
`Boxes` object can be used to index, manipulate, and convert bounding boxes to different formats.
|
||||
|
||||
!!! example "Boxes"
|
||||
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a pretrained YOLOv8n model
|
||||
model = YOLO('yolov8n.pt')
|
||||
|
||||
# Run inference on an image
|
||||
results = model('bus.jpg') # results list
|
||||
|
||||
# View results
|
||||
for r in results:
|
||||
print(r.boxes) # print the Boxes object containing the detection bounding boxes
|
||||
```
|
||||
|
||||
Here is a table for the `Boxes` class methods and properties, including their name, type, and description:
|
||||
|
||||
| Name | Type | Description |
|
||||
|-----------|---------------------------|--------------------------------------------------------------------|
|
||||
| `cpu()` | Method | Move the object to CPU memory. |
|
||||
| `numpy()` | Method | Convert the object to a numpy array. |
|
||||
| `cuda()` | Method | Move the object to CUDA memory. |
|
||||
| `to()` | Method | Move the object to the specified device. |
|
||||
| `xyxy` | Property (`torch.Tensor`) | Return the boxes in xyxy format. |
|
||||
| `conf` | Property (`torch.Tensor`) | Return the confidence values of the boxes. |
|
||||
| `cls` | Property (`torch.Tensor`) | Return the class values of the boxes. |
|
||||
| `id` | Property (`torch.Tensor`) | Return the track IDs of the boxes (if available). |
|
||||
| `xywh` | Property (`torch.Tensor`) | Return the boxes in xywh format. |
|
||||
| `xyxyn` | Property (`torch.Tensor`) | Return the boxes in xyxy format normalized by original image size. |
|
||||
| `xywhn` | Property (`torch.Tensor`) | Return the boxes in xywh format normalized by original image size. |
|
||||
|
||||
For more details see the `Boxes` class [documentation](../reference/engine/results.md).
|
||||
|
||||
### Masks
|
||||
|
||||
`Masks` object can be used index, manipulate and convert masks to segments.
|
||||
|
||||
!!! example "Masks"
|
||||
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a pretrained YOLOv8n-seg Segment model
|
||||
model = YOLO('yolov8n-seg.pt')
|
||||
|
||||
# Run inference on an image
|
||||
results = model('bus.jpg') # results list
|
||||
|
||||
# View results
|
||||
for r in results:
|
||||
print(r.masks) # print the Masks object containing the detected instance masks
|
||||
```
|
||||
|
||||
Here is a table for the `Masks` class methods and properties, including their name, type, and description:
|
||||
|
||||
| Name | Type | Description |
|
||||
|-----------|---------------------------|-----------------------------------------------------------------|
|
||||
| `cpu()` | Method | Returns the masks tensor on CPU memory. |
|
||||
| `numpy()` | Method | Returns the masks tensor as a numpy array. |
|
||||
| `cuda()` | Method | Returns the masks tensor on GPU memory. |
|
||||
| `to()` | Method | Returns the masks tensor with the specified device and dtype. |
|
||||
| `xyn` | Property (`torch.Tensor`) | A list of normalized segments represented as tensors. |
|
||||
| `xy` | Property (`torch.Tensor`) | A list of segments in pixel coordinates represented as tensors. |
|
||||
|
||||
For more details see the `Masks` class [documentation](../reference/engine/results.md).
|
||||
|
||||
### Keypoints
|
||||
|
||||
`Keypoints` object can be used index, manipulate and normalize coordinates.
|
||||
|
||||
!!! example "Keypoints"
|
||||
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a pretrained YOLOv8n-pose Pose model
|
||||
model = YOLO('yolov8n-pose.pt')
|
||||
|
||||
# Run inference on an image
|
||||
results = model('bus.jpg') # results list
|
||||
|
||||
# View results
|
||||
for r in results:
|
||||
print(r.keypoints) # print the Keypoints object containing the detected keypoints
|
||||
```
|
||||
|
||||
Here is a table for the `Keypoints` class methods and properties, including their name, type, and description:
|
||||
|
||||
| Name | Type | Description |
|
||||
|-----------|---------------------------|-------------------------------------------------------------------|
|
||||
| `cpu()` | Method | Returns the keypoints tensor on CPU memory. |
|
||||
| `numpy()` | Method | Returns the keypoints tensor as a numpy array. |
|
||||
| `cuda()` | Method | Returns the keypoints tensor on GPU memory. |
|
||||
| `to()` | Method | Returns the keypoints tensor with the specified device and dtype. |
|
||||
| `xyn` | Property (`torch.Tensor`) | A list of normalized keypoints represented as tensors. |
|
||||
| `xy` | Property (`torch.Tensor`) | A list of keypoints in pixel coordinates represented as tensors. |
|
||||
| `conf` | Property (`torch.Tensor`) | Returns confidence values of keypoints if available, else None. |
|
||||
|
||||
For more details see the `Keypoints` class [documentation](../reference/engine/results.md).
|
||||
|
||||
### Probs
|
||||
|
||||
`Probs` object can be used index, get `top1` and `top5` indices and scores of classification.
|
||||
|
||||
!!! example "Probs"
|
||||
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a pretrained YOLOv8n-cls Classify model
|
||||
model = YOLO('yolov8n-cls.pt')
|
||||
|
||||
# Run inference on an image
|
||||
results = model('bus.jpg') # results list
|
||||
|
||||
# View results
|
||||
for r in results:
|
||||
print(r.probs) # print the Probs object containing the detected class probabilities
|
||||
```
|
||||
|
||||
Here's a table summarizing the methods and properties for the `Probs` class:
|
||||
|
||||
| Name | Type | Description |
|
||||
|------------|---------------------------|-------------------------------------------------------------------------|
|
||||
| `cpu()` | Method | Returns a copy of the probs tensor on CPU memory. |
|
||||
| `numpy()` | Method | Returns a copy of the probs tensor as a numpy array. |
|
||||
| `cuda()` | Method | Returns a copy of the probs tensor on GPU memory. |
|
||||
| `to()` | Method | Returns a copy of the probs tensor with the specified device and dtype. |
|
||||
| `top1` | Property (`int`) | Index of the top 1 class. |
|
||||
| `top5` | Property (`list[int]`) | Indices of the top 5 classes. |
|
||||
| `top1conf` | Property (`torch.Tensor`) | Confidence of the top 1 class. |
|
||||
| `top5conf` | Property (`torch.Tensor`) | Confidences of the top 5 classes. |
|
||||
|
||||
For more details see the `Probs` class [documentation](../reference/engine/results.md).
|
||||
|
||||
## Plotting Results
|
||||
|
||||
You can use the `plot()` method of a `Result` objects to visualize predictions. It plots all prediction types (boxes, masks, keypoints, probabilities, etc.) contained in the `Results` object onto a numpy array that can then be shown or saved.
|
||||
|
||||
!!! example "Plotting"
|
||||
|
||||
```python
|
||||
from PIL import Image
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a pretrained YOLOv8n model
|
||||
model = YOLO('yolov8n.pt')
|
||||
|
||||
# Run inference on 'bus.jpg'
|
||||
results = model('bus.jpg') # results list
|
||||
|
||||
# Show the results
|
||||
for r in results:
|
||||
im_array = r.plot() # plot a BGR numpy array of predictions
|
||||
im = Image.fromarray(im_array[..., ::-1]) # RGB PIL image
|
||||
im.show() # show image
|
||||
im.save('results.jpg') # save image
|
||||
```
|
||||
|
||||
The `plot()` method supports the following arguments:
|
||||
|
||||
| Argument | Type | Description | Default |
|
||||
|--------------|-----------------|--------------------------------------------------------------------------------|---------------|
|
||||
| `conf` | `bool` | Whether to plot the detection confidence score. | `True` |
|
||||
| `line_width` | `float` | The line width of the bounding boxes. If None, it is scaled to the image size. | `None` |
|
||||
| `font_size` | `float` | The font size of the text. If None, it is scaled to the image size. | `None` |
|
||||
| `font` | `str` | The font to use for the text. | `'Arial.ttf'` |
|
||||
| `pil` | `bool` | Whether to return the image as a PIL Image. | `False` |
|
||||
| `img` | `numpy.ndarray` | Plot to another image. if not, plot to original image. | `None` |
|
||||
| `im_gpu` | `torch.Tensor` | Normalized image in gpu with shape (1, 3, 640, 640), for faster mask plotting. | `None` |
|
||||
| `kpt_radius` | `int` | Radius of the drawn keypoints. Default is 5. | `5` |
|
||||
| `kpt_line` | `bool` | Whether to draw lines connecting keypoints. | `True` |
|
||||
| `labels` | `bool` | Whether to plot the label of bounding boxes. | `True` |
|
||||
| `boxes` | `bool` | Whether to plot the bounding boxes. | `True` |
|
||||
| `masks` | `bool` | Whether to plot the masks. | `True` |
|
||||
| `probs` | `bool` | Whether to plot classification probability | `True` |
|
||||
|
||||
## Thread-Safe Inference
|
||||
|
||||
Ensuring thread safety during inference is crucial when you are running multiple YOLO models in parallel across different threads. Thread-safe inference guarantees that each thread's predictions are isolated and do not interfere with one another, avoiding race conditions and ensuring consistent and reliable outputs.
|
||||
|
||||
When using YOLO models in a multi-threaded application, it's important to instantiate separate model objects for each thread or employ thread-local storage to prevent conflicts:
|
||||
|
||||
!!! example "Thread-Safe Inference"
|
||||
|
||||
Instantiate a single model inside each thread for thread-safe inference:
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
from threading import Thread
|
||||
|
||||
def thread_safe_predict(image_path):
|
||||
# Instantiate a new model inside the thread
|
||||
local_model = YOLO("yolov8n.pt")
|
||||
results = local_model.predict(image_path)
|
||||
# Process results
|
||||
|
||||
|
||||
# Starting threads that each have their own model instance
|
||||
Thread(target=thread_safe_predict, args=("image1.jpg",)).start()
|
||||
Thread(target=thread_safe_predict, args=("image2.jpg",)).start()
|
||||
```
|
||||
|
||||
For an in-depth look at thread-safe inference with YOLO models and step-by-step instructions, please refer to our [YOLO Thread-Safe Inference Guide](../guides/yolo-thread-safe-inference.md). This guide will provide you with all the necessary information to avoid common pitfalls and ensure that your multi-threaded inference runs smoothly.
|
||||
|
||||
## Streaming Source `for`-loop
|
||||
|
||||
Here's a Python script using OpenCV (`cv2`) and YOLOv8 to run inference on video frames. This script assumes you have already installed the necessary packages (`opencv-python` and `ultralytics`).
|
||||
|
||||
!!! example "Streaming for-loop"
|
||||
|
||||
```python
|
||||
import cv2
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load the YOLOv8 model
|
||||
model = YOLO('yolov8n.pt')
|
||||
|
||||
# Open the video file
|
||||
video_path = "path/to/your/video/file.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 YOLOv8 inference on the frame
|
||||
results = model(frame)
|
||||
|
||||
# Visualize the results on the frame
|
||||
annotated_frame = results[0].plot()
|
||||
|
||||
# Display the annotated frame
|
||||
cv2.imshow("YOLOv8 Inference", 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()
|
||||
```
|
||||
|
||||
This script will run predictions on each frame of the video, visualize the results, and display them in a window. The loop can be exited by pressing 'q'.
|
||||
354
docs/en/modes/track.md
Normal file
354
docs/en/modes/track.md
Normal file
|
|
@ -0,0 +1,354 @@
|
|||
---
|
||||
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
|
||||
---
|
||||
|
||||
# Multi-Object Tracking with Ultralytics YOLO
|
||||
|
||||
<img width="1024" src="https://user-images.githubusercontent.com/26833433/243418637-1d6250fd-1515-4c10-a844-a32818ae6d46.png" alt="Multi-object tracking examples">
|
||||
|
||||
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.
|
||||
|
||||
## 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.
|
||||
|
||||
<p align="center">
|
||||
<br>
|
||||
<iframe width="720" height="405" src="https://www.youtube.com/embed/hHyHmOtmEgs?si=VNZtXmm45Nb9s-N-"
|
||||
title="YouTube video player" frameborder="0"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
|
||||
allowfullscreen>
|
||||
</iframe>
|
||||
<br>
|
||||
<strong>Watch:</strong> Object Detection and Tracking with Ultralytics YOLOv8.
|
||||
</p>
|
||||
|
||||
## Real-world Applications
|
||||
|
||||
| Transportation | Retail | Aquaculture |
|
||||
|:----------------------------------------------------------------------------------------------------------------------:|:---------------------------------------------------------------------------------------------------------------------:|:-------------------------------------------------------------------------------------------------------------------:|
|
||||
|  |  |  |
|
||||
| Vehicle Tracking | People Tracking | Fish Tracking |
|
||||
|
||||
## 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.
|
||||
|
||||
!!! example ""
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load an official or custom model
|
||||
model = YOLO('yolov8n.pt') # Load an official Detect model
|
||||
model = YOLO('yolov8n-seg.pt') # Load an official Segment model
|
||||
model = YOLO('yolov8n-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
|
||||
```
|
||||
|
||||
=== "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.
|
||||
|
||||
!!! example ""
|
||||
|
||||
=== "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)
|
||||
```
|
||||
|
||||
=== "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.
|
||||
|
||||
!!! example ""
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load the model and run the tracker with a custom configuration file
|
||||
model = YOLO('yolov8n.pt')
|
||||
results = model.track(source="https://youtu.be/LNwODJXcvt4", tracker='custom_tracker.yaml')
|
||||
```
|
||||
|
||||
=== "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 that 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"
|
||||
|
||||
```python
|
||||
import cv2
|
||||
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)
|
||||
|
||||
# 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)
|
||||
|
||||
# Visualize the results on the frame
|
||||
annotated_frame = results[0].plot()
|
||||
|
||||
# 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()
|
||||
```
|
||||
|
||||
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'.
|
||||
|
||||
### Plotting Tracks Over Time
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
!!! example "Plotting tracks over multiple video frames"
|
||||
|
||||
```python
|
||||
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()
|
||||
```
|
||||
|
||||
### Multithreaded Tracking
|
||||
|
||||
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.
|
||||
|
||||
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, the model to use and the file index), 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()`.
|
||||
|
||||
!!! example "Streaming for-loop with tracking"
|
||||
|
||||
```python
|
||||
import threading
|
||||
import cv2
|
||||
from ultralytics import YOLO
|
||||
|
||||
|
||||
def run_tracker_in_thread(filename, model, file_index):
|
||||
"""
|
||||
Runs a video file or webcam stream concurrently with the YOLOv8 model using threading.
|
||||
|
||||
This function captures video frames from a given file or camera source and utilizes the YOLOv8 model for object
|
||||
tracking. The function runs in its own thread for concurrent processing.
|
||||
|
||||
Args:
|
||||
filename (str): The path to the video file or the identifier for the webcam/external camera source.
|
||||
model (obj): The YOLOv8 model object.
|
||||
file_index (int): An index to uniquely identify the file being processed, used for display purposes.
|
||||
|
||||
Note:
|
||||
Press 'q' to quit the video display window.
|
||||
"""
|
||||
video = cv2.VideoCapture(filename) # Read the video file
|
||||
|
||||
while True:
|
||||
ret, frame = video.read() # Read the video frames
|
||||
|
||||
# Exit the loop if no more frames in either video
|
||||
if not ret:
|
||||
break
|
||||
|
||||
# Track objects in frames if available
|
||||
results = model.track(frame, persist=True)
|
||||
res_plotted = results[0].plot()
|
||||
cv2.imshow(f"Tracking_Stream_{file_index}", res_plotted)
|
||||
|
||||
key = cv2.waitKey(1)
|
||||
if key == ord('q'):
|
||||
break
|
||||
|
||||
# Release video sources
|
||||
video.release()
|
||||
|
||||
|
||||
# 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" # Path to video file, 0 for webcam
|
||||
video_file2 = 0 # Path to video file, 0 for webcam, 1 for external camera
|
||||
|
||||
# Create the tracker threads
|
||||
tracker_thread1 = threading.Thread(target=run_tracker_in_thread, args=(video_file1, model1, 1), daemon=True)
|
||||
tracker_thread2 = threading.Thread(target=run_tracker_in_thread, args=(video_file2, model2, 2), 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.
|
||||
|
||||
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 🙏!
|
||||
294
docs/en/modes/train.md
Normal file
294
docs/en/modes/train.md
Normal file
|
|
@ -0,0 +1,294 @@
|
|||
---
|
||||
comments: true
|
||||
description: Step-by-step guide to train YOLOv8 models with Ultralytics YOLO including examples of single-GPU and multi-GPU training
|
||||
keywords: Ultralytics, YOLOv8, YOLO, object detection, train mode, custom dataset, GPU training, multi-GPU, hyperparameters, CLI examples, Python examples
|
||||
---
|
||||
|
||||
# Model Training with Ultralytics YOLO
|
||||
|
||||
<img width="1024" src="https://github.com/ultralytics/assets/raw/main/yolov8/banner-integrations.png" alt="Ultralytics YOLO ecosystem and integrations">
|
||||
|
||||
## Introduction
|
||||
|
||||
Training a deep learning model involves feeding it data and adjusting its parameters so that it can make accurate predictions. Train mode in Ultralytics YOLOv8 is engineered for effective and efficient training of object detection models, fully utilizing modern hardware capabilities. This guide aims to cover all the details you need to get started with training your own models using YOLOv8's robust set of features.
|
||||
|
||||
<p align="center">
|
||||
<br>
|
||||
<iframe width="720" height="405" src="https://www.youtube.com/embed/LNwODJXcvt4?si=7n1UvGRLSd9p5wKs"
|
||||
title="YouTube video player" frameborder="0"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
|
||||
allowfullscreen>
|
||||
</iframe>
|
||||
<br>
|
||||
<strong>Watch:</strong> How to Train a YOLOv8 model on Your Custom Dataset in Google Colab.
|
||||
</p>
|
||||
|
||||
## Why Choose Ultralytics YOLO for Training?
|
||||
|
||||
Here are some compelling reasons to opt for YOLOv8's Train mode:
|
||||
|
||||
- **Efficiency:** Make the most out of your hardware, whether you're on a single-GPU setup or scaling across multiple GPUs.
|
||||
- **Versatility:** Train on custom datasets in addition to readily available ones like COCO, VOC, and ImageNet.
|
||||
- **User-Friendly:** Simple yet powerful CLI and Python interfaces for a straightforward training experience.
|
||||
- **Hyperparameter Flexibility:** A broad range of customizable hyperparameters to fine-tune model performance.
|
||||
|
||||
### Key Features of Train Mode
|
||||
|
||||
The following are some notable features of YOLOv8's Train mode:
|
||||
|
||||
- **Automatic Dataset Download:** Standard datasets like COCO, VOC, and ImageNet are downloaded automatically on first use.
|
||||
- **Multi-GPU Support:** Scale your training efforts seamlessly across multiple GPUs to expedite the process.
|
||||
- **Hyperparameter Configuration:** The option to modify hyperparameters through YAML configuration files or CLI arguments.
|
||||
- **Visualization and Monitoring:** Real-time tracking of training metrics and visualization of the learning process for better insights.
|
||||
|
||||
!!! tip "Tip"
|
||||
|
||||
* YOLOv8 datasets like COCO, VOC, ImageNet and many others automatically download on first use, i.e. `yolo train data=coco.yaml`
|
||||
|
||||
## Usage Examples
|
||||
|
||||
Train YOLOv8n on the COCO128 dataset for 100 epochs at image size 640. The training device can be specified using the `device` argument. If no argument is passed GPU `device=0` will be used if available, otherwise `device=cpu` will be used. See Arguments section below for a full list of training arguments.
|
||||
|
||||
!!! example "Single-GPU and CPU Training Example"
|
||||
|
||||
Device is determined automatically. If a GPU is available then it will be used, otherwise training will start on CPU.
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a model
|
||||
model = YOLO('yolov8n.yaml') # build a new model from YAML
|
||||
model = YOLO('yolov8n.pt') # load a pretrained model (recommended for training)
|
||||
model = YOLO('yolov8n.yaml').load('yolov8n.pt') # build from YAML and transfer weights
|
||||
|
||||
# Train the model
|
||||
results = model.train(data='coco128.yaml', epochs=100, imgsz=640)
|
||||
```
|
||||
|
||||
=== "CLI"
|
||||
|
||||
```bash
|
||||
# Build a new model from YAML and start training from scratch
|
||||
yolo detect train data=coco128.yaml model=yolov8n.yaml epochs=100 imgsz=640
|
||||
|
||||
# Start training from a pretrained *.pt model
|
||||
yolo detect train data=coco128.yaml model=yolov8n.pt epochs=100 imgsz=640
|
||||
|
||||
# Build a new model from YAML, transfer pretrained weights to it and start training
|
||||
yolo detect train data=coco128.yaml model=yolov8n.yaml pretrained=yolov8n.pt epochs=100 imgsz=640
|
||||
```
|
||||
|
||||
### Multi-GPU Training
|
||||
|
||||
Multi-GPU training allows for more efficient utilization of available hardware resources by distributing the training load across multiple GPUs. This feature is available through both the Python API and the command-line interface. To enable multi-GPU training, specify the GPU device IDs you wish to use.
|
||||
|
||||
!!! example "Multi-GPU Training Example"
|
||||
|
||||
To train with 2 GPUs, CUDA devices 0 and 1 use the following commands. Expand to additional GPUs as required.
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a model
|
||||
model = YOLO('yolov8n.pt') # load a pretrained model (recommended for training)
|
||||
|
||||
# Train the model with 2 GPUs
|
||||
results = model.train(data='coco128.yaml', epochs=100, imgsz=640, device=[0, 1])
|
||||
```
|
||||
|
||||
=== "CLI"
|
||||
|
||||
```bash
|
||||
# Start training from a pretrained *.pt model using GPUs 0 and 1
|
||||
yolo detect train data=coco128.yaml model=yolov8n.pt epochs=100 imgsz=640 device=0,1
|
||||
```
|
||||
|
||||
### Apple M1 and M2 MPS Training
|
||||
|
||||
With the support for Apple M1 and M2 chips integrated in the Ultralytics YOLO models, it's now possible to train your models on devices utilizing the powerful Metal Performance Shaders (MPS) framework. The MPS offers a high-performance way of executing computation and image processing tasks on Apple's custom silicon.
|
||||
|
||||
To enable training on Apple M1 and M2 chips, you should specify 'mps' as your device when initiating the training process. Below is an example of how you could do this in Python and via the command line:
|
||||
|
||||
!!! example "MPS Training Example"
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a model
|
||||
model = YOLO('yolov8n.pt') # load a pretrained model (recommended for training)
|
||||
|
||||
# Train the model with 2 GPUs
|
||||
results = model.train(data='coco128.yaml', epochs=100, imgsz=640, device='mps')
|
||||
```
|
||||
|
||||
=== "CLI"
|
||||
|
||||
```bash
|
||||
# Start training from a pretrained *.pt model using GPUs 0 and 1
|
||||
yolo detect train data=coco128.yaml model=yolov8n.pt epochs=100 imgsz=640 device=mps
|
||||
```
|
||||
|
||||
While leveraging the computational power of the M1/M2 chips, this enables more efficient processing of the training tasks. For more detailed guidance and advanced configuration options, please refer to the [PyTorch MPS documentation](https://pytorch.org/docs/stable/notes/mps.html).
|
||||
|
||||
### Resuming Interrupted Trainings
|
||||
|
||||
Resuming training from a previously saved state is a crucial feature when working with deep learning models. This can come in handy in various scenarios, like when the training process has been unexpectedly interrupted, or when you wish to continue training a model with new data or for more epochs.
|
||||
|
||||
When training is resumed, Ultralytics YOLO loads the weights from the last saved model and also restores the optimizer state, learning rate scheduler, and the epoch number. This allows you to continue the training process seamlessly from where it was left off.
|
||||
|
||||
You can easily resume training in Ultralytics YOLO by setting the `resume` argument to `True` when calling the `train` method, and specifying the path to the `.pt` file containing the partially trained model weights.
|
||||
|
||||
Below is an example of how to resume an interrupted training using Python and via the command line:
|
||||
|
||||
!!! example "Resume Training Example"
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a model
|
||||
model = YOLO('path/to/last.pt') # load a partially trained model
|
||||
|
||||
# Resume training
|
||||
results = model.train(resume=True)
|
||||
```
|
||||
|
||||
=== "CLI"
|
||||
|
||||
```bash
|
||||
# Resume an interrupted training
|
||||
yolo train resume model=path/to/last.pt
|
||||
```
|
||||
|
||||
By setting `resume=True`, the `train` function will continue training from where it left off, using the state stored in the 'path/to/last.pt' file. If the `resume` argument is omitted or set to `False`, the `train` function will start a new training session.
|
||||
|
||||
Remember that checkpoints are saved at the end of every epoch by default, or at fixed interval using the `save_period` argument, so you must complete at least 1 epoch to resume a training run.
|
||||
|
||||
## Arguments
|
||||
|
||||
Training settings for YOLO models refer to the various hyperparameters and configurations used to train the model on a dataset. These settings can affect the model's performance, speed, and accuracy. Some common YOLO training settings include the batch size, learning rate, momentum, and weight decay. Other factors that may affect the training process include the choice of optimizer, the choice of loss function, and the size and composition of the training dataset. It is important to carefully tune and experiment with these settings to achieve the best possible performance for a given task.
|
||||
|
||||
| Key | Value | Description |
|
||||
|-------------------|----------|------------------------------------------------------------------------------------------------|
|
||||
| `model` | `None` | path to model file, i.e. yolov8n.pt, yolov8n.yaml |
|
||||
| `data` | `None` | path to data file, i.e. coco128.yaml |
|
||||
| `epochs` | `100` | number of epochs to train for |
|
||||
| `patience` | `50` | epochs to wait for no observable improvement for early stopping of training |
|
||||
| `batch` | `16` | number of images per batch (-1 for AutoBatch) |
|
||||
| `imgsz` | `640` | size of input images as integer |
|
||||
| `save` | `True` | save train checkpoints and predict results |
|
||||
| `save_period` | `-1` | Save checkpoint every x epochs (disabled if < 1) |
|
||||
| `cache` | `False` | True/ram, disk or False. Use cache for data loading |
|
||||
| `device` | `None` | device to run on, i.e. cuda device=0 or device=0,1,2,3 or device=cpu |
|
||||
| `workers` | `8` | number of worker threads for data loading (per RANK if DDP) |
|
||||
| `project` | `None` | project name |
|
||||
| `name` | `None` | experiment name |
|
||||
| `exist_ok` | `False` | whether to overwrite existing experiment |
|
||||
| `pretrained` | `True` | (bool or 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] |
|
||||
| `verbose` | `False` | whether to print verbose output |
|
||||
| `seed` | `0` | random seed for reproducibility |
|
||||
| `deterministic` | `True` | whether to enable deterministic mode |
|
||||
| `single_cls` | `False` | train multi-class data as single-class |
|
||||
| `rect` | `False` | rectangular training with each batch collated for minimum padding |
|
||||
| `cos_lr` | `False` | use cosine learning rate scheduler |
|
||||
| `close_mosaic` | `10` | (int) disable mosaic augmentation for final epochs (0 to disable) |
|
||||
| `resume` | `False` | resume training from last checkpoint |
|
||||
| `amp` | `True` | Automatic Mixed Precision (AMP) training, choices=[True, False] |
|
||||
| `fraction` | `1.0` | dataset fraction to train on (default is 1.0, all images in train set) |
|
||||
| `profile` | `False` | profile ONNX and TensorRT speeds during training for loggers |
|
||||
| `freeze` | `None` | (int or list, optional) freeze first n layers, or freeze list of layer indices during training |
|
||||
| `lr0` | `0.01` | initial learning rate (i.e. SGD=1E-2, Adam=1E-3) |
|
||||
| `lrf` | `0.01` | final learning rate (lr0 * lrf) |
|
||||
| `momentum` | `0.937` | SGD momentum/Adam beta1 |
|
||||
| `weight_decay` | `0.0005` | optimizer weight decay 5e-4 |
|
||||
| `warmup_epochs` | `3.0` | warmup epochs (fractions ok) |
|
||||
| `warmup_momentum` | `0.8` | warmup initial momentum |
|
||||
| `warmup_bias_lr` | `0.1` | warmup initial bias lr |
|
||||
| `box` | `7.5` | box loss gain |
|
||||
| `cls` | `0.5` | cls loss gain (scale with pixels) |
|
||||
| `dfl` | `1.5` | dfl loss gain |
|
||||
| `pose` | `12.0` | pose loss gain (pose-only) |
|
||||
| `kobj` | `2.0` | keypoint obj loss gain (pose-only) |
|
||||
| `label_smoothing` | `0.0` | label smoothing (fraction) |
|
||||
| `nbs` | `64` | nominal batch size |
|
||||
| `overlap_mask` | `True` | masks should overlap during training (segment train only) |
|
||||
| `mask_ratio` | `4` | mask downsample ratio (segment train only) |
|
||||
| `dropout` | `0.0` | use dropout regularization (classify train only) |
|
||||
| `val` | `True` | validate/test during training |
|
||||
|
||||
## Logging
|
||||
|
||||
In training a YOLOv8 model, you might find it valuable to keep track of the model's performance over time. This is where logging comes into play. Ultralytics' YOLO provides support for three types of loggers - Comet, ClearML, and TensorBoard.
|
||||
|
||||
To use a logger, select it from the dropdown menu in the code snippet above and run it. The chosen logger will be installed and initialized.
|
||||
|
||||
### Comet
|
||||
|
||||
[Comet](https://www.comet.ml/site/) is a platform that allows data scientists and developers to track, compare, explain and optimize experiments and models. It provides functionalities such as real-time metrics, code diffs, and hyperparameters tracking.
|
||||
|
||||
To use Comet:
|
||||
|
||||
!!! example ""
|
||||
|
||||
=== "Python"
|
||||
```python
|
||||
# pip install comet_ml
|
||||
import comet_ml
|
||||
|
||||
comet_ml.init()
|
||||
```
|
||||
|
||||
Remember to sign in to your Comet account on their website and get your API key. You will need to add this to your environment variables or your script to log your experiments.
|
||||
|
||||
### ClearML
|
||||
|
||||
[ClearML](https://www.clear.ml/) is an open-source platform that automates tracking of experiments and helps with efficient sharing of resources. It is designed to help teams manage, execute, and reproduce their ML work more efficiently.
|
||||
|
||||
To use ClearML:
|
||||
|
||||
!!! example ""
|
||||
|
||||
=== "Python"
|
||||
```python
|
||||
# pip install clearml
|
||||
import clearml
|
||||
|
||||
clearml.browser_login()
|
||||
```
|
||||
|
||||
After running this script, you will need to sign in to your ClearML account on the browser and authenticate your session.
|
||||
|
||||
### TensorBoard
|
||||
|
||||
[TensorBoard](https://www.tensorflow.org/tensorboard) is a visualization toolkit for TensorFlow. It allows you to visualize your TensorFlow graph, plot quantitative metrics about the execution of your graph, and show additional data like images that pass through it.
|
||||
|
||||
To use TensorBoard in [Google Colab](https://colab.research.google.com/github/ultralytics/ultralytics/blob/main/examples/tutorial.ipynb):
|
||||
|
||||
!!! example ""
|
||||
|
||||
=== "CLI"
|
||||
```bash
|
||||
load_ext tensorboard
|
||||
tensorboard --logdir ultralytics/runs # replace with 'runs' directory
|
||||
```
|
||||
|
||||
To use TensorBoard locally run the below command and view results at http://localhost:6006/.
|
||||
|
||||
!!! example ""
|
||||
|
||||
=== "CLI"
|
||||
```bash
|
||||
tensorboard --logdir ultralytics/runs # replace with 'runs' directory
|
||||
```
|
||||
|
||||
This will load TensorBoard and direct it to the directory where your training logs are saved.
|
||||
|
||||
After setting up your logger, you can then proceed with your model training. All training metrics will be automatically logged in your chosen platform, and you can access these logs to monitor your model's performance over time, compare different models, and identify areas for improvement.
|
||||
86
docs/en/modes/val.md
Normal file
86
docs/en/modes/val.md
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
---
|
||||
comments: true
|
||||
description: Guide for Validating YOLOv8 Models. Learn how to evaluate the performance of your YOLO models using validation settings and metrics with Python and CLI examples.
|
||||
keywords: Ultralytics, YOLO Docs, YOLOv8, validation, model evaluation, hyperparameters, accuracy, metrics, Python, CLI
|
||||
---
|
||||
|
||||
# Model Validation with Ultralytics YOLO
|
||||
|
||||
<img width="1024" src="https://github.com/ultralytics/assets/raw/main/yolov8/banner-integrations.png" alt="Ultralytics YOLO ecosystem and integrations">
|
||||
|
||||
## Introduction
|
||||
|
||||
Validation is a critical step in the machine learning pipeline, allowing you to assess the quality of your trained models. Val mode in Ultralytics YOLOv8 provides a robust suite of tools and metrics for evaluating the performance of your object detection models. This guide serves as a complete resource for understanding how to effectively use the Val mode to ensure that your models are both accurate and reliable.
|
||||
|
||||
## Why Validate with Ultralytics YOLO?
|
||||
|
||||
Here's why using YOLOv8's Val mode is advantageous:
|
||||
|
||||
- **Precision:** Get accurate metrics like mAP50, mAP75, and mAP50-95 to comprehensively evaluate your model.
|
||||
- **Convenience:** Utilize built-in features that remember training settings, simplifying the validation process.
|
||||
- **Flexibility:** Validate your model with the same or different datasets and image sizes.
|
||||
- **Hyperparameter Tuning:** Use validation metrics to fine-tune your model for better performance.
|
||||
|
||||
### Key Features of Val Mode
|
||||
|
||||
These are the notable functionalities offered by YOLOv8's Val mode:
|
||||
|
||||
- **Automated Settings:** Models remember their training configurations for straightforward validation.
|
||||
- **Multi-Metric Support:** Evaluate your model based on a range of accuracy metrics.
|
||||
- **CLI and Python API:** Choose from command-line interface or Python API based on your preference for validation.
|
||||
- **Data Compatibility:** Works seamlessly with datasets used during the training phase as well as custom datasets.
|
||||
|
||||
!!! tip "Tip"
|
||||
|
||||
* YOLOv8 models automatically remember their training settings, so you can validate a model at the same image size and on the original dataset easily with just `yolo val model=yolov8n.pt` or `model('yolov8n.pt').val()`
|
||||
|
||||
## Usage Examples
|
||||
|
||||
Validate trained YOLOv8n model accuracy on the COCO128 dataset. No argument need to passed as the `model` retains it's training `data` and arguments as model attributes. See Arguments section below for a full list of export arguments.
|
||||
|
||||
!!! example ""
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python
|
||||
from ultralytics import YOLO
|
||||
|
||||
# Load a model
|
||||
model = YOLO('yolov8n.pt') # load an official model
|
||||
model = YOLO('path/to/best.pt') # load a custom model
|
||||
|
||||
# Validate the model
|
||||
metrics = model.val() # no arguments needed, dataset and settings remembered
|
||||
metrics.box.map # map50-95
|
||||
metrics.box.map50 # map50
|
||||
metrics.box.map75 # map75
|
||||
metrics.box.maps # a list contains map50-95 of each category
|
||||
```
|
||||
=== "CLI"
|
||||
|
||||
```bash
|
||||
yolo detect val model=yolov8n.pt # val official model
|
||||
yolo detect val model=path/to/best.pt # val custom model
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
Validation settings for YOLO models refer to the various hyperparameters and configurations used to evaluate the model's performance on a validation dataset. These settings can affect the model's performance, speed, and accuracy. Some common YOLO validation settings include the batch size, the frequency with which validation is performed during training, and the metrics used to evaluate the model's performance. Other factors that may affect the validation process include the size and composition of the validation dataset and the specific task the model is being used for. It is important to carefully tune and experiment with these settings to ensure that the model is performing well on the validation dataset and to detect and prevent overfitting.
|
||||
|
||||
| Key | Value | Description |
|
||||
|---------------|---------|--------------------------------------------------------------------|
|
||||
| `data` | `None` | path to data file, i.e. coco128.yaml |
|
||||
| `imgsz` | `640` | size of input images as integer |
|
||||
| `batch` | `16` | number of images per batch (-1 for AutoBatch) |
|
||||
| `save_json` | `False` | save results to JSON file |
|
||||
| `save_hybrid` | `False` | save hybrid version of labels (labels + additional predictions) |
|
||||
| `conf` | `0.001` | object confidence threshold for detection |
|
||||
| `iou` | `0.6` | intersection over union (IoU) threshold for NMS |
|
||||
| `max_det` | `300` | maximum number of detections per image |
|
||||
| `half` | `True` | use half precision (FP16) |
|
||||
| `device` | `None` | device to run on, i.e. cuda device=0/1/2/3 or device=cpu |
|
||||
| `dnn` | `False` | use OpenCV DNN for ONNX inference |
|
||||
| `plots` | `False` | show plots during training |
|
||||
| `rect` | `False` | rectangular val with each batch collated for minimum padding |
|
||||
| `split` | `val` | dataset split to use for validation, i.e. 'val', 'test' or 'train' |
|
||||
|
|
||||
Loading…
Add table
Add a link
Reference in a new issue