The YOLOv8 Python API lets you load, train, validate, predict, track, and export Ultralytics YOLO models directly from Python. Instead of running everything through terminal commands, you can import the YOLO class from the ultralytics package and integrate YOLOv8 into scripts, notebooks, web applications, automation pipelines, or larger computer vision systems. Ultralytics officially supports Python workflows for training, validation, prediction, tracking, and model export.
A basic YOLOv8 Python workflow looks like:
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
results = model.predict("image.jpg")
The same model object can later be used for training, validation, tracking, or export without switching to a separate interface.
Introduction to the YOLOv8 Python API
YOLOv8 can be used through both the Ultralytics command-line interface and its Python package. The CLI is convenient for quickly starting standard operations, but Python gives developers significantly more control over how YOLO is integrated into an application.
For example, you can load a model once and then process images programmatically:
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
results = model("image.jpg")
You can then inspect individual detections, extract coordinates, read confidence scores, apply custom business logic, store results in a database, draw your own visualizations, or send detections to another part of an application.
The Python API therefore becomes especially useful when YOLOv8 is only one component of a larger computer vision workflow.
What Is the YOLOv8 Python API?
The YOLOv8 Python API is the programmatic interface exposed through the Ultralytics Python package.
Its main entry point is:
from ultralytics import YOLO
After importing YOLO, you can create a model object from a pretrained checkpoint, custom checkpoint, exported model, or architecture configuration.
For example:
model = YOLO("yolov8n.pt")
The resulting object can perform multiple modes such as:
train
val
predict
track
export
Ultralytics documents these modes as part of the same Python API.
Role of the Ultralytics Python Package
The ultralytics package provides the code required to:
- load YOLO models,
- preprocess input sources,
- execute inference,
- train custom models,
- calculate validation metrics,
- run multi-object tracking,
- export models,
- access structured prediction results.
Instead of manually building PyTorch preprocessing and post-processing code for every operation, the package provides standardized methods.
For example:
model.train(...)
model.val(...)
model.predict(...)
model.track(...)
model.export(...)
This makes it possible to use the same model object across an entire project.
Python API vs YOLO Command Line Interface
The CLI and Python API expose many of the same underlying capabilities, but they are designed for different workflows.
CLI example:
yolo detect predict model=yolov8n.pt source=image.jpg
Python equivalent:
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
results = model.predict(source="image.jpg")
The CLI is useful when you want:
quick experiments
simple training commands
one-time predictions
shell automation
The Python API is better when you need:
custom processing logic
loops
condition-based behavior
database integration
application development
result extraction
custom visualizations
Ultralytics describes the CLI as a straightforward no-code-style terminal interface, while the Python API provides programmatic access to the same modes.
How to Install YOLOv8 for Python
The easiest way to use YOLOv8 in Python is to install the official Ultralytics package.
A normal installation requires Python and pip.
Install the Ultralytics Package
Run:
pip install ultralytics
If the package is already installed, it can be upgraded with:
pip install -U ultralytics
After installation, the package provides the YOLO Python interface and the yolo command-line program.
For GPU acceleration, the underlying PyTorch installation must also support the installed CUDA environment.
Import YOLO in a Python Script
Create a Python file such as:
detect.py
Then add:
from ultralytics import YOLO
You can immediately create a model:
model = YOLO("yolov8n.pt")
If the checkpoint is not already available locally, supported pretrained checkpoints can normally be resolved by Ultralytics.
Verify the Installation
A simple test is:
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
print(model)
You can also run a prediction:
results = model("image.jpg")
print(results)
If the package imports correctly and the model loads, the Python setup is working.
How to Load a YOLOv8 Model in Python
The YOLO constructor can load different model sources depending on whether you want inference, transfer learning, continued training, or a fresh architecture.
Typical options include:
pretrained .pt model
custom best.pt checkpoint
architecture .yaml
exported deployment model
Load a Pretrained YOLOv8 Model
For object detection:
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
Other YOLOv8 detection sizes include:
yolov8s.pt
yolov8m.pt
yolov8l.pt
yolov8x.pt
Ultralytics’ YOLOv8 documentation shows checkpoint-based loading for training and prediction workflows.
A pretrained model is useful for immediate inference or transfer learning.
Load Custom-Trained Weights
After custom training, a checkpoint may be saved as:
runs/detect/train/weights/best.pt
Load it with:
from ultralytics import YOLO
model = YOLO("runs/detect/train/weights/best.pt")
You can then predict:
results = model("test.jpg")
or validate:
metrics = model.val(data="data.yaml")
This is the normal workflow for deploying a custom YOLOv8 detector.
Load a Model from a YAML Configuration
A model can also be constructed from an architecture YAML:
from ultralytics import YOLO
model = YOLO("yolov8n.yaml")
This creates the architecture without simply loading the standard pretrained .pt checkpoint.
You can then train it:
model.train(
data="data.yaml",
epochs=100
)
This approach is useful for scratch training or architecture customization.
Run YOLOv8 Predictions with the Python API
Prediction mode supports multiple source types, including images, videos, streams, folders, and other supported inputs. Ultralytics’ Predict mode returns structured Results objects rather than only saving visual output.
The general syntax is:
results = model.predict(source=...)
or simply:
results = model(source)
Predict Objects in an Image
Example:
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
results = model.predict(
source="image.jpg",
conf=0.25
)
You can also use:
results = model("image.jpg")
The returned object contains detections for the processed input.
For multiple images:
results = model.predict(
source=[
"image1.jpg",
"image2.jpg"
]
)
Run Inference on Videos
Video inference uses the same API:
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
results = model.predict(
source="video.mp4"
)
For long videos or streams, using streaming results can reduce memory usage:
results = model.predict(
source="video.mp4",
stream=True
)
for result in results:
print(result.boxes)
Predict mode officially supports new images and video sources.
Use Webcam and Live Stream Sources
A local webcam can commonly be passed using its device index:
results = model.predict(
source=0,
stream=True
)
for result in results:
print(result.boxes)
For network streams, supported stream URLs can be passed as the source.
For example:
results = model.predict(
source="rtsp://camera-stream",
stream=True
)
The actual inference rate depends on the model, input resolution, device, and video source.
Access YOLOv8 Prediction Results in Python
One major advantage of the Python API is structured access to prediction results.
Ultralytics returns a Results object containing task-dependent attributes such as:
boxes
masks
keypoints
probs
obb
The result API also exposes class information, bounding-box coordinates, and confidence values for detection tasks.
Access Bounding Boxes
For detection:
results = model("image.jpg")
result = results[0]
boxes = result.boxes
Bounding-box coordinates can be accessed in different formats.
For example:
xyxy = result.boxes.xyxy
This provides:
x1
y1
x2
y2
coordinates.
Normalized coordinates are also available through corresponding result properties.
You can inspect detections individually:
for box in result.boxes:
print(box.xyxy)
Access Class IDs and Confidence Scores
Class IDs:
classes = result.boxes.cls
Confidence values:
confidences = result.boxes.conf
For example:
for box in result.boxes:
class_id = int(box.cls[0])
confidence = float(box.conf[0])
coordinates = box.xyxy[0]
print(class_id, confidence, coordinates)
You can map IDs to names using:
print(result.names)
Ultralytics’ results API includes class and confidence information as part of detection results.
Access Segmentation Masks and Keypoints
For segmentation:
model = YOLO("yolov8n-seg.pt")
results = model("image.jpg")
result = results[0]
masks = result.masks
Useful mask properties include polygon and normalized polygon representations when available.
Ultralytics segmentation results include masks together with class labels and confidence information.
For pose estimation:
model = YOLO("yolov8n-pose.pt")
results = model("image.jpg")
keypoints = results[0].keypoints
Pose results represent detected keypoint locations and can also contain confidence information.
Train YOLOv8 Using the Python API
YOLOv8 training can be started directly from Python through:
model.train()
This makes it easier to build training into scripts or experimental pipelines without repeatedly constructing CLI commands. Ultralytics documents Train mode as part of the standard Python interface.
Train on a Custom Dataset
Example:
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
model.train(
data="data.yaml",
epochs=100
)
The YAML file describes the training and validation paths and class names.
For example:
path: /datasets/custom
train: images/train
val: images/val
names:
0: person
1: vehicle
Configure Epochs, Batch Size, and Image Size
A more complete training example is:
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
model.train(
data="data.yaml",
epochs=100,
batch=16,
imgsz=640,
device=0
)
Common settings include:
epochs
batch
imgsz
device
optimizer
lr0
patience
workers
Ultralytics Train mode exposes these as configurable arguments.
Use Pretrained Weights for Training
For transfer learning:
model = YOLO("yolov8n.pt")
then:
model.train(
data="data.yaml",
epochs=100
)
This starts training from learned weights rather than random initialization.
For many custom datasets, this approach converges faster and requires less data than scratch training.
Validate a YOLOv8 Model in Python
Validation is performed with:
model.val()
The method returns a metrics object that can be inspected programmatically. Ultralytics officially documents this workflow for trained detection models.
Run Model Validation
Example:
from ultralytics import YOLO
model = YOLO("best.pt")
metrics = model.val(
data="data.yaml"
)
You can specify additional settings:
metrics = model.val(
data="data.yaml",
imgsz=640,
batch=16,
device=0
)
Access Precision, Recall, and mAP
For detection, mAP values can be read from:
print(metrics.box.map)
which represents mAP50-95.
You can also access:
print(metrics.box.map50)
print(metrics.box.map75)
Ultralytics’ detection documentation explicitly exposes these metrics through the validation result object.
Additional precision and recall information can also be accessed from the detection metrics structures.
Evaluate a Custom-Trained Model
Load:
model = YOLO("runs/detect/train/weights/best.pt")
then:
metrics = model.val(
data="data.yaml"
)
This allows you to compare multiple checkpoints using the same validation dataset.
For reliable comparisons, keep:
data
imgsz
validation settings
consistent between models.
YOLOv8 Python API for Different Tasks
YOLOv8 is not limited to standard bounding-box detection. The YOLOv8 family includes pretrained variants for detection, segmentation, classification, pose estimation, and oriented bounding boxes. Ultralytics’ official YOLOv8 page lists these supported tasks.
The Python programming pattern remains similar:
model = YOLO("model.pt")
results = model("input.jpg")
The main difference is the type of output stored in the Results object.
Object Detection
Load:
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
results = model("image.jpg")
Access:
results[0].boxes
Detection outputs contain bounding boxes, class IDs, and confidence values.
Instance Segmentation
Load:
model = YOLO("yolov8n-seg.pt")
Predict:
results = model("image.jpg")
Access masks:
masks = results[0].masks
Segmentation outputs include object masks alongside detection information.
Pose Estimation
Load:
model = YOLO("yolov8n-pose.pt")
Predict:
results = model("person.jpg")
Access:
keypoints = results[0].keypoints
Pose estimation returns keypoint structures associated with detected objects.
Image Classification
For classification:
model = YOLO("yolov8n-cls.pt")
results = model("image.jpg")
Classification results use probability information rather than detection bounding boxes.
For example:
probs = results[0].probs
Ultralytics supports classification through the same train, val, predict, and export workflow.
Oriented Bounding Box Detection
For rotated objects:
model = YOLO("yolov8n-obb.pt")
results = model("aerial.jpg")
Access oriented boxes:
obb = results[0].obb
OBB is useful for objects where rotation matters, such as ships, aerial vehicles, and rotated objects in remote-sensing imagery.
Track Objects with the YOLOv8 Python API
Ultralytics provides Track mode for maintaining object identities across video frames.
Tracking combines detections with a tracker that associates objects over time. Instead of seeing a new anonymous car on every frame, the tracker attempts to maintain an ID such as:
Car ID 7
across consecutive frames.
Ultralytics supports multi-object tracking through model.track().
Run Multi-Object Tracking
Example:
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
results = model.track(
source="video.mp4",
persist=True
)
For streaming processing:
results = model.track(
source="video.mp4",
stream=True,
persist=True
)
for result in results:
print(result.boxes)
Tracking performance depends on the detector, tracker configuration, frame rate, scene conditions, and hardware.
Access Tracking IDs
When tracking IDs are available, they can be accessed from the boxes result.
For example:
for result in results:
if result.boxes.id is not None:
track_ids = result.boxes.id.int().cpu().tolist()
print(track_ids)
You can combine IDs with:
boxes = result.boxes.xyxy
classes = result.boxes.cls
confidences = result.boxes.conf
This allows you to build custom counting, trajectory, or analytics systems.
Use BoT-SORT and ByteTrack
Ultralytics Track mode supports configurable tracker YAML files.
The documented tracker options include BoT-SORT and ByteTrack, with BoT-SORT currently documented as the default tracker in the tracking dataset/configuration guidance.
BoT-SORT example:
results = model.track(
source="video.mp4",
tracker="botsort.yaml"
)
ByteTrack:
results = model.track(
source="video.mp4",
tracker="bytetrack.yaml"
)
Tracker availability can evolve across Ultralytics versions, so use the tracker configurations installed with your current package.
Export YOLOv8 Models Using Python
The Python API can export trained models for deployment in environments that do not use the original PyTorch checkpoint.
Use:
model.export()
Ultralytics supports multiple export targets such as ONNX, TensorRT, CoreML, and others.
Export to ONNX
Example:
from ultralytics import YOLO
model = YOLO("best.pt")
model.export(
format="onnx"
)
ONNX is useful for interoperability with various inference runtimes.
Additional export options can be passed depending on the target environment.
Export to TensorRT
For NVIDIA TensorRT:
model.export(
format="engine"
)
Ultralytics uses the engine format name for TensorRT export. The exact environment requirements depend on the NVIDIA GPU, CUDA, TensorRT version, and platform.
TensorRT can be useful when optimized NVIDIA GPU inference is required.
Export to Other Deployment Formats
Ultralytics Export mode supports additional deployment targets, which can include formats such as:
ONNX
TensorRT
OpenVINO
CoreML
TFLite
TorchScript
depending on the model, platform, and current Ultralytics version.
The basic pattern remains:
model.export(
format="FORMAT_NAME"
)
Choose the target format according to the deployment hardware and runtime.
Common YOLOv8 Python API Errors
Most Python API problems are caused by file paths, device configuration, unsupported sources, or incompatible package environments rather than the YOLO model itself.
Check the complete traceback before changing code because the error message often identifies the failing component.
Model File Not Found
Example:
model = YOLO("best.pt")
may fail if best.pt is not in the current working directory.
Use the correct path:
model = YOLO(
"runs/detect/train/weights/best.pt"
)
You can verify the path with Python:
from pathlib import Path
print(Path("best.pt").exists())
If it prints:
False
the path is incorrect.
CUDA and GPU Errors
GPU errors can include:
CUDA unavailable
out of memory
driver mismatch
PyTorch CUDA mismatch
You can explicitly use CPU:
results = model.predict(
source="image.jpg",
device="cpu"
)
or GPU:
results = model.predict(
source="image.jpg",
device=0
)
For out-of-memory training problems, reduce:
batch
imgsz
model size
Incorrect Input Source
A prediction can fail if the source does not exist or is not in a supported form.
For example:
model("missing.jpg")
will fail because the source cannot be opened.
Check:
from pathlib import Path
source = Path("image.jpg")
print(source.exists())
For streams, verify that the camera or network source is actually accessible.
Dependency and Version Issues
Ultralytics evolves over time, so old examples may use behavior that has changed.
Check the installed package:
pip show ultralytics
Upgrade when appropriate:
pip install -U ultralytics
Also verify compatible versions of:
Python
PyTorch
CUDA
GPU drivers
Avoid mixing random package versions when troubleshooting CUDA issues.
FAQs About the YOLOv8 Python API
How do I use YOLOv8 in Python?
Install Ultralytics:
pip install ultralytics
Then:
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
results = model("image.jpg")
Ultralytics officially supports prediction, training, validation, tracking, and export through its Python interface.
How do I load a YOLOv8 model in Python?
For a pretrained model:
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
For custom weights:
model = YOLO("best.pt")
For an architecture:
model = YOLO("yolov8n.yaml")
The appropriate source depends on whether you want pretrained inference, custom deployment, or fresh training.
How do I train YOLOv8 using Python?
Load the model:
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
Then:
model.train(
data="data.yaml",
epochs=100,
imgsz=640,
batch=16
)
Ultralytics exposes Train mode directly through the Python API.
How do I access YOLOv8 detection results in Python?
Run prediction:
results = model("image.jpg")
result = results[0]
Then access:
result.boxes.xyxy
result.boxes.cls
result.boxes.conf
For other tasks:
result.masks
result.keypoints
result.obb
result.probs
depending on the model type. The Results API is designed to expose these structured prediction outputs.
Can YOLOv8 process videos with the Python API?
Yes.
For example:
results = model.predict(
source="video.mp4",
stream=True
)
for result in results:
print(result.boxes)
Predict mode supports images, videos, and stream-oriented inputs.
Can I use custom-trained YOLOv8 weights in Python?
Yes.
Load:
model = YOLO(
"runs/detect/train/weights/best.pt"
)
Then use the model normally:
model.predict("image.jpg")
model.val(data="data.yaml")
model.export(format="onnx")
Custom checkpoints use the same high-level Python interface as pretrained checkpoints.
What is the difference between the YOLOv8 Python API and CLI?
The CLI executes operations directly from the terminal:
yolo detect predict model=yolov8n.pt source=image.jpg
The Python API uses code:
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
results = model("image.jpg")
The CLI is convenient for quick commands.
Python is more suitable for:
applications
custom logic
result processing
automation
tracking systems
database integration
API development
Both interfaces expose the main Ultralytics YOLO workflows.
Conclusion
The YOLOv8 Python API provides a flexible way to use Ultralytics YOLO directly inside Python applications. The main interface begins with:
from ultralytics import YOLO
and a model can be loaded with:
model = YOLO("yolov8n.pt")
From there, the same model object can perform the core workflow:
Load Model
↓
Predict
↓
Access Results
↓
Train
↓
Validate
↓
Track
↓
Export
The most important Python methods are:
model.predict()
model.train()
model.val()
model.track()
model.export()
Ultralytics documents all of these as standard model modes available through its Python interface.
For prediction results, YOLOv8 provides structured objects rather than only rendered images. Depending on the model task, you can access:
result.boxes
result.masks
result.keypoints
result.probs
result.obb
This makes the Python API especially useful for custom applications where predictions need to be analyzed, transformed, stored, tracked, or passed to another system.
A complete detection example is:
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
results = model.predict(
source="image.jpg",
conf=0.25
)
for result in results:
for box in result.boxes:
class_id = int(box.cls[0])
confidence = float(box.conf[0])
coordinates = box.xyxy[0]
print(
class_id,
confidence,
coordinates
)
For custom training:
model.train(
data="data.yaml",
epochs=100,
imgsz=640,
batch=16
)
For validation:
metrics = model.val(
data="data.yaml"
)
print(metrics.box.map)
print(metrics.box.map50)
For tracking:
results = model.track(
source="video.mp4",
tracker="botsort.yaml",
persist=True
)
And for export:
model.export(
format="onnx"
)
The CLI is excellent for quick experiments, but the Python API becomes the better option when YOLOv8 needs to be integrated into a larger software system. It gives direct access to detections, class IDs, confidence scores, masks, keypoints, tracking IDs, metrics, and exported models while keeping the workflow inside normal Python code.
I’m Jane Austen, a skilled content writer with the ability to simplify any complex topic. I focus on delivering valuable tips and strategies throughout my articles.