Skip to content
HUIAHUB

TutorialImage & video

Ultralytics YOLO object detection: predict, train and export a custom model

Run Ultralytics YOLO object detection from Python or the CLI, train on your own labeled images and export to ONNX, after checking the AGPL-3.0 licence terms.

Edited by Published 6 min read13 sources

Ultralytics YOLO object detection takes three commands: pip install ultralytics, yolo predict with a pretrained YOLO26 model, and yolo train on your own labeled dataset. Exporting the result to ONNX is one more command. Decide on the licence first: the package and its models are AGPL-3.0, and Ultralytics sells an Enterprise licence for closed-source and commercial use.

What YOLO object detection models do

Object detection finds where objects are in an image or video frame and what they are. The Ultralytics detect docs describe the output as a set of bounding boxes, each with a class label and a confidence score. Detection fits when you need to locate objects but not trace their exact outline; segmentation covers that case.

The ultralytics Python package (version 8.4.172 on PyPI at the time of writing) runs the current YOLO26 family and older models back to YOLOv3. Besides detection it handles instance and semantic segmentation, depth estimation, classification, pose estimation, oriented boxes and tracking. The Ultralytics README (opens in a new tab) says YOLO27 is in preview, with no models released and no launch date.

The pretrained YOLO26 detection models are trained on COCO's 80 classes and come in five sizes. These figures are from the README, measured by Ultralytics at 640 pixels:

ModelParameters (M)mAP 50-95 (COCO val)CPU ONNX (ms)T4 TensorRT (ms)
YOLO26n2.440.938.91.7
YOLO26s9.548.687.22.5
YOLO26m20.453.1220.04.7
YOLO26l24.855.0286.26.2
YOLO26x55.757.5525.811.8

Smaller models are faster and less accurate. Pretrained weights download automatically the first time you name them.

Licence: AGPL-3.0 or the Ultralytics Enterprise licence

Settle this before you write code, because it decides whether you can ship. Ultralytics offers two licences, according to its README:

  • AGPL-3.0, an OSI-approved open-source licence, which the README aims at students, researchers and enthusiasts.
  • The Ultralytics Enterprise licence, for business products and services, internal tools and production deployments, which removes the AGPL-3.0 open-source requirements.

The Ultralytics licensing page goes further. It says AGPL-3.0 use means publicly releasing the full source of the derivative work, including the larger application and, where applicable, model weights. It also says trained Ultralytics YOLO models fall under AGPL-3.0 by default, and it lists SaaS platforms, proprietary software and embedded devices as cases for the Enterprise licence. Pricing is not published on the pages reviewed here.

Use this table as a starting point, then read the licence and ask a lawyer:

Your projectLicence Ultralytics points to
Research, coursework or a personal project you can publish in fullAGPL-3.0
An open-source application released under AGPL-compatible terms, with its weightsAGPL-3.0
A closed-source product, mobile app or device firmwareEnterprise
A hosted API or SaaS feature that runs YOLO on the serverEnterprise
An internal company tool you will not open-sourceEnterprise

Install the ultralytics package

The Ultralytics quickstart (opens in a new tab) lists Python 3.8 or newer and PyTorch 1.8 or newer:

pip install -U ultralytics

Conda (conda install -c conda-forge ultralytics), Docker images and a source install are also documented. For a specific PyTorch build, such as a CUDA or ROCm version, install PyTorch first and ultralytics second. On servers without a display, the quickstart suggests pip install ultralytics-opencv-headless to avoid libGL errors.

Run predictions from the CLI and Python

Predict from the command line

yolo predict model=yolo26n.pt source='https://ultralytics.com/images/bus.jpg'

The yolo command takes a mode (train, val, predict, export, track or benchmark) and arg=value pairs. The task is read from the model file. Annotated results go to runs/detect/predict on a first run. The source argument accepts an image, video, folder, URL or stream, and source=0 reads from a webcam.

Predict from Python

from ultralytics import YOLO

model = YOLO("yolo26n.pt")
results = model("https://ultralytics.com/images/bus.jpg")

for result in results:
    boxes = result.boxes.xyxy          # pixel corners: x1, y1, x2, y2
    confs = result.boxes.conf          # confidence per box
    names = [result.names[c.item()] for c in result.boxes.cls.int()]

A call returns a list of Results objects, one per image. For long videos or live streams, the predict docs recommend stream=True, which returns a generator and keeps only the current frame's results in memory. The default confidence threshold for prediction is 0.25, set by conf.

Train YOLO on a custom dataset

Training starts from pretrained weights, which the train docs recommend over building a model from scratch.

Step 1: label images in YOLO format

Each image gets a .txt file with the same name, one row per object:

0 0.481 0.634 0.690 0.713
2 0.127 0.402 0.088 0.150

The row format is class x_center y_center width height. Coordinates are normalized from 0 to 1: divide x and width by the image width, y and height by the image height. Class IDs start at 0. Images with no objects need no label file. The rows above are illustrative.

Step 2: lay out the folders and write a dataset YAML

Follow the layout of the COCO8 sample dataset: images/train, images/val, labels/train and labels/val under one root. Then describe it in a YAML file. This template uses illustrative class names:

# my-dataset.yaml
path: datasets/my-dataset   # dataset root
train: images/train         # relative to path
val: images/val
test:                       # optional
names:
  0: helmet
  1: person
  2: forklift

The train, val and test keys also accept a list of folders or a .txt file with one image path per line.

Step 3: train

yolo detect train data=my-dataset.yaml model=yolo26n.pt epochs=100 imgsz=640

The Python equivalent is YOLO("yolo26n.pt").train(data="my-dataset.yaml", epochs=100, imgsz=640). The train mode docs (opens in a new tab) list the defaults: 100 epochs, batch size 16, image size 640, and early stopping (patience) after 100 epochs without validation improvement. Without a device argument, training uses GPU 0 if one is available and the CPU otherwise.

A few options worth knowing:

  • batch=-1 picks a batch size that uses about 60% of GPU memory. If the first epoch runs out of memory on a single GPU, the trainer halves the batch and retries up to three times.
  • device=0,1 trains on two GPUs, device=mps on Apple silicon and device=-1 on the most idle GPU. The docs say multi-GPU training does not work on Windows with official PyTorch wheels from 2.4 on; use Linux or WSL2.
  • On Windows, wrap training code in an if __name__ == "__main__": block to avoid a RuntimeError.
  • yolo train resume model=path/to/last.pt resumes an interrupted run. Checkpoints are saved at the end of each epoch.

To check the pipeline before training on real data, run the same command with data=coco8.yaml. COCO8 is an 8-image sample (4 train, 4 val) that downloads automatically.

Export to ONNX and other formats

The export mode docs (opens in a new tab) show one command for an official or custom model:

yolo export model=path/to/best.pt format=onnx

In Python, model.export(format="onnx") returns the path of the exported file. After a first training run, the best weights are at runs/detect/train/weights/best.pt, the path the export docs use in their examples. You can run prediction directly on the exported file, for example yolo predict model=best.onnx.

Common format values:

TargetformatOutput
ONNXonnx.onnx file
TensorRTengine.engine file
OpenVINOopenvino_openvino_model/ folder
CoreMLcoreml.mlpackage
LiteRTlitert.tflite file
NCNNncnn_ncnn_model/ folder
TorchScript (default)torchscript.torchscript file

Useful ONNX arguments include imgsz, dynamic=True for variable input sizes, simplify (on by default), opset and batch (default 1). Precision is set with quantize: 16 for FP16 or 8 for INT8. INT8 needs calibration data passed with data, for example data=my-dataset.yaml. The older half=True and int8=True flags still work but print deprecation warnings.

Most export formats need extra packages. Ultralytics installs missing ones at export time; set YOLO_AUTOINSTALL=False to stop that in containers or CI, and export will fail with a list of what is missing instead.

The README says Ultralytics measured its CPU speed figures with ONNX exports and its GPU figures with TensorRT exports.

Frequently asked questions

Which YOLO26 size should I start with?

Start with YOLO26n for a first run, since it has 2.4M parameters and the shortest CPU time in Ultralytics' table. Move to s or m if accuracy on your validation set is too low. Train each candidate on the same data and compare validation mAP rather than relying on COCO numbers.

How many labeled images do I need to train a custom detector?

The Ultralytics docs pages reviewed here do not give a minimum. COCO8 has only 8 images, but it exists to test the pipeline, not to produce a usable model. Start with what you have, check validation metrics, and add labeled images for the classes that score worst.

Can I train Ultralytics YOLO without an NVIDIA GPU?

Yes. Training falls back to the CPU when no GPU is found, and the train docs cover Apple silicon (`device=mps`), AMD GPUs through a ROCm build of PyTorch, Intel GPUs (`device=xpu:0`) and Huawei Ascend NPUs.

Does exporting to ONNX change the AGPL-3.0 licence of my model?

Ultralytics' licensing page says trained YOLO models fall under AGPL-3.0 by default, and it lists closed-source software and embedded devices as Enterprise cases without an exception for exported formats. An ONNX file produced by the export command is still a trained Ultralytics model. Check the licence text with a lawyer before shipping one in a closed product.

Do I have to remove non-maximum suppression myself after export?

By default (`nms=None`), exports return raw predictions for external NMS. Setting `nms=True` embeds NMS in formats that support it, and `nms=False` selects the NMS-free head where the model has one, which YOLO26 does according to the export arguments.

Sources

  1. 1.GitHub - ultralytics/ultralytics: Ultralytics YOLO27, YOLO26, YOLO11, YOLOv8 — object detection, instance segmentation, semantic segmentation, image classification, pose estimation, object tracking ·RepositoryPrimarygithub.com
  2. 2.Install UltralyticsOfficial docsPrimarydocs.ultralytics.com
  3. 3.Model Training with Ultralytics YOLOOfficial docsPrimarydocs.ultralytics.com
  4. 4.Model Export with Ultralytics YOLOOfficial docsPrimarydocs.ultralytics.com
  5. 5.pypi.org/project/ultralyticsWeb
  6. 6.ultralytics.com/licenseWeb
  7. 7.docs.ultralytics.com/tasks/detectOfficial docsPrimary
  8. 8.docs.ultralytics.com/modes/predictOfficial docsPrimary
  9. 9.github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/default.yamlRepositoryPrimary
  10. 10.docs.ultralytics.com/datasets/detectOfficial docsPrimary
  11. 11.docs.ultralytics.com/datasets/detect/coco8Official docsPrimary
  12. 12.github.com/ultralytics/ultralytics/tree/main/docs/macrosRepositoryPrimary

Spotted an error? See our corrections policy.

Enjoyed this? Get the weekly brief.

New guides, Project & Tool of the Week and the AI developments that matter. One email, no spam.

Read next