2023-05-01 20:20:05 +00:00
---
comments: true
2024-06-02 19:39:34 +00:00
description: Learn to integrate YOLOv8 in Python for object detection, segmentation, and classification. Load, train models, and make predictions easily with our comprehensive guide.
keywords: YOLOv8, Python, object detection, segmentation, classification, machine learning, AI, pretrained models, train models, make predictions
2023-05-01 20:20:05 +00:00
---
2023-03-29 20:56:52 +00:00
# Python Usage
2023-10-09 18:08:39 +00:00
Welcome to the YOLOv8 Python Usage documentation! This guide is designed to help you seamlessly integrate YOLOv8 into your Python projects for object detection, segmentation, and classification. Here, you'll learn how to load and use pretrained models, train new models, and perform predictions on images. The easy-to-use Python interface is a valuable resource for anyone looking to incorporate YOLOv8 into their Python projects, allowing you to quickly implement advanced object detection capabilities. Let's get started!
2023-03-29 20:56:52 +00:00
2023-12-10 15:38:46 +00:00
< p align = "center" >
< br >
2024-02-03 22:24:20 +00:00
< iframe loading = "lazy" width = "720" height = "405" src = "https://www.youtube.com/embed/GsXGnb-A4Kc?start=58"
2023-12-10 15:38:46 +00:00
title="YouTube video player" frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen>
< / iframe >
< br >
< strong > Watch:< / strong > Mastering Ultralytics YOLOv8: Python
< / p >
2023-10-09 18:08:39 +00:00
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.
2023-03-29 20:56:52 +00:00
2023-11-18 20:51:47 +00:00
!!! Example "Python"
2023-03-29 20:56:52 +00:00
```python
from ultralytics import YOLO
2023-07-23 14:03:34 +00:00
2023-03-29 20:56:52 +00:00
# Create a new YOLO model from scratch
2024-05-18 16:58:06 +00:00
model = YOLO("yolov8n.yaml")
2023-07-23 14:03:34 +00:00
2023-03-29 20:56:52 +00:00
# Load a pretrained YOLO model (recommended for training)
2024-05-18 16:58:06 +00:00
model = YOLO("yolov8n.pt")
2023-07-23 14:03:34 +00:00
2024-04-19 03:47:21 +00:00
# Train the model using the 'coco8.yaml' dataset for 3 epochs
2024-05-18 16:58:06 +00:00
results = model.train(data="coco8.yaml", epochs=3)
2023-07-23 14:03:34 +00:00
2023-03-29 20:56:52 +00:00
# Evaluate the model's performance on the validation set
results = model.val()
2023-07-23 14:03:34 +00:00
2023-03-29 20:56:52 +00:00
# Perform object detection on an image using the model
2024-05-18 16:58:06 +00:00
results = model("https://ultralytics.com/images/bus.jpg")
2023-07-23 14:03:34 +00:00
2023-03-29 20:56:52 +00:00
# Export the model to ONNX format
2024-05-18 16:58:06 +00:00
success = model.export(format="onnx")
2023-03-29 20:56:52 +00:00
```
## [Train](../modes/train.md)
2023-10-09 18:08:39 +00:00
Train mode is used for training a YOLOv8 model on a custom dataset. In this mode, the model is trained using the specified dataset and hyperparameters. The training process involves optimizing the model's parameters so that it can accurately predict the classes and locations of objects in an image.
2023-01-12 16:09:26 +00:00
2023-11-18 20:51:47 +00:00
!!! Example "Train"
2023-01-12 16:09:26 +00:00
2023-02-17 21:26:40 +00:00
=== "From pretrained(recommended)"
2024-01-15 22:37:37 +00:00
2023-01-12 16:09:26 +00:00
```python
from ultralytics import YOLO
2024-05-18 16:58:06 +00:00
model = YOLO("yolov8n.pt") # pass any model type
2023-08-09 22:55:36 +00:00
results = model.train(epochs=5)
2023-01-12 16:09:26 +00:00
```
=== "From scratch"
2024-01-15 22:37:37 +00:00
2023-01-12 16:09:26 +00:00
```python
from ultralytics import YOLO
2024-05-18 16:58:06 +00:00
model = YOLO("yolov8n.yaml")
results = model.train(data="coco8.yaml", epochs=5)
2023-01-12 16:09:26 +00:00
```
=== "Resume"
2024-01-15 22:37:37 +00:00
2023-01-12 16:09:26 +00:00
```python
2023-02-07 21:33:25 +00:00
model = YOLO("last.pt")
2023-08-09 22:55:36 +00:00
results = model.train(resume=True)
2023-01-12 16:09:26 +00:00
```
2023-11-25 16:59:01 +00:00
[Train Examples ](../modes/train.md ){ .md-button }
2023-03-29 20:56:52 +00:00
## [Val](../modes/val.md)
2023-10-09 18:08:39 +00:00
Val mode is used for validating a YOLOv8 model after it has been trained. In this mode, the model is evaluated on a validation set to measure its accuracy and generalization performance. This mode can be used to tune the hyperparameters of the model to improve its performance.
2023-03-29 20:56:52 +00:00
2023-11-18 20:51:47 +00:00
!!! Example "Val"
2023-01-12 16:09:26 +00:00
=== "Val after training"
2024-01-15 22:37:37 +00:00
2023-01-12 16:09:26 +00:00
```python
2024-05-19 17:13:04 +00:00
from ultralytics import YOLO
# Load a YOLOv8 model
model = YOLO("yolov8n.yaml")
2023-01-12 16:09:26 +00:00
2024-05-19 17:13:04 +00:00
# Train the model
model.train(data="coco8.yaml", epochs=5)
# Validate on training data
model.val()
2023-01-12 16:09:26 +00:00
```
2024-05-19 17:13:04 +00:00
=== "Val on another dataset"
2024-01-15 22:37:37 +00:00
2023-01-12 16:09:26 +00:00
```python
2024-05-19 17:13:04 +00:00
from ultralytics import YOLO
2023-01-12 16:09:26 +00:00
2024-05-19 17:13:04 +00:00
# Load a YOLOv8 model
model = YOLO("yolov8n.yaml")
# Train the model
model.train(data="coco8.yaml", epochs=5)
# Validate on separate data
model.val(data="path/to/separate/data.yaml")
2023-01-12 16:09:26 +00:00
```
2023-11-25 16:59:01 +00:00
[Val Examples ](../modes/val.md ){ .md-button }
2023-03-29 20:56:52 +00:00
## [Predict](../modes/predict.md)
2023-10-09 18:08:39 +00:00
Predict mode is used for making predictions using a trained YOLOv8 model on new images or videos. In this mode, the model is loaded from a checkpoint file, and the user can provide images or videos to perform inference. The model predicts the classes and locations of objects in the input images or videos.
2023-03-29 20:56:52 +00:00
2023-11-18 20:51:47 +00:00
!!! Example "Predict"
2023-01-12 16:09:26 +00:00
=== "From source"
2024-01-15 22:37:37 +00:00
2023-01-12 16:09:26 +00:00
```python
2023-01-17 13:32:34 +00:00
import cv2
2024-05-18 16:58:06 +00:00
from PIL import Image
2024-06-10 00:33:07 +00:00
2024-05-18 16:58:06 +00:00
from ultralytics import YOLO
2023-01-12 16:09:26 +00:00
model = YOLO("model.pt")
2023-01-17 13:32:34 +00:00
# accepts all formats - image/dir/Path/URL/video/PIL/ndarray. 0 for webcam
results = model.predict(source="0")
2024-05-18 16:58:06 +00:00
results = model.predict(source="folder", show=True) # Display preds. Accepts all YOLO predict arguments
2023-01-12 16:09:26 +00:00
2023-01-17 13:32:34 +00:00
# from PIL
im1 = Image.open("bus.jpg")
results = model.predict(source=im1, save=True) # save plotted images
2023-01-12 16:09:26 +00:00
2023-01-17 13:32:34 +00:00
# from ndarray
im2 = cv2.imread("bus.jpg")
results = model.predict(source=im2, save=True, save_txt=True) # save predictions as labels
2023-01-12 16:09:26 +00:00
2023-01-17 13:32:34 +00:00
# from list of PIL/ndarray
results = model.predict(source=[im1, im2])
```
2023-01-12 16:09:26 +00:00
2023-01-17 13:32:34 +00:00
=== "Results usage"
2024-01-15 22:37:37 +00:00
2023-01-12 16:09:26 +00:00
```python
2023-01-17 13:32:34 +00:00
# results would be a list of Results object including all the predictions by default
2023-07-23 14:03:34 +00:00
# but be careful as it could occupy a lot memory when there're many images,
2023-01-17 13:32:34 +00:00
# especially the task is segmentation.
# 1. return as a list
results = model.predict(source="folder")
# results would be a generator which is more friendly to memory by setting stream=True
# 2. return as a generator
results = model.predict(source=0, stream=True)
for result in results:
2023-04-13 18:19:42 +00:00
# Detection
2024-05-18 16:58:06 +00:00
result.boxes.xyxy # box with xyxy format, (N, 4)
result.boxes.xywh # box with xywh format, (N, 4)
2023-01-17 13:32:34 +00:00
result.boxes.xyxyn # box with xyxy format but normalized, (N, 4)
result.boxes.xywhn # box with xywh format but normalized, (N, 4)
2024-05-18 16:58:06 +00:00
result.boxes.conf # confidence score, (N, 1)
result.boxes.cls # cls, (N, 1)
2023-01-17 13:32:34 +00:00
2023-04-13 18:19:42 +00:00
# Segmentation
2024-05-18 16:58:06 +00:00
result.masks.data # masks, (N, H, W)
result.masks.xy # x,y segments (pixels), List[segment] * N
result.masks.xyn # x,y segments (normalized), List[segment] * N
2023-01-17 13:32:34 +00:00
2023-04-13 18:19:42 +00:00
# Classification
2024-05-18 16:58:06 +00:00
result.probs # cls prob, (num_class, )
2023-01-17 13:32:34 +00:00
2023-07-23 14:03:34 +00:00
# Each result is composed of torch.Tensor by default,
2023-01-17 13:32:34 +00:00
# in which you can easily use following functionality:
result = result.cuda()
result = result.cpu()
result = result.to("cpu")
result = result.numpy()
2023-01-12 16:09:26 +00:00
```
2023-11-25 16:59:01 +00:00
[Predict Examples ](../modes/predict.md ){ .md-button }
2023-03-29 20:56:52 +00:00
## [Export](../modes/export.md)
2023-10-09 18:08:39 +00:00
Export mode is used for exporting a YOLOv8 model to a format that can be used for deployment. In this mode, the model is converted to a format that can be used by other software applications or hardware devices. This mode is useful when deploying the model to production environments.
2023-01-12 16:09:26 +00:00
2023-11-18 20:51:47 +00:00
!!! Example "Export"
2023-03-29 20:56:52 +00:00
=== "Export to ONNX"
Export an official YOLOv8n model to ONNX with dynamic batch-size and image-size.
2023-01-12 16:09:26 +00:00
```python
2024-05-19 17:13:04 +00:00
from ultralytics import YOLO
2023-01-12 16:09:26 +00:00
2024-05-19 17:13:04 +00:00
model = YOLO("yolov8n.pt")
model.export(format="onnx", dynamic=True)
2023-03-29 20:56:52 +00:00
```
=== "Export to TensorRT"
2023-01-12 16:09:26 +00:00
2023-03-29 20:56:52 +00:00
Export an official YOLOv8n model to TensorRT on `device=0` for acceleration on CUDA devices.
```python
2024-05-19 17:13:04 +00:00
from ultralytics import YOLO
2023-03-29 20:56:52 +00:00
2024-05-19 17:13:04 +00:00
model = YOLO("yolov8n.pt")
model.export(format="onnx", device=0)
2023-03-29 20:56:52 +00:00
```
2023-11-25 16:59:01 +00:00
[Export Examples ](../modes/export.md ){ .md-button }
2023-03-29 20:56:52 +00:00
## [Track](../modes/track.md)
2023-10-09 18:08:39 +00:00
Track mode is used for tracking objects in real-time using a YOLOv8 model. In this mode, the model is loaded from a checkpoint file, and the user can provide a live video stream to perform real-time object tracking. This mode is useful for applications such as surveillance systems or self-driving cars.
2023-03-29 20:56:52 +00:00
2023-11-18 20:51:47 +00:00
!!! Example "Track"
2023-03-29 20:56:52 +00:00
=== "Python"
2023-07-23 14:03:34 +00:00
2023-03-29 20:56:52 +00:00
```python
from ultralytics import YOLO
2023-07-23 14:03:34 +00:00
2023-03-29 20:56:52 +00:00
# Load a model
2024-05-18 16:58:06 +00:00
model = YOLO("yolov8n.pt") # load an official detection model
model = YOLO("yolov8n-seg.pt") # load an official segmentation model
model = YOLO("path/to/best.pt") # load a custom model
2023-07-23 14:03:34 +00:00
2023-03-29 20:56:52 +00:00
# Track with the model
2023-09-10 02:58:24 +00:00
results = model.track(source="https://youtu.be/LNwODJXcvt4", show=True)
results = model.track(source="https://youtu.be/LNwODJXcvt4", show=True, tracker="bytetrack.yaml")
2023-01-12 16:09:26 +00:00
```
2023-11-25 16:59:01 +00:00
[Track Examples ](../modes/track.md ){ .md-button }
2023-01-12 16:09:26 +00:00
2023-03-29 20:56:52 +00:00
## [Benchmark](../modes/benchmark.md)
2023-01-12 16:09:26 +00:00
2024-01-07 16:13:42 +00:00
Benchmark mode is used to profile the speed and accuracy of various export formats for YOLOv8. The benchmarks provide information on the size of the exported format, its `mAP50-95` metrics (for object detection and segmentation) or `accuracy_top5` metrics (for classification), and the inference time in milliseconds per image across various export formats like ONNX, OpenVINO, TensorRT and others. This information can help users choose the optimal export format for their specific use case based on their requirements for speed and accuracy.
2023-01-12 16:09:26 +00:00
2023-11-18 20:51:47 +00:00
!!! Example "Benchmark"
2023-03-29 20:56:52 +00:00
=== "Python"
2023-07-23 14:03:34 +00:00
2023-03-29 20:56:52 +00:00
Benchmark an official YOLOv8n model across all export formats.
```python
2023-07-16 15:47:45 +00:00
from ultralytics.utils.benchmarks import benchmark
2023-07-23 14:03:34 +00:00
2023-03-29 20:56:52 +00:00
# Benchmark
2024-05-18 16:58:06 +00:00
benchmark(model="yolov8n.pt", data="coco8.yaml", imgsz=640, half=False, device=0)
2023-03-29 20:56:52 +00:00
```
2023-01-12 16:09:26 +00:00
2023-11-25 16:59:01 +00:00
[Benchmark Examples ](../modes/benchmark.md ){ .md-button }
2023-01-12 16:09:26 +00:00
2024-01-09 22:50:26 +00:00
## Explorer
2024-03-03 00:59:43 +00:00
Explorer API can be used to explore datasets with advanced semantic, vector-similarity and SQL search among other features. It also enabled searching for images based on their content using natural language by utilizing the power of LLMs. The Explorer API allows you to write your own dataset exploration notebooks or scripts to get insights into your datasets.
2024-01-09 22:50:26 +00:00
!!! Example "Semantic Search Using Explorer"
=== "Using Images"
```python
from ultralytics import Explorer
# create an Explorer object
2024-05-18 16:58:06 +00:00
exp = Explorer(data="coco8.yaml", model="yolov8n.pt")
2024-01-09 22:50:26 +00:00
exp.create_embeddings_table()
2024-05-18 16:58:06 +00:00
similar = exp.get_similar(img="https://ultralytics.com/images/bus.jpg", limit=10)
2024-01-09 22:50:26 +00:00
print(similar.head())
# Search using multiple indices
similar = exp.get_similar(
2024-05-18 16:58:06 +00:00
img=["https://ultralytics.com/images/bus.jpg", "https://ultralytics.com/images/bus.jpg"], limit=10
)
2024-01-09 22:50:26 +00:00
print(similar.head())
```
=== "Using Dataset Indices"
```python
from ultralytics import Explorer
# create an Explorer object
2024-05-18 16:58:06 +00:00
exp = Explorer(data="coco8.yaml", model="yolov8n.pt")
2024-01-09 22:50:26 +00:00
exp.create_embeddings_table()
similar = exp.get_similar(idx=1, limit=10)
print(similar.head())
# Search using multiple indices
2024-05-18 16:58:06 +00:00
similar = exp.get_similar(idx=[1, 10], limit=10)
2024-01-09 22:50:26 +00:00
print(similar.head())
```
[Explorer ](../datasets/explorer/index.md ){ .md-button }
2023-03-29 20:56:52 +00:00
## Using Trainers
2023-01-12 16:09:26 +00:00
2023-10-09 18:08:39 +00:00
`YOLO` model class is a high-level wrapper on the Trainer classes. Each YOLO task has its own trainer that inherits from `BaseTrainer` .
2023-01-12 16:09:26 +00:00
2023-11-18 20:51:47 +00:00
!!! Tip "Detection Trainer Example"
2023-01-12 16:09:26 +00:00
```python
2024-05-18 16:58:06 +00:00
from ultralytics.models.yolo import DetectionPredictor, DetectionTrainer, DetectionValidator
2023-01-12 16:09:26 +00:00
# trainer
trainer = DetectionTrainer(overrides={})
trainer.train()
trained_model = trainer.best
# Validator
val = DetectionValidator(args=...)
val(model=trained_model)
# predictor
pred = DetectionPredictor(overrides={})
pred(source=SOURCE, model=trained_model)
# resume from last weight
overrides["resume"] = trainer.last
trainer = detect.DetectionTrainer(overrides=overrides)
```
2023-10-09 18:08:39 +00:00
You can easily customize Trainers to support custom tasks or explore R& D ideas. Learn more about Customizing `Trainers` , `Validators` and `Predictors` to suit your project needs in the Customization Section.
2023-01-12 16:09:26 +00:00
2023-11-25 16:59:01 +00:00
[Customization tutorials ](engine.md ){ .md-button }