Yolov8-源码解析-十七-
Yolov8 源码解析(十七)
comments: true
description: Harness the power of Ultralytics YOLOv8 for real-time, high-speed inference on various data sources. Learn about predict mode, key features, and practical applications.
keywords: Ultralytics, YOLOv8, model prediction, inference, predict mode, real-time inference, computer vision, machine learning, streaming, high performance
Model Prediction with Ultralytics YOLO
![Ultralytics YOLO ecosystem and integrations](https://github.com/ultralytics/assets/raw/main/yolov8/banner-integrations.png)
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.
Watch: How to Extract the Outputs from Ultralytics YOLOv8 Model for Custom Projects.
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 settingstream=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`"
```py
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 bounding box 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
obb = result.obb # Oriented boxes object for OBB outputs
result.show() # display to screen
result.save(filename="result.jpg") # save to disk
```
=== "Return a generator with `stream=True`"
```py
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 bounding box 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
obb = result.obb # Oriented boxes object for OBB outputs
result.show() # display to screen
result.save(filename="result.jpg") # save to disk
```
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.
```py
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.
```py
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.
```py
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).
```py
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.
```py
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.
```py
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.
```py
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.
```py
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.
```py
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/**/*`.
```py
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.
```py
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.
```py
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.
```py
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
```py
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)
```
Inference arguments:
Argument | Type | Default | Description |
---|---|---|---|
source |
str |
'ultralytics/assets' |
Specifies the data source for inference. Can be an image path, video file, directory, URL, or device ID for live feeds. Supports a wide range of formats and sources, enabling flexible application across different types of input. |
conf |
float |
0.25 |
Sets the minimum confidence threshold for detections. Objects detected with confidence below this threshold will be disregarded. Adjusting this value can help reduce false positives. |
iou |
float |
0.7 |
Intersection Over Union (IoU) threshold for Non-Maximum Suppression (NMS). Lower values result in fewer detections by eliminating overlapping boxes, useful for reducing duplicates. |
imgsz |
int or tuple |
640 |
Defines the image size for inference. Can be a single integer 640 for square resizing or a (height, width) tuple. Proper sizing can improve detection accuracy and processing speed. |
half |
bool |
False |
Enables half-precision (FP16) inference, which can speed up model inference on supported GPUs with minimal impact on accuracy. |
device |
str |
None |
Specifies the device for inference (e.g., cpu , cuda:0 or 0 ). Allows users to select between CPU, a specific GPU, or other compute devices for model execution. |
max_det |
int |
300 |
Maximum number of detections allowed per image. Limits the total number of objects the model can detect in a single inference, preventing excessive outputs in dense scenes. |
vid_stride |
int |
1 |
Frame stride for video inputs. Allows skipping frames in videos to speed up processing at the cost of temporal resolution. A value of 1 processes every frame, higher values skip frames. |
stream_buffer |
bool |
False |
Determines if all frames should be buffered when processing video streams (True ), or if the model should return the most recent frame (False ). Useful for real-time applications. |
visualize |
bool |
False |
Activates visualization of model features during inference, providing insights into what the model is "seeing". Useful for debugging and model interpretation. |
augment |
bool |
False |
Enables test-time augmentation (TTA) for predictions, potentially improving detection robustness at the cost of inference speed. |
agnostic_nms |
bool |
False |
Enables class-agnostic Non-Maximum Suppression (NMS), which merges overlapping boxes of different classes. Useful in multi-class detection scenarios where class overlap is common. |
classes |
list[int] |
None |
Filters predictions to a set of class IDs. Only detections belonging to the specified classes will be returned. Useful for focusing on relevant objects in multi-class detection tasks. |
retina_masks |
bool |
False |
Uses high-resolution segmentation masks if available in the model. This can enhance mask quality for segmentation tasks, providing finer detail. |
embed |
list[int] |
None |
Specifies the layers from which to extract feature vectors or embeddings. Useful for downstream tasks like clustering or similarity search. |
Visualization arguments:
Argument | Type | Default | Description |
---|---|---|---|
show |
bool |
False |
If True , displays the annotated images or videos in a window. Useful for immediate visual feedback during development or testing. |
save |
bool |
False |
Enables saving of the annotated images or videos to file. Useful for documentation, further analysis, or sharing results. |
save_frames |
bool |
False |
When processing videos, saves individual frames as images. Useful for extracting specific frames or for detailed frame-by-frame analysis. |
save_txt |
bool |
False |
Saves detection results in a text file, following the format [class] [x_center] [y_center] [width] [height] [confidence] . Useful for integration with other analysis tools. |
save_conf |
bool |
False |
Includes confidence scores in the saved text files. Enhances the detail available for post-processing and analysis. |
save_crop |
bool |
False |
Saves cropped images of detections. Useful for dataset augmentation, analysis, or creating focused datasets for specific objects. |
show_labels |
bool |
True |
Displays labels for each detection in the visual output. Provides immediate understanding of detected objects. |
show_conf |
bool |
True |
Displays the confidence score for each detection alongside the label. Gives insight into the model's certainty for each detection. |
show_boxes |
bool |
True |
Draws bounding boxes around detected objects. Essential for visual identification and location of objects in images or video frames. |
line_width |
None or int |
None |
Specifies the line width of bounding boxes. If None , the line width is automatically adjusted based on the image size. Provides visual customization for clarity. |
Image and Video Formats
YOLOv8 supports various image and video formats, as specified in 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 |
.dng |
yolo predict source=image.dng |
Adobe DNG |
.jpeg |
yolo predict source=image.jpeg |
JPEG |
.jpg |
yolo predict source=image.jpg |
JPEG |
.mpo |
yolo predict source=image.mpo |
Multi Picture Object |
.png |
yolo predict source=image.png |
Portable Network Graphics |
.tif |
yolo predict source=image.tif |
Tag Image File Format |
.tiff |
yolo predict source=image.tiff |
Tag Image File Format |
.webp |
yolo predict source=image.webp |
WebP |
.pfm |
yolo predict source=image.pfm |
Portable FloatMap |
Videos
The below table contains valid Ultralytics video formats.
Video Suffixes | Example Predict Command | Reference |
---|---|---|
.asf |
yolo predict source=video.asf |
Advanced Systems Format |
.avi |
yolo predict source=video.avi |
Audio Video Interleave |
.gif |
yolo predict source=video.gif |
Graphics Interchange Format |
.m4v |
yolo predict source=video.m4v |
MPEG-4 Part 14 |
.mkv |
yolo predict source=video.mkv |
Matroska |
.mov |
yolo predict source=video.mov |
QuickTime File Format |
.mp4 |
yolo predict source=video.mp4 |
MPEG-4 Part 14 - Wikipedia |
.mpeg |
yolo predict source=video.mpeg |
MPEG-1 Part 2 |
.mpg |
yolo predict source=video.mpg |
MPEG-1 Part 2 |
.ts |
yolo predict source=video.ts |
MPEG Transport Stream |
.wmv |
yolo predict source=video.wmv |
Windows Media Video |
.webm |
yolo predict source=video.webm |
WebM Project |
Working with Results
All Ultralytics predict()
calls will return a list of Results
objects:
!!! Example "Results"
```py
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. |
obb |
OBB, optional |
An OBB object containing oriented bounding boxes. |
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 |
---|---|---|
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. |
plot() |
numpy.ndarray |
Plots the detection results. Returns a numpy array of the annotated image. |
show() |
None |
Show annotated results to screen. |
save() |
None |
Save annotated results to file. |
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() |
str |
Convert the object to JSON format. |
For more details see the Results
class documentation.
Boxes
Boxes
object can be used to index, manipulate, and convert bounding boxes to different formats.
!!! Example "Boxes"
```py
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.
Masks
Masks
object can be used index, manipulate and convert masks to segments.
!!! Example "Masks"
```py
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.
Keypoints
Keypoints
object can be used index, manipulate and normalize coordinates.
!!! Example "Keypoints"
```py
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.
Probs
Probs
object can be used index, get top1
and top5
indices and scores of classification.
!!! Example "Probs"
```py
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.
OBB
OBB
object can be used to index, manipulate, and convert oriented bounding boxes to different formats.
!!! Example "OBB"
```py
from ultralytics import YOLO
# Load a pretrained YOLOv8n model
model = YOLO("yolov8n-obb.pt")
# Run inference on an image
results = model("bus.jpg") # results list
# View results
for r in results:
print(r.obb) # print the OBB object containing the oriented detection bounding boxes
```
Here is a table for the OBB
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. |
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). |
xyxy |
Property (torch.Tensor ) |
Return the horizontal boxes in xyxy format. |
xywhr |
Property (torch.Tensor ) |
Return the rotated boxes in xywhr format. |
xyxyxyxy |
Property (torch.Tensor ) |
Return the rotated boxes in xyxyxyxy format. |
xyxyxyxyn |
Property (torch.Tensor ) |
Return the rotated boxes in xyxyxyxy format normalized by image size. |
For more details see the OBB
class documentation.
Plotting Results
The plot()
method in Results
objects facilitates visualization of predictions by overlaying detected objects (such as bounding boxes, masks, keypoints, and probabilities) onto the original image. This method returns the annotated image as a NumPy array, allowing for easy display or saving.
!!! Example "Plotting"
```py
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", "zidane.jpg"]) # results list
# Visualize the results
for i, r in enumerate(results):
# Plot results image
im_bgr = r.plot() # BGR-order numpy array
im_rgb = Image.fromarray(im_bgr[..., ::-1]) # RGB-order PIL image
# Show results to screen (in supported environments)
r.show()
# Save results to disk
r.save(filename=f"results{i}.jpg")
```
plot()
Method Parameters
The plot()
method supports various arguments to customize the output:
Argument | Type | Description | Default |
---|---|---|---|
conf |
bool |
Include detection confidence scores. | True |
line_width |
float |
Line width of bounding boxes. Scales with image size if None . |
None |
font_size |
float |
Text font size. Scales with image size if None . |
None |
font |
str |
Font name for text annotations. | 'Arial.ttf' |
pil |
bool |
Return image as a PIL Image object. | False |
img |
numpy.ndarray |
Alternative image for plotting. Uses the original image if None . |
None |
im_gpu |
torch.Tensor |
GPU-accelerated image for faster mask plotting. Shape: (1, 3, 640, 640). | None |
kpt_radius |
int |
Radius for drawn keypoints. | 5 |
kpt_line |
bool |
Connect keypoints with lines. | True |
labels |
bool |
Include class labels in annotations. | True |
boxes |
bool |
Overlay bounding boxes on the image. | True |
masks |
bool |
Overlay masks on the image. | True |
probs |
bool |
Include classification probabilities. | True |
show |
bool |
Display the annotated image directly using the default image viewer. | False |
save |
bool |
Save the annotated image to a file specified by filename . |
False |
filename |
str |
Path and name of the file to save the annotated image if save is True . |
None |
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:
```py
from threading import Thread
from ultralytics import YOLO
def thread_safe_predict(image_path):
"""Performs thread-safe prediction on an image using a locally instantiated YOLO model."""
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. 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"
```py
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'.
FAQ
What is Ultralytics YOLOv8 and its predict mode for real-time inference?
Ultralytics YOLOv8 is a state-of-the-art model for real-time object detection, segmentation, and classification. Its predict mode allows users to perform high-speed inference on various data sources such as images, videos, and live streams. Designed for performance and versatility, it also offers batch processing and streaming modes. For more details on its features, check out the Ultralytics YOLOv8 predict mode.
How can I run inference using Ultralytics YOLOv8 on different data sources?
Ultralytics YOLOv8 can process a wide range of data sources, including individual images, videos, directories, URLs, and streams. You can specify the data source in the model.predict()
call. For example, use 'image.jpg'
for a local image or 'https://ultralytics.com/images/bus.jpg'
for a URL. Check out the detailed examples for various inference sources in the documentation.
How do I optimize YOLOv8 inference speed and memory usage?
To optimize inference speed and manage memory efficiently, you can use the streaming mode by setting stream=True
in the predictor's call method. The streaming mode generates a memory-efficient generator of Results
objects instead of loading all frames into memory. For processing long videos or large datasets, streaming mode is particularly useful. Learn more about streaming mode.
What inference arguments does Ultralytics YOLOv8 support?
The model.predict()
method in YOLOv8 supports various arguments such as conf
, iou
, imgsz
, device
, and more. These arguments allow you to customize the inference process, setting parameters like confidence thresholds, image size, and the device used for computation. Detailed descriptions of these arguments can be found in the inference arguments section.
How can I visualize and save the results of YOLOv8 predictions?
After running inference with YOLOv8, the Results
objects contain methods for displaying and saving annotated images. You can use methods like result.show()
and result.save(filename="result.jpg")
to visualize and save the results. For a comprehensive list of these methods, refer to the working with results section.
comments: true
description: Discover efficient, flexible, and customizable multi-object tracking with Ultralytics YOLO. Learn to track real-time video streams with ease.
keywords: multi-object tracking, Ultralytics YOLO, video analytics, real-time tracking, object detection, AI, machine learning
Multi-Object Tracking with Ultralytics YOLO
![Multi-object tracking examples](https://user-images.githubusercontent.com/26833433/243418637-1d6250fd-1515-4c10-a844-a32818ae6d46.png)
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.
Watch: Object Detection and Tracking with Ultralytics YOLOv8.
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 - Use
botsort.yaml
to enable this tracker. - ByteTrack - Use
bytetrack.yaml
to enable this tracker.
The default tracker is BoT-SORT.
Tracking
!!! Warning "Tracker Threshold Information"
If object confidence score will be low, i.e lower than [`track_high_thresh`](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/trackers/bytetrack.yaml#L5), then there will be no tracks successfully returned and updated.
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"
```py
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("https://youtu.be/LNwODJXcvt4", show=True) # Tracking with default tracker
results = model.track("https://youtu.be/LNwODJXcvt4", show=True, tracker="bytetrack.yaml") # with ByteTrack
```
=== "CLI"
```py
# 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
!!! Warning "Tracker Threshold Information"
If object confidence score will be low, i.e lower than [`track_high_thresh`](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/trackers/bytetrack.yaml#L5), then there will be no tracks successfully returned and updated.
Tracking Arguments
Tracking configuration shares properties with Predict mode, such as conf
, iou
, and show
. For further configurations, refer to the Predict model page.
!!! Example
=== "Python"
```py
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"
```py
# 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 and modify any configurations (except the tracker_type
) as per your needs.
!!! Example
=== "Python"
```py
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"
```py
# 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 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"
```py
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"
```py
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"
```py
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! 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 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 🙏!
FAQ
What is Multi-Object Tracking and how does Ultralytics YOLO support it?
Multi-object tracking in video analytics involves both identifying objects and maintaining a unique ID for each detected object across video frames. Ultralytics YOLO supports this by providing real-time tracking along with object IDs, facilitating tasks such as security surveillance and sports analytics. The system uses trackers like BoT-SORT and ByteTrack, which can be configured via YAML files.
How do I configure a custom tracker for Ultralytics YOLO?
You can configure a custom tracker by copying an existing tracker configuration file (e.g., custom_tracker.yaml
) from the Ultralytics tracker configuration directory and modifying parameters as needed, except for the tracker_type
. Use this file in your tracking model like so:
!!! Example
=== "Python"
```py
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
results = model.track(source="https://youtu.be/LNwODJXcvt4", tracker="custom_tracker.yaml")
```
=== "CLI"
```py
yolo track model=yolov8n.pt source="https://youtu.be/LNwODJXcvt4" tracker='custom_tracker.yaml'
```
How can I run object tracking on multiple video streams simultaneously?
To run object tracking on multiple video streams simultaneously, you can use Python's threading
module. Each thread will handle a separate video stream. Here's an example of how you can set this up:
!!! Example "Multithreaded Tracking"
```py
import threading
import cv2
from ultralytics import YOLO
def run_tracker_in_thread(filename, model, file_index):
video = cv2.VideoCapture(filename)
while True:
ret, frame = video.read()
if not ret:
break
results = model.track(frame, persist=True)
res_plotted = results[0].plot()
cv2.imshow(f"Tracking_Stream_{file_index}", res_plotted)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
video.release()
model1 = YOLO("yolov8n.pt")
model2 = YOLO("yolov8n-seg.pt")
video_file1 = "path/to/video1.mp4"
video_file2 = 0 # Path to a second video file, or 0 for a webcam
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)
tracker_thread1.start()
tracker_thread2.start()
tracker_thread1.join()
tracker_thread2.join()
cv2.destroyAllWindows()
```
What are the real-world applications of multi-object tracking with Ultralytics YOLO?
Multi-object tracking with Ultralytics YOLO has numerous applications, including:
- Transportation: Vehicle tracking for traffic management and autonomous driving.
- Retail: People tracking for in-store analytics and security.
- Aquaculture: Fish tracking for monitoring aquatic environments.
These applications benefit from Ultralytics YOLO's ability to process high-frame-rate videos in real time.
How can I visualize object tracks over multiple video frames with Ultralytics YOLO?
To visualize object tracks over multiple video frames, you can use the YOLO model's tracking features along with OpenCV to draw the paths of detected objects. Here's an example script that demonstrates this:
!!! Example "Plotting tracks over multiple video frames"
```py
from collections import defaultdict
import cv2
import numpy as np
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
video_path = "path/to/video.mp4"
cap = cv2.VideoCapture(video_path)
track_history = defaultdict(lambda: [])
while cap.isOpened():
success, frame = cap.read()
if success:
results = model.track(frame, persist=True)
boxes = results[0].boxes.xywh.cpu()
track_ids = results[0].boxes.id.int().cpu().tolist()
annotated_frame = results[0].plot()
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)))
if len(track) > 30:
track.pop(0)
points = np.hstack(track).astype(np.int32).reshape((-1, 1, 2))
cv2.polylines(annotated_frame, [points], isClosed=False, color=(230, 230, 230), thickness=10)
cv2.imshow("YOLOv8 Tracking", annotated_frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
else:
break
cap.release()
cv2.destroyAllWindows()
```
This script will plot the tracking lines showing the movement paths of the tracked objects over time.
comments: true
description: Learn how to efficiently train object detection models using YOLOv8 with comprehensive instructions on settings, augmentation, and hardware utilization.
keywords: Ultralytics, YOLOv8, model training, deep learning, object detection, GPU training, dataset augmentation, hyperparameter tuning, model performance, M1 M2 training
Model Training with Ultralytics YOLO
![Ultralytics YOLO ecosystem and integrations](https://github.com/ultralytics/assets/raw/main/yolov8/banner-integrations.png)
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.
Watch: How to Train a YOLOv8 model on Your Custom Dataset in Google Colab.
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 COCO8 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"
```py
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="coco8.yaml", epochs=100, imgsz=640)
```
=== "CLI"
```py
# Build a new model from YAML and start training from scratch
yolo detect train data=coco8.yaml model=yolov8n.yaml epochs=100 imgsz=640
# Start training from a pretrained *.pt model
yolo detect train data=coco8.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=coco8.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"
```py
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="coco8.yaml", epochs=100, imgsz=640, device=[0, 1])
```
=== "CLI"
```py
# Start training from a pretrained *.pt model using GPUs 0 and 1
yolo detect train data=coco8.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"
```py
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="coco8.yaml", epochs=100, imgsz=640, device="mps")
```
=== "CLI"
```py
# Start training from a pretrained *.pt model using GPUs 0 and 1
yolo detect train data=coco8.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.
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"
```py
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"
```py
# 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.
Train Settings
The training settings for YOLO models encompass various hyperparameters and configurations used during the training process. These settings influence the model's performance, speed, and accuracy. Key training settings include batch size, learning rate, momentum, and weight decay. Additionally, the choice of optimizer, loss function, and training dataset composition can impact the training process. Careful tuning and experimentation with these settings are crucial for optimizing performance.
Argument | Default | Description |
---|---|---|
model |
None |
Specifies the model file for training. Accepts a path to either a .pt pretrained model or a .yaml configuration file. Essential for defining the model structure or initializing weights. |
data |
None |
Path to the dataset configuration file (e.g., coco8.yaml ). This file contains dataset-specific parameters, including paths to training and validation data, class names, and number of classes. |
epochs |
100 |
Total number of training epochs. Each epoch represents a full pass over the entire dataset. Adjusting this value can affect training duration and model performance. |
time |
None |
Maximum training time in hours. If set, this overrides the epochs argument, allowing training to automatically stop after the specified duration. Useful for time-constrained training scenarios. |
patience |
100 |
Number of epochs to wait without improvement in validation metrics before early stopping the training. Helps prevent overfitting by stopping training when performance plateaus. |
batch |
16 |
Batch size, with three modes: set as an integer (e.g., batch=16 ), auto mode for 60% GPU memory utilization (batch=-1 ), or auto mode with specified utilization fraction (batch=0.70 ). |
imgsz |
640 |
Target image size for training. All images are resized to this dimension before being fed into the model. Affects model accuracy and computational complexity. |
save |
True |
Enables saving of training checkpoints and final model weights. Useful for resuming training or model deployment. |
save_period |
-1 |
Frequency of saving model checkpoints, specified in epochs. A value of -1 disables this feature. Useful for saving interim models during long training sessions. |
cache |
False |
Enables caching of dataset images in memory (True /ram ), on disk (disk ), or disables it (False ). Improves training speed by reducing disk I/O at the cost of increased memory usage. |
device |
None |
Specifies the computational device(s) for training: a single GPU (device=0 ), multiple GPUs (device=0,1 ), CPU (device=cpu ), or MPS for Apple silicon (device=mps ). |
workers |
8 |
Number of worker threads for data loading (per RANK if Multi-GPU training). Influences the speed of data preprocessing and feeding into the model, especially useful in multi-GPU setups. |
project |
None |
Name of the project directory where training outputs are saved. Allows for organized storage of different experiments. |
name |
None |
Name of the training run. Used for creating a subdirectory within the project folder, where training logs and outputs are stored. |
exist_ok |
False |
If True, allows overwriting of an existing project/name directory. Useful for iterative experimentation without needing to manually clear previous outputs. |
pretrained |
True |
Determines whether to start training from a pretrained model. Can be a boolean value or a string path to a specific model from which to load weights. Enhances training efficiency and model performance. |
optimizer |
'auto' |
Choice of optimizer for training. Options include SGD , Adam , AdamW , NAdam , RAdam , RMSProp etc., or auto for automatic selection based on model configuration. Affects convergence speed and stability. |
verbose |
False |
Enables verbose output during training, providing detailed logs and progress updates. Useful for debugging and closely monitoring the training process. |
seed |
0 |
Sets the random seed for training, ensuring reproducibility of results across runs with the same configurations. |
deterministic |
True |
Forces deterministic algorithm use, ensuring reproducibility but may affect performance and speed due to the restriction on non-deterministic algorithms. |
single_cls |
False |
Treats all classes in multi-class datasets as a single class during training. Useful for binary classification tasks or when focusing on object presence rather than classification. |
rect |
False |
Enables rectangular training, optimizing batch composition for minimal padding. Can improve efficiency and speed but may affect model accuracy. |
cos_lr |
False |
Utilizes a cosine learning rate scheduler, adjusting the learning rate following a cosine curve over epochs. Helps in managing learning rate for better convergence. |
close_mosaic |
10 |
Disables mosaic data augmentation in the last N epochs to stabilize training before completion. Setting to 0 disables this feature. |
resume |
False |
Resumes training from the last saved checkpoint. Automatically loads model weights, optimizer state, and epoch count, continuing training seamlessly. |
amp |
True |
Enables Automatic Mixed Precision (AMP) training, reducing memory usage and possibly speeding up training with minimal impact on accuracy. |
fraction |
1.0 |
Specifies the fraction of the dataset to use for training. Allows for training on a subset of the full dataset, useful for experiments or when resources are limited. |
profile |
False |
Enables profiling of ONNX and TensorRT speeds during training, useful for optimizing model deployment. |
freeze |
None |
Freezes the first N layers of the model or specified layers by index, reducing the number of trainable parameters. Useful for fine-tuning or transfer learning. |
lr0 |
0.01 |
Initial learning rate (i.e. SGD=1E-2 , Adam=1E-3 ) . Adjusting this value is crucial for the optimization process, influencing how rapidly model weights are updated. |
lrf |
0.01 |
Final learning rate as a fraction of the initial rate = (lr0 * lrf ), used in conjunction with schedulers to adjust the learning rate over time. |
momentum |
0.937 |
Momentum factor for SGD or beta1 for Adam optimizers, influencing the incorporation of past gradients in the current update. |
weight_decay |
0.0005 |
L2 regularization term, penalizing large weights to prevent overfitting. |
warmup_epochs |
3.0 |
Number of epochs for learning rate warmup, gradually increasing the learning rate from a low value to the initial learning rate to stabilize training early on. |
warmup_momentum |
0.8 |
Initial momentum for warmup phase, gradually adjusting to the set momentum over the warmup period. |
warmup_bias_lr |
0.1 |
Learning rate for bias parameters during the warmup phase, helping stabilize model training in the initial epochs. |
box |
7.5 |
Weight of the box loss component in the loss function, influencing how much emphasis is placed on accurately predicting bounding box coordinates. |
cls |
0.5 |
Weight of the classification loss in the total loss function, affecting the importance of correct class prediction relative to other components. |
dfl |
1.5 |
Weight of the distribution focal loss, used in certain YOLO versions for fine-grained classification. |
pose |
12.0 |
Weight of the pose loss in models trained for pose estimation, influencing the emphasis on accurately predicting pose keypoints. |
kobj |
2.0 |
Weight of the keypoint objectness loss in pose estimation models, balancing detection confidence with pose accuracy. |
label_smoothing |
0.0 |
Applies label smoothing, softening hard labels to a mix of the target label and a uniform distribution over labels, can improve generalization. |
nbs |
64 |
Nominal batch size for normalization of loss. |
overlap_mask |
True |
Determines whether segmentation masks should overlap during training, applicable in instance segmentation tasks. |
mask_ratio |
4 |
Downsample ratio for segmentation masks, affecting the resolution of masks used during training. |
dropout |
0.0 |
Dropout rate for regularization in classification tasks, preventing overfitting by randomly omitting units during training. |
val |
True |
Enables validation during training, allowing for periodic evaluation of model performance on a separate dataset. |
plots |
False |
Generates and saves plots of training and validation metrics, as well as prediction examples, providing visual insights into model performance and learning progression. |
!!! info "Note on Batch-size Settings"
The `batch` argument can be configured in three ways:
- **Fixed Batch Size**: Set an integer value (e.g., `batch=16`), specifying the number of images per batch directly.
- **Auto Mode (60% GPU Memory)**: Use `batch=-1` to automatically adjust batch size for approximately 60% CUDA memory utilization.
- **Auto Mode with Utilization Fraction**: Set a fraction value (e.g., `batch=0.70`) to adjust batch size based on the specified fraction of GPU memory usage.
Augmentation Settings and Hyperparameters
Augmentation techniques are essential for improving the robustness and performance of YOLO models by introducing variability into the training data, helping the model generalize better to unseen data. The following table outlines the purpose and effect of each augmentation argument:
Argument | Type | Default | Range | Description |
---|---|---|---|---|
hsv_h |
float |
0.015 |
0.0 - 1.0 |
Adjusts the hue of the image by a fraction of the color wheel, introducing color variability. Helps the model generalize across different lighting conditions. |
hsv_s |
float |
0.7 |
0.0 - 1.0 |
Alters the saturation of the image by a fraction, affecting the intensity of colors. Useful for simulating different environmental conditions. |
hsv_v |
float |
0.4 |
0.0 - 1.0 |
Modifies the value (brightness) of the image by a fraction, helping the model to perform well under various lighting conditions. |
degrees |
float |
0.0 |
-180 - +180 |
Rotates the image randomly within the specified degree range, improving the model's ability to recognize objects at various orientations. |
translate |
float |
0.1 |
0.0 - 1.0 |
Translates the image horizontally and vertically by a fraction of the image size, aiding in learning to detect partially visible objects. |
scale |
float |
0.5 |
>=0.0 |
Scales the image by a gain factor, simulating objects at different distances from the camera. |
shear |
float |
0.0 |
-180 - +180 |
Shears the image by a specified degree, mimicking the effect of objects being viewed from different angles. |
perspective |
float |
0.0 |
0.0 - 0.001 |
Applies a random perspective transformation to the image, enhancing the model's ability to understand objects in 3D space. |
flipud |
float |
0.0 |
0.0 - 1.0 |
Flips the image upside down with the specified probability, increasing the data variability without affecting the object's characteristics. |
fliplr |
float |
0.5 |
0.0 - 1.0 |
Flips the image left to right with the specified probability, useful for learning symmetrical objects and increasing dataset diversity. |
bgr |
float |
0.0 |
0.0 - 1.0 |
Flips the image channels from RGB to BGR with the specified probability, useful for increasing robustness to incorrect channel ordering. |
mosaic |
float |
1.0 |
0.0 - 1.0 |
Combines four training images into one, simulating different scene compositions and object interactions. Highly effective for complex scene understanding. |
mixup |
float |
0.0 |
0.0 - 1.0 |
Blends two images and their labels, creating a composite image. Enhances the model's ability to generalize by introducing label noise and visual variability. |
copy_paste |
float |
0.0 |
0.0 - 1.0 |
Copies objects from one image and pastes them onto another, useful for increasing object instances and learning object occlusion. |
auto_augment |
str |
randaugment |
- | Automatically applies a predefined augmentation policy (randaugment , autoaugment , augmix ), optimizing for classification tasks by diversifying the visual features. |
erasing |
float |
0.4 |
0.0 - 0.9 |
Randomly erases a portion of the image during classification training, encouraging the model to focus on less obvious features for recognition. |
crop_fraction |
float |
1.0 |
0.1 - 1.0 |
Crops the classification image to a fraction of its size to emphasize central features and adapt to object scales, reducing background distractions. |
These settings can be adjusted to meet the specific requirements of the dataset and task at hand. Experimenting with different values can help find the optimal augmentation strategy that leads to the best model performance.
!!! info
For more information about training augmentation operations, see the [reference section](../reference/data/augment.md).
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 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"
```py
# 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 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"
```py
# 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 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:
!!! Example
=== "CLI"
```py
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"
```py
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.
FAQ
How do I train an object detection model using Ultralytics YOLOv8?
To train an object detection model using Ultralytics YOLOv8, you can either use the Python API or the CLI. Below is an example for both:
!!! Example "Single-GPU and CPU Training Example"
=== "Python"
```py
from ultralytics import YOLO
# Load a model
model = YOLO("yolov8n.pt") # load a pretrained model (recommended for training)
# Train the model
results = model.train(data="coco8.yaml", epochs=100, imgsz=640)
```
=== "CLI"
```py
yolo detect train data=coco8.yaml model=yolov8n.pt epochs=100 imgsz=640
```
For more details, refer to the Train Settings section.
What are the key features of Ultralytics YOLOv8's Train mode?
The key features of Ultralytics YOLOv8's Train mode include:
- Automatic Dataset Download: Automatically downloads standard datasets like COCO, VOC, and ImageNet.
- Multi-GPU Support: Scale training across multiple GPUs for faster processing.
- Hyperparameter Configuration: Customize hyperparameters through YAML files or CLI arguments.
- Visualization and Monitoring: Real-time tracking of training metrics for better insights.
These features make training efficient and customizable to your needs. For more details, see the Key Features of Train Mode section.
How do I resume training from an interrupted session in Ultralytics YOLOv8?
To resume training from an interrupted session, set the resume
argument to True
and specify the path to the last saved checkpoint.
!!! Example "Resume Training Example"
=== "Python"
```py
from ultralytics import YOLO
# Load the partially trained model
model = YOLO("path/to/last.pt")
# Resume training
results = model.train(resume=True)
```
=== "CLI"
```py
yolo train resume model=path/to/last.pt
```
Check the section on Resuming Interrupted Trainings for more information.
Can I train YOLOv8 models on Apple M1 and M2 chips?
Yes, Ultralytics YOLOv8 supports training on Apple M1 and M2 chips utilizing the Metal Performance Shaders (MPS) framework. Specify 'mps' as your training device.
!!! Example "MPS Training Example"
=== "Python"
```py
from ultralytics import YOLO
# Load a pretrained model
model = YOLO("yolov8n.pt")
# Train the model on M1/M2 chip
results = model.train(data="coco8.yaml", epochs=100, imgsz=640, device="mps")
```
=== "CLI"
```py
yolo detect train data=coco8.yaml model=yolov8n.pt epochs=100 imgsz=640 device=mps
```
For more details, refer to the Apple M1 and M2 MPS Training section.
What are the common training settings, and how do I configure them?
Ultralytics YOLOv8 allows you to configure a variety of training settings such as batch size, learning rate, epochs, and more through arguments. Here's a brief overview:
Argument | Default | Description |
---|---|---|
model |
None |
Path to the model file for training. |
data |
None |
Path to the dataset configuration file (e.g., coco8.yaml ). |
epochs |
100 |
Total number of training epochs. |
batch |
16 |
Batch size, adjustable as integer or auto mode. |
imgsz |
640 |
Target image size for training. |
device |
None |
Computational device(s) for training like cpu , 0 , 0,1 , or mps . |
save |
True |
Enables saving of training checkpoints and final model weights. |
For an in-depth guide on training settings, check the Train Settings section.
comments: true
description: Learn how to validate your YOLOv8 model with precise metrics, easy-to-use tools, and custom settings for optimal performance.
keywords: Ultralytics, YOLOv8, model validation, machine learning, object detection, mAP metrics, Python API, CLI
Model Validation with Ultralytics YOLO
![Ultralytics YOLO ecosystem and integrations](https://github.com/ultralytics/assets/raw/main/yolov8/banner-integrations.png)
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.
Watch: Ultralytics Modes Tutorial: Validation
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 COCO8 dataset. No argument need to passed as the model
retains its training data
and arguments as model attributes. See Arguments section below for a full list of export arguments.
!!! Example
=== "Python"
```py
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"
```py
yolo detect val model=yolov8n.pt # val official model
yolo detect val model=path/to/best.pt # val custom model
```
Arguments for YOLO Model Validation
When validating YOLO models, several arguments can be fine-tuned to optimize the evaluation process. These arguments control aspects such as input image size, batch processing, and performance thresholds. Below is a detailed breakdown of each argument to help you customize your validation settings effectively.
Argument | Type | Default | Description |
---|---|---|---|
data |
str |
None |
Specifies the path to the dataset configuration file (e.g., coco8.yaml ). This file includes paths to validation data, class names, and number of classes. |
imgsz |
int |
640 |
Defines the size of input images. All images are resized to this dimension before processing. |
batch |
int |
16 |
Sets the number of images per batch. Use -1 for AutoBatch, which automatically adjusts based on GPU memory availability. |
save_json |
bool |
False |
If True , saves the results to a JSON file for further analysis or integration with other tools. |
save_hybrid |
bool |
False |
If True , saves a hybrid version of labels that combines original annotations with additional model predictions. |
conf |
float |
0.001 |
Sets the minimum confidence threshold for detections. Detections with confidence below this threshold are discarded. |
iou |
float |
0.6 |
Sets the Intersection Over Union (IoU) threshold for Non-Maximum Suppression (NMS). Helps in reducing duplicate detections. |
max_det |
int |
300 |
Limits the maximum number of detections per image. Useful in dense scenes to prevent excessive detections. |
half |
bool |
True |
Enables half-precision (FP16) computation, reducing memory usage and potentially increasing speed with minimal impact on accuracy. |
device |
str |
None |
Specifies the device for validation (cpu , cuda:0 , etc.). Allows flexibility in utilizing CPU or GPU resources. |
dnn |
bool |
False |
If True , uses the OpenCV DNN module for ONNX model inference, offering an alternative to PyTorch inference methods. |
plots |
bool |
False |
When set to True , generates and saves plots of predictions versus ground truth for visual evaluation of the model's performance. |
rect |
bool |
False |
If True , uses rectangular inference for batching, reducing padding and potentially increasing speed and efficiency. |
split |
str |
val |
Determines the dataset split to use for validation (val , test , or train ). Allows flexibility in choosing the data segment for performance evaluation. |
Each of these settings plays a vital role in the validation process, allowing for a customizable and efficient evaluation of YOLO models. Adjusting these parameters according to your specific needs and resources can help achieve the best balance between accuracy and performance.
Example Validation with Arguments
The below examples showcase YOLO model validation with custom arguments in Python and CLI.
!!! Example
=== "Python"
```py
from ultralytics import YOLO
# Load a model
model = YOLO("yolov8n.pt")
# Customize validation settings
validation_results = model.val(data="coco8.yaml", imgsz=640, batch=16, conf=0.25, iou=0.6, device="0")
```
=== "CLI"
```py
yolo val model=yolov8n.pt data=coco8.yaml imgsz=640 batch=16 conf=0.25 iou=0.6 device=0
```
FAQ
How do I validate my YOLOv8 model with Ultralytics?
To validate your YOLOv8 model, you can use the Val mode provided by Ultralytics. For example, using the Python API, you can load a model and run validation with:
from ultralytics import YOLO
# Load a model
model = YOLO("yolov8n.pt")
# Validate the model
metrics = model.val()
print(metrics.box.map) # map50-95
Alternatively, you can use the command-line interface (CLI):
yolo val model=yolov8n.pt
For further customization, you can adjust various arguments like imgsz
, batch
, and conf
in both Python and CLI modes. Check the Arguments for YOLO Model Validation section for the full list of parameters.
What metrics can I get from YOLOv8 model validation?
YOLOv8 model validation provides several key metrics to assess model performance. These include:
- mAP50 (mean Average Precision at IoU threshold 0.5)
- mAP75 (mean Average Precision at IoU threshold 0.75)
- mAP50-95 (mean Average Precision across multiple IoU thresholds from 0.5 to 0.95)
Using the Python API, you can access these metrics as follows:
metrics = model.val() # assumes `model` has been loaded
print(metrics.box.map) # mAP50-95
print(metrics.box.map50) # mAP50
print(metrics.box.map75) # mAP75
print(metrics.box.maps) # list of mAP50-95 for each category
For a complete performance evaluation, it's crucial to review all these metrics. For more details, refer to the Key Features of Val Mode.
What are the advantages of using Ultralytics YOLO for validation?
Using Ultralytics YOLO for validation provides several advantages:
- Precision: YOLOv8 offers accurate performance metrics including mAP50, mAP75, and mAP50-95.
- Convenience: The models remember their training settings, making validation straightforward.
- Flexibility: You can validate against the same or different datasets and image sizes.
- Hyperparameter Tuning: Validation metrics help in fine-tuning models for better performance.
These benefits ensure that your models are evaluated thoroughly and can be optimized for superior results. Learn more about these advantages in the Why Validate with Ultralytics YOLO section.
Can I validate my YOLOv8 model using a custom dataset?
Yes, you can validate your YOLOv8 model using a custom dataset. Specify the data
argument with the path to your dataset configuration file. This file should include paths to the validation data, class names, and other relevant details.
Example in Python:
from ultralytics import YOLO
# Load a model
model = YOLO("yolov8n.pt")
# Validate with a custom dataset
metrics = model.val(data="path/to/your/custom_dataset.yaml")
print(metrics.box.map) # map50-95
Example using CLI:
yolo val model=yolov8n.pt data=path/to/your/custom_dataset.yaml
For more customizable options during validation, see the Example Validation with Arguments section.
How do I save validation results to a JSON file in YOLOv8?
To save the validation results to a JSON file, you can set the save_json
argument to True
when running validation. This can be done in both the Python API and CLI.
Example in Python:
from ultralytics import YOLO
# Load a model
model = YOLO("yolov8n.pt")
# Save validation results to JSON
metrics = model.val(save_json=True)
Example using CLI:
yolo val model=yolov8n.pt save_json=True
This functionality is particularly useful for further analysis or integration with other tools. Check the Arguments for YOLO Model Validation for more details.
comments: true
description: Learn how to install Ultralytics using pip, conda, or Docker. Follow our step-by-step guide for a seamless setup of YOLOv8 with thorough instructions.
keywords: Ultralytics, YOLOv8, Install Ultralytics, pip, conda, Docker, GitHub, machine learning, object detection
Install Ultralytics
Ultralytics provides various installation methods including pip, conda, and Docker. Install YOLOv8 via the ultralytics
pip package for the latest stable release or by cloning the Ultralytics GitHub repository for the most up-to-date version. Docker can be used to execute the package in an isolated container, avoiding local installation.
Watch: Ultralytics YOLO Quick Start Guide
!!! Example "Install"
<p align="left" style="margin-bottom: -20px;">![PyPI - Python Version](https://img.shields.io/pypi/pyversions/ultralytics?logo=python&logoColor=gold)<p>
=== "Pip install (recommended)"
Install the `ultralytics` package using pip, or update an existing installation by running `pip install -U ultralytics`. Visit the Python Package Index (PyPI) for more details on the `ultralytics` package: [https://pypi.org/project/ultralytics/](https://pypi.org/project/ultralytics/).
[![PyPI - Version](https://img.shields.io/pypi/v/ultralytics?logo=pypi&logoColor=white)](https://pypi.org/project/ultralytics/)
[![Downloads](https://static.pepy.tech/badge/ultralytics)](https://pepy.tech/project/ultralytics)
```py
# Install the ultralytics package from PyPI
pip install ultralytics
```
You can also install the `ultralytics` package directly from the GitHub [repository](https://github.com/ultralytics/ultralytics). This might be useful if you want the latest development version. Make sure to have the Git command-line tool installed on your system. The `@main` command installs the `main` branch and may be modified to another branch, i.e. `@my-branch`, or removed entirely to default to `main` branch.
```py
# Install the ultralytics package from GitHub
pip install git+https://github.com/ultralytics/ultralytics.git@main
```
=== "Conda install"
Conda is an alternative package manager to pip which may also be used for installation. Visit Anaconda for more details at [https://anaconda.org/conda-forge/ultralytics](https://anaconda.org/conda-forge/ultralytics). Ultralytics feedstock repository for updating the conda package is at [https://github.com/conda-forge/ultralytics-feedstock/](https://github.com/conda-forge/ultralytics-feedstock/).
[![Conda Version](https://img.shields.io/conda/vn/conda-forge/ultralytics?logo=condaforge)](https://anaconda.org/conda-forge/ultralytics)
[![Conda Downloads](https://img.shields.io/conda/dn/conda-forge/ultralytics.svg)](https://anaconda.org/conda-forge/ultralytics)
[![Conda Recipe](https://img.shields.io/badge/recipe-ultralytics-green.svg)](https://anaconda.org/conda-forge/ultralytics)
[![Conda Platforms](https://img.shields.io/conda/pn/conda-forge/ultralytics.svg)](https://anaconda.org/conda-forge/ultralytics)
```py
# Install the ultralytics package using conda
conda install -c conda-forge ultralytics
```
!!! Note
If you are installing in a CUDA environment best practice is to install `ultralytics`, `pytorch` and `pytorch-cuda` in the same command to allow the conda package manager to resolve any conflicts, or else to install `pytorch-cuda` last to allow it override the CPU-specific `pytorch` package if necessary.
```py
# Install all packages together using conda
conda install -c pytorch -c nvidia -c conda-forge pytorch torchvision pytorch-cuda=11.8 ultralytics
```
### Conda Docker Image
Ultralytics Conda Docker images are also available from [DockerHub](https://hub.docker.com/r/ultralytics/ultralytics). These images are based on [Miniconda3](https://docs.conda.io/projects/miniconda/en/latest/) and are an simple way to start using `ultralytics` in a Conda environment.
```py
# Set image name as a variable
t=ultralytics/ultralytics:latest-conda
# Pull the latest ultralytics image from Docker Hub
sudo docker pull $t
# Run the ultralytics image in a container with GPU support
sudo docker run -it --ipc=host --gpus all $t # all GPUs
sudo docker run -it --ipc=host --gpus '"device=2,3"' $t # specify GPUs
```
=== "Git clone"
Clone the `ultralytics` repository if you are interested in contributing to the development or wish to experiment with the latest source code. After cloning, navigate into the directory and install the package in editable mode `-e` using pip.
[![GitHub last commit](https://img.shields.io/github/last-commit/ultralytics/ultralytics?logo=github)](https://github.com/ultralytics/ultralytics)
[![GitHub commit activity](https://img.shields.io/github/commit-activity/t/ultralytics/ultralytics)](https://github.com/ultralytics/ultralytics)
```py
# Clone the ultralytics repository
git clone https://github.com/ultralytics/ultralytics
# Navigate to the cloned directory
cd ultralytics
# Install the package in editable mode for development
pip install -e .
```
=== "Docker"
Utilize Docker to effortlessly execute the `ultralytics` package in an isolated container, ensuring consistent and smooth performance across various environments. By choosing one of the official `ultralytics` images from [Docker Hub](https://hub.docker.com/r/ultralytics/ultralytics), you not only avoid the complexity of local installation but also benefit from access to a verified working environment. Ultralytics offers 5 main supported Docker images, each designed to provide high compatibility and efficiency for different platforms and use cases:
[![Docker Image Version](https://img.shields.io/docker/v/ultralytics/ultralytics?sort=semver&logo=docker)](https://hub.docker.com/r/ultralytics/ultralytics)
[![Docker Pulls](https://img.shields.io/docker/pulls/ultralytics/ultralytics)](https://hub.docker.com/r/ultralytics/ultralytics)
- **Dockerfile:** GPU image recommended for training.
- **Dockerfile-arm64:** Optimized for ARM64 architecture, allowing deployment on devices like Raspberry Pi and other ARM64-based platforms.
- **Dockerfile-cpu:** Ubuntu-based CPU-only version suitable for inference and environments without GPUs.
- **Dockerfile-jetson:** Tailored for NVIDIA Jetson devices, integrating GPU support optimized for these platforms.
- **Dockerfile-python:** Minimal image with just Python and necessary dependencies, ideal for lightweight applications and development.
- **Dockerfile-conda:** Based on Miniconda3 with conda installation of ultralytics package.
Below are the commands to get the latest image and execute it:
```py
# Set image name as a variable
t=ultralytics/ultralytics:latest
# Pull the latest ultralytics image from Docker Hub
sudo docker pull $t
# Run the ultralytics image in a container with GPU support
sudo docker run -it --ipc=host --gpus all $t # all GPUs
sudo docker run -it --ipc=host --gpus '"device=2,3"' $t # specify GPUs
```
The above command initializes a Docker container with the latest `ultralytics` image. The `-it` flag assigns a pseudo-TTY and maintains stdin open, enabling you to interact with the container. The `--ipc=host` flag sets the IPC (Inter-Process Communication) namespace to the host, which is essential for sharing memory between processes. The `--gpus all` flag enables access to all available GPUs inside the container, which is crucial for tasks that require GPU computation.
Note: To work with files on your local machine within the container, use Docker volumes for mounting a local directory into the container:
```py
# Mount local directory to a directory inside the container
sudo docker run -it --ipc=host --gpus all -v /path/on/host:/path/in/container $t
```
Alter `/path/on/host` with the directory path on your local machine, and `/path/in/container` with the desired path inside the Docker container for accessibility.
For advanced Docker usage, feel free to explore the [Ultralytics Docker Guide](./guides/docker-quickstart.md).
See the ultralytics
pyproject.toml file for a list of dependencies. Note that all examples above install all required dependencies.
!!! Tip "Tip"
PyTorch requirements vary by operating system and CUDA requirements, so it's recommended to install PyTorch first following instructions at [https://pytorch.org/get-started/locally](https://pytorch.org/get-started/locally).
<a href="https://pytorch.org/get-started/locally/">
<img width="800" alt="PyTorch Installation Instructions" src="https://user-images.githubusercontent.com/26833433/228650108-ab0ec98a-b328-4f40-a40d-95355e8a84e3.png">
</a>
Use Ultralytics with CLI
The Ultralytics command line interface (CLI) allows for simple single-line commands without the need for a Python environment. CLI requires no customization or Python code. You can simply run all tasks from the terminal with the yolo
command. Check out the CLI Guide to learn more about using YOLOv8 from the command line.
!!! Example
=== "Syntax"
Ultralytics `yolo` commands use the following syntax:
```py
yolo TASK MODE ARGS
```
- `TASK` (optional) is one of ([detect](tasks/detect.md), [segment](tasks/segment.md), [classify](tasks/classify.md), [pose](tasks/pose.md))
- `MODE` (required) is one of ([train](modes/train.md), [val](modes/val.md), [predict](modes/predict.md), [export](modes/export.md), [track](modes/track.md))
- `ARGS` (optional) are `arg=value` pairs like `imgsz=640` that override defaults.
See all `ARGS` in the full [Configuration Guide](usage/cfg.md) or with the `yolo cfg` CLI command.
=== "Train"
Train a detection model for 10 epochs with an initial learning_rate of 0.01
```py
yolo train data=coco8.yaml model=yolov8n.pt epochs=10 lr0=0.01
```
=== "Predict"
Predict a YouTube video using a pretrained segmentation model at image size 320:
```py
yolo predict model=yolov8n-seg.pt source='https://youtu.be/LNwODJXcvt4' imgsz=320
```
=== "Val"
Val a pretrained detection model at batch-size 1 and image size 640:
```py
yolo val model=yolov8n.pt data=coco8.yaml batch=1 imgsz=640
```
=== "Export"
Export a YOLOv8n classification model to ONNX format at image size 224 by 128 (no TASK required)
```py
yolo export model=yolov8n-cls.pt format=onnx imgsz=224,128
```
=== "Special"
Run special commands to see version, view settings, run checks and more:
```py
yolo help
yolo checks
yolo version
yolo settings
yolo copy-cfg
yolo cfg
```
!!! Warning "Warning"
Arguments must be passed as `arg=val` pairs, split by an equals `=` sign and delimited by spaces between pairs. Do not use `--` argument prefixes or commas `,` between arguments.
- `yolo predict model=yolov8n.pt imgsz=640 conf=0.25` ✅
- `yolo predict model yolov8n.pt imgsz 640 conf 0.25` ❌ (missing `=`)
- `yolo predict model=yolov8n.pt, imgsz=640, conf=0.25` ❌ (do not use `,`)
- `yolo predict --model yolov8n.pt --imgsz 640 --conf 0.25` ❌ (do not use `--`)
Use Ultralytics with Python
YOLOv8's Python interface allows for seamless integration into your Python projects, making it easy to load, run, and process the model's output. Designed with simplicity and ease of use in mind, the Python interface enables users to quickly implement object detection, segmentation, and classification in their projects. This makes YOLOv8's Python interface an invaluable tool for anyone looking to incorporate these functionalities into their Python projects.
For example, users can load a model, train it, evaluate its performance on a validation set, and even export it to ONNX format with just a few lines of code. Check out the Python Guide to learn more about using YOLOv8 within your Python projects.
!!! Example
```py
from ultralytics import YOLO
# Create a new YOLO model from scratch
model = YOLO("yolov8n.yaml")
# Load a pretrained YOLO model (recommended for training)
model = YOLO("yolov8n.pt")
# Train the model using the 'coco8.yaml' dataset for 3 epochs
results = model.train(data="coco8.yaml", epochs=3)
# Evaluate the model's performance on the validation set
results = model.val()
# Perform object detection on an image using the model
results = model("https://ultralytics.com/images/bus.jpg")
# Export the model to ONNX format
success = model.export(format="onnx")
```
Ultralytics Settings
The Ultralytics library provides a powerful settings management system to enable fine-grained control over your experiments. By making use of the SettingsManager
housed within the ultralytics.utils
module, users can readily access and alter their settings. These are stored in a YAML file and can be viewed or modified either directly within the Python environment or via the Command-Line Interface (CLI).
Inspecting Settings
To gain insight into the current configuration of your settings, you can view them directly:
!!! Example "View settings"
=== "Python"
You can use Python to view your settings. Start by importing the `settings` object from the `ultralytics` module. Print and return settings using the following commands:
```py
from ultralytics import settings
# View all settings
print(settings)
# Return a specific setting
value = settings["runs_dir"]
```
=== "CLI"
Alternatively, the command-line interface allows you to check your settings with a simple command:
```py
yolo settings
```
Modifying Settings
Ultralytics allows users to easily modify their settings. Changes can be performed in the following ways:
!!! Example "Update settings"
=== "Python"
Within the Python environment, call the `update` method on the `settings` object to change your settings:
```py
from ultralytics import settings
# Update a setting
settings.update({"runs_dir": "/path/to/runs"})
# Update multiple settings
settings.update({"runs_dir": "/path/to/runs", "tensorboard": False})
# Reset settings to default values
settings.reset()
```
=== "CLI"
If you prefer using the command-line interface, the following commands will allow you to modify your settings:
```py
# Update a setting
yolo settings runs_dir='/path/to/runs'
# Update multiple settings
yolo settings runs_dir='/path/to/runs' tensorboard=False
# Reset settings to default values
yolo settings reset
```
Understanding Settings
The table below provides an overview of the settings available for adjustment within Ultralytics. Each setting is outlined along with an example value, the data type, and a brief description.
Name | Example Value | Data Type | Description |
---|---|---|---|
settings_version |
'0.0.4' |
str |
Ultralytics settings version (different from Ultralytics pip version) |
datasets_dir |
'/path/to/datasets' |
str |
The directory where the datasets are stored |
weights_dir |
'/path/to/weights' |
str |
The directory where the model weights are stored |
runs_dir |
'/path/to/runs' |
str |
The directory where the experiment runs are stored |
uuid |
'a1b2c3d4' |
str |
The unique identifier for the current settings |
sync |
True |
bool |
Whether to sync analytics and crashes to HUB |
api_key |
'' |
str |
Ultralytics HUB API Key |
clearml |
True |
bool |
Whether to use ClearML logging |
comet |
True |
bool |
Whether to use Comet ML for experiment tracking and visualization |
dvc |
True |
bool |
Whether to use DVC for experiment tracking and version control |
hub |
True |
bool |
Whether to use Ultralytics HUB integration |
mlflow |
True |
bool |
Whether to use MLFlow for experiment tracking |
neptune |
True |
bool |
Whether to use Neptune for experiment tracking |
raytune |
True |
bool |
Whether to use Ray Tune for hyperparameter tuning |
tensorboard |
True |
bool |
Whether to use TensorBoard for visualization |
wandb |
True |
bool |
Whether to use Weights & Biases logging |
As you navigate through your projects or experiments, be sure to revisit these settings to ensure that they are optimally configured for your needs.
FAQ
How do I install Ultralytics YOLOv8 using pip?
To install Ultralytics YOLOv8 with pip, execute the following command:
pip install ultralytics
For the latest stable release, this will install the ultralytics
package directly from the Python Package Index (PyPI). For more details, visit the ultralytics package on PyPI.
Alternatively, you can install the latest development version directly from GitHub:
pip install git+https://github.com/ultralytics/ultralytics.git
Make sure to have the Git command-line tool installed on your system.
Can I install Ultralytics YOLOv8 using conda?
Yes, you can install Ultralytics YOLOv8 using conda by running:
conda install -c conda-forge ultralytics
This method is an excellent alternative to pip and ensures compatibility with other packages in your environment. For CUDA environments, it's best to install ultralytics
, pytorch
, and pytorch-cuda
simultaneously to resolve any conflicts:
conda install -c pytorch -c nvidia -c conda-forge pytorch torchvision pytorch-cuda=11.8 ultralytics
For more instructions, visit the Conda quickstart guide.
What are the advantages of using Docker to run Ultralytics YOLOv8?
Using Docker to run Ultralytics YOLOv8 provides an isolated and consistent environment, ensuring smooth performance across different systems. It also eliminates the complexity of local installation. Official Docker images from Ultralytics are available on Docker Hub, with different variants tailored for GPU, CPU, ARM64, NVIDIA Jetson, and Conda environments. Below are the commands to pull and run the latest image:
# Pull the latest ultralytics image from Docker Hub
sudo docker pull ultralytics/ultralytics:latest
# Run the ultralytics image in a container with GPU support
sudo docker run -it --ipc=host --gpus all ultralytics/ultralytics:latest
For more detailed Docker instructions, check out the Docker quickstart guide.
How do I clone the Ultralytics repository for development?
To clone the Ultralytics repository and set up a development environment, use the following steps:
# Clone the ultralytics repository
git clone https://github.com/ultralytics/ultralytics
# Navigate to the cloned directory
cd ultralytics
# Install the package in editable mode for development
pip install -e .
This approach allows you to contribute to the project or experiment with the latest source code. For more details, visit the Ultralytics GitHub repository.
Why should I use Ultralytics YOLOv8 CLI?
The Ultralytics YOLOv8 command line interface (CLI) simplifies running object detection tasks without requiring Python code. You can execute single-line commands for tasks like training, validation, and prediction straight from your terminal. The basic syntax for yolo
commands is:
yolo TASK MODE ARGS
For example, to train a detection model with specified parameters:
yolo train data=coco8.yaml model=yolov8n.pt epochs=10 lr0=0.01
Check out the full CLI Guide to explore more commands and usage examples.