Detecting Objects with Ultralytics YOLO
Everything in the previous lessons (IoU, NMS, box encoding, the one-stage grid, a training loop) is packaged in the Ultralytics library: pretrained YOLO models, one-line inference, training on your own data from a YAML file, evaluation and export. This lesson uses the two pretrained COCO models cached in the course's Docker image, the nano versions of YOLOv8 and YOLO11, on the scikit-image sample photos, and shows what each inference argument does by counting what changes. Then it trains on a tiny generated data set to show the training interface, and explains the parts that are not run here. All examples import ultralytics, so they are recorded: run on a CPU in Docker, output saved.
First predictions and the Results object
YOLO("yolov8n.pt") loads the model; model.predict(source) (or just model(source)) accepts file paths, URLs, PIL images, NumPy arrays and lists of them, and returns one Results object per image. A NumPy array is read as BGR, the OpenCV convention, so the RGB images from scikit-image are flipped first.
import numpy as np
from ultralytics import YOLO
from skimage import data
model = YOLO("yolov8n.pt")
print("classes:", len(model.names), "| first ten:", [model.names[i] for i in range(10)])
for name in ["astronaut", "coffee", "chelsea", "rocket"]:
bgr = getattr(data, name)()[:, :, ::-1].copy()
r = model.predict(bgr, verbose=False)[0] # default conf=0.25, iou=0.7, imgsz=640
print(f"{name}: orig_shape {r.orig_shape}, {len(r.boxes)} boxes")
for xyxy, xywhn, c, s in zip(r.boxes.xyxy.tolist(), r.boxes.xywhn.tolist(), r.boxes.cls.tolist(), r.boxes.conf.tolist()):
print(f" {r.names[int(c)]:12s} conf {s:.2f} xyxy {np.round(xyxy).astype(int).tolist()} xywhn {np.round(xywhn, 3).tolist()}")classes: 80 | first ten: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light']
astronaut: orig_shape (512, 512), 1 boxes
person conf 0.71 xyxy [5, 14, 363, 511] xywhn [0.36, 0.513, 0.7, 0.972]
coffee: orig_shape (400, 600), 2 boxes
cup conf 0.92 xyxy [169, 17, 423, 326] xywhn [0.493, 0.429, 0.424, 0.774]
dining table conf 0.72 xyxy [0, 1, 588, 393] xywhn [0.49, 0.493, 0.979, 0.98]
chelsea: orig_shape (300, 451), 1 boxes
cat conf 0.89 xyxy [2, 0, 431, 295] xywhn [0.481, 0.492, 0.951, 0.985]
rocket: orig_shape (427, 640), 0 boxes
model.names maps the 80 COCO class ids to names, and person is id 0. Each Results holds a boxes object with parallel tensors: xyxy (corners in original pixels), xywh (centre and size), xyxyn / xywhn (normalised by the original width and height: the YOLO label format), conf and cls. orig_shape is (height, width). Other fields hold masks, keypoints or oriented boxes for the segmentation, pose and OBB models, and r.plot() draws the boxes onto a copy of the image (as a BGR array).
The four photos show the range: the astronaut is a person at 0.71, the coffee picture is a cup at 0.92 and a dining table at 0.72 (the table fills the frame), the cat is a cat at 0.89, and the rocket photo gives nothing, because COCO has no rocket class and nothing else in the picture passes 0.25. A detector only knows its training classes.
Letterboxing
The network wants a size divisible by its largest stride (32), and the images have every shape. Ultralytics letterboxes: it scales the image by one factor so that the longer side becomes imgsz, keeps the aspect ratio, and pads the rest with grey (114). At prediction time it pads only up to the next multiple of 32 ("rectangular" inference); training batches are padded to the full square (validation uses rectangular batches, one shape per batch). Boxes come back in original-image pixels by undoing both steps:
with = imgsz and the left and top padding. The resizing lesson has the general geometry. This part needs only NumPy and OpenCV, so it runs in your browser, on a montage of three sample photos scaled to 300 pixels high and put side by side:
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)
def letterbox(img, size=640, stride=32, square=False):
h, w = img.shape[:2]
r = min(size / h, size / w)
nh, nw = round(h * r), round(w * r)
th, tw = (size, size) if square else (int(np.ceil(nh / stride) * stride), int(np.ceil(nw / stride) * stride))
top, left = (th - nh) // 2, (tw - nw) // 2
out = np.full((th, tw, 3), 114, np.uint8)
out[top:top + nh, left:left + nw] = cv2.resize(img, (nw, nh), interpolation=cv2.INTER_LINEAR)
return out, r, (left, top)
tiles = [cv2.resize(im, (round(im.shape[1] * 300 / im.shape[0]), 300), interpolation=cv2.INTER_AREA)
for im in [data.astronaut(), data.chelsea(), data.coffee()]]
montage = np.concatenate(tiles, axis=1)
print("tile widths:", [t.shape[1] for t in tiles], "| montage:", montage.shape)
for square in [False, True]:
lb, r, (px, py) = letterbox(montage, square=square)
pad_share = 1 - round(montage.shape[0] * r) * round(montage.shape[1] * r) / (lb.shape[0] * lb.shape[1])
print(f"{'square' if square else 'rect '} letterbox: {lb.shape}, scale r = {r:.4f}, padding left {px}, top {py}, "
f"padding {pad_share:.0%} of the input")
box_net = np.array([100.0, 40.0, 180.0, 120.0]) # a box in the rect letterboxed image
lb, r, (px, py) = letterbox(montage)
box_orig = (box_net - [px, py, px, py]) / r
print("box in network pixels", box_net.tolist(), "-> original montage pixels", box_orig.round(1).tolist())tile widths: [300, 451, 450] | montage: (300, 1201, 3)
rect letterbox: (160, 640, 3), scale r = 0.5329, padding left 0, top 0, padding 0% of the input
square letterbox: (640, 640, 3), scale r = 0.5329, padding left 0, top 240, padding 75% of the input
box in network pixels [100.0, 40.0, 180.0, 120.0] -> original montage pixels [187.7, 75.1, 337.8, 225.2]
The 300 x 1201 montage is scaled by to 160 x 640, which is already a multiple of 32, so rectangular inference needs no padding at all. Square letterboxing, as in training, would pad 240 rows at the top and the bottom: 75% of the network input would be grey, wasted compute and wasted resolution. A box at [100, 40, 180, 120] in network pixels is [187.7, 75.1, 337.8, 225.2] in the montage. For wide or tall images, the choice of imgsz therefore decides how many pixels each object gets: the montage's objects are shrunk by almost half before the network sees them.
What the arguments do
The arguments you will change most are conf (score threshold, default 0.25), iou (the NMS IoU threshold, default 0.7), imgsz (the letterbox size, default 640), classes (keep only these class ids) and max_det (default 300). The same montage, through YOLOv8n, counting detections as each argument changes:
import numpy as np
import cv2
from ultralytics import YOLO
from ultralytics.data.augment import LetterBox
from skimage import data
tiles = [cv2.resize(im, (round(im.shape[1] * 300 / im.shape[0]), 300), interpolation=cv2.INTER_AREA)
for im in [data.astronaut(), data.chelsea(), data.coffee()]]
montage = np.concatenate(tiles, axis=1)[:, :, ::-1].copy() # BGR for Ultralytics
print("Ultralytics LetterBox, rect:", LetterBox((640, 640), auto=True, stride=32)(image=montage).shape,
"| square:", LetterBox((640, 640), auto=False)(image=montage).shape)
model = YOLO("yolov8n.pt")
def show(r):
return [f"{r.names[int(c)]} {s:.2f}" for c, s in zip(r.boxes.cls.tolist(), r.boxes.conf.tolist())]
r = model.predict(montage, verbose=False)[0]
print("defaults:", show(r))
edges = np.cumsum([t.shape[1] for t in tiles]) # tiles end at x = 300, 751, 1201
for (x1, y1, x2, y2), c in zip(r.boxes.xyxy.round().int().tolist(), r.boxes.cls.tolist()):
tile = ["astronaut", "chelsea", "coffee"][int(np.searchsorted(edges, (x1 + x2) / 2, side="right"))]
print(f" {r.names[int(c)]:12s} [{x1}, {y1}, {x2}, {y2}] in the {tile} tile")
for conf in [0.05, 0.1, 0.25, 0.5]:
print(f"conf {conf}: {len(model.predict(montage, conf=conf, verbose=False)[0].boxes)} boxes")
for iou in [0.3, 0.7, 0.95]:
print(f"iou {iou} (at conf 0.05): {len(model.predict(montage, conf=0.05, iou=iou, verbose=False)[0].boxes)} boxes")
for imgsz in [320, 640, 1280]:
print(f"imgsz {imgsz}:", show(model.predict(montage, imgsz=imgsz, verbose=False)[0]))
print("classes=[0] (person only):", show(model.predict(montage, classes=[0], verbose=False)[0]))Ultralytics LetterBox, rect: (160, 640, 3) | square: (640, 640, 3)
defaults: ['cat 0.91', 'dining table 0.81', 'cup 0.81', 'person 0.73', 'sports ball 0.33']
cat [305, 0, 704, 299] in the chelsea tile
dining table [753, 1, 1199, 299] in the coffee tile
cup [877, 11, 1070, 245] in the coffee tile
person [8, 7, 212, 300] in the astronaut tile
sports ball [162, 201, 291, 299] in the astronaut tile
conf 0.05: 8 boxes
conf 0.1: 6 boxes
conf 0.25: 5 boxes
conf 0.5: 4 boxes
iou 0.3 (at conf 0.05): 7 boxes
iou 0.7 (at conf 0.05): 8 boxes
iou 0.95 (at conf 0.05): 20 boxes
imgsz 320: ['cat 0.78', 'cup 0.69', 'dining table 0.55', 'person 0.44', 'cup 0.33']
imgsz 640: ['cat 0.91', 'dining table 0.81', 'cup 0.81', 'person 0.73', 'sports ball 0.33']
imgsz 1280: ['cup 0.92', 'cat 0.90', 'dining table 0.84', 'person 0.83']
classes=[0] (person only): ['person 0.73']
Ultralytics' own LetterBox gives the same shapes as the browser version. With the defaults the montage gives five boxes, four of them right (cat, dining table, cup, person) and one false positive: a sports ball at 0.33 on the astronaut tile, where the helmet she holds looks like a ball at this size. The arguments behave as the earlier lessons predict:
confonly filters: 8 boxes at 0.05, 5 at 0.25, 4 at 0.5, where the sports ball is gone. For evaluation use a low value (Ultralytics'valuses 0.001); for an application, choose it on validation data.iouis the NMS threshold: 7 boxes at 0.3, 8 at 0.7, and 20 at 0.95, where NMS removes almost nothing and the duplicates come back (NMS).imgszchanges what the network sees. At 320 the objects are a quarter of the size: scores drop (person 0.44) and a second, wrongcupappears. At 1280 the montage is upscaled, all four real objects score 0.83 or more and the sports ball disappears. Larger is not always better (it is four times slower than 640 and the model was trained at 640), but for small objects it often is.classes=[0]keeps onlyperson: the filter is applied inside NMS, so it is cheaper than filtering afterwards.
YOLOv8n against YOLO11n
YOLO11 (2024) is the successor in the same library: a reworked backbone and neck (C3k2 blocks, a spatial attention block), the same anchor-free decoupled head. Same images, same settings:
import numpy as np
import cv2
from ultralytics import YOLO
from skimage import data
tiles = [cv2.resize(im, (round(im.shape[1] * 300 / im.shape[0]), 300), interpolation=cv2.INTER_AREA)
for im in [data.astronaut(), data.chelsea(), data.coffee()]]
images = {name: getattr(data, name)()[:, :, ::-1].copy() for name in ["astronaut", "coffee", "chelsea"]}
images["montage"] = np.concatenate(tiles, axis=1)[:, :, ::-1].copy()
for weights in ["yolov8n.pt", "yolo11n.pt"]:
model = YOLO(weights)
print(f"{weights}: {sum(p.numel() for p in model.model.parameters()):,} parameters")
for name, img in images.items():
r = model.predict(img, verbose=False)[0]
print(f" {name:9s}", [f"{r.names[int(c)]} {s:.2f}" for c, s in zip(r.boxes.cls.tolist(), r.boxes.conf.tolist())])yolov8n.pt: 3,157,200 parameters
astronaut ['person 0.71']
coffee ['cup 0.92', 'dining table 0.72']
chelsea ['cat 0.89']
montage ['cat 0.91', 'dining table 0.81', 'cup 0.81', 'person 0.73', 'sports ball 0.33']
yolo11n.pt: 2,624,080 parameters
astronaut ['person 0.90', 'sports ball 0.68']
coffee ['cup 0.82', 'dining table 0.78', 'spoon 0.29']
chelsea ['cat 0.85']
montage ['cup 0.90', 'cat 0.84', 'person 0.81', 'dining table 0.64']
YOLO11n has 17% fewer parameters (2.62 against 3.16 million) and Ultralytics reports a higher COCO mAP for it (39.5 against 37.3 mAP50-95 on COCO val2017 in its published model tables). On these four images it is more confident about the astronaut (0.90) and the montage person (0.81), but it also produces two new errors: the same sports ball false positive on the full-size astronaut, now at 0.68, and a spoon at 0.29 on the coffee picture. Four images cannot rank two detectors; that needs a labelled validation set and AP. What the comparison does show is that a newer model changes which mistakes you get, so rerun your own evaluation before swapping models in an application.
Training on your own data
A data set for Ultralytics is a folder of images and a parallel folder of label files, one .txt per image with one line class cx cy w h per object, normalised to 0 to 1 (box formats), plus a YAML file that names the folders and the classes. An image without objects gets an empty .txt. This example writes 128 generated training scenes and 32 validation scenes (the course's make_scene) in that layout, fine-tunes the COCO-pretrained YOLOv8n for three epochs at imgsz=64 on the CPU, and validates. YOLO_VERBOSE=False and plots=False keep the log and the plot files out of the way; the MLflow logger, which is installed in this image, is switched off in the settings.
import os
os.environ["YOLO_VERBOSE"] = "False"
import tempfile
import numpy as np
from ultralytics import YOLO, settings
import numpy as np, cv2
CLASSES = ["square", "circle", "triangle"]
def make_scene(rng, size=64, max_objects=3):
"""Noisy grey background with 1..max_objects shapes that do not touch.
Returns RGB uint8 image, boxes (n, 4) as [x1, y1, x2, y2] with x2, y2 exclusive,
labels (n,) indices into CLASSES, masks (n, size, size) bool."""
img = rng.normal(110, 12, (size, size, 3)).clip(0, 255).astype(np.uint8)
n = int(rng.integers(1, max_objects + 1))
boxes, labels, masks = [], [], []
for _ in range(100):
if len(boxes) == n:
break
s = int(rng.integers(12, 25)); x = int(rng.integers(0, size - s)); y = int(rng.integers(0, size - s))
if any(x < b[2] + 2 and b[0] < x + s + 2 and y < b[3] + 2 and b[1] < y + s + 2 for b in boxes):
continue
c = int(rng.integers(0, 3)); m = np.zeros((size, size), np.uint8)
if c == 0:
cv2.rectangle(m, (x, y), (x + s - 1, y + s - 1), 1, -1)
elif c == 1:
cv2.circle(m, (x + s // 2, y + s // 2), s // 2, 1, -1)
else:
cv2.fillPoly(m, [np.array([[x + s // 2, y], [x, y + s - 1], [x + s - 1, y + s - 1]], np.int32)], 1)
img[m > 0] = rng.integers(0, 256, 3)
ys, xs = np.nonzero(m)
boxes.append([int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1])
labels.append(c); masks.append(m > 0)
return img, np.array(boxes).reshape(-1, 4), np.array(labels), np.array(masks)
settings.update({"mlflow": False})
root = tempfile.mkdtemp()
rng = np.random.default_rng(0)
for split, n in [("train", 128), ("val", 32)]:
os.makedirs(f"{root}/images/{split}"); os.makedirs(f"{root}/labels/{split}")
for i in range(n):
img, boxes, labels, _ = make_scene(rng)
cv2.imwrite(f"{root}/images/{split}/{i:04d}.png", img[:, :, ::-1]) # files are written as BGR
with open(f"{root}/labels/{split}/{i:04d}.txt", "w") as f:
for (x1, y1, x2, y2), l in zip(boxes, labels):
f.write(f"{l} {(x1 + x2) / 128:.6f} {(y1 + y2) / 128:.6f} {(x2 - x1) / 64:.6f} {(y2 - y1) / 64:.6f}\n")
with open(f"{root}/shapes.yaml", "w") as f:
f.write(f"path: {root}\ntrain: images/train\nval: images/val\nnames:\n 0: square\n 1: circle\n 2: triangle\n")
print(open(f"{root}/labels/train/0001.txt").read().strip())
model = YOLO("yolov8n.pt")
model.train(data=f"{root}/shapes.yaml", epochs=3, imgsz=64, batch=16, workers=0, device="cpu", seed=0,
deterministic=True, plots=False, amp=False, project=root, name="run", exist_ok=True)
print("classes now:", model.names)
m = model.val(data=f"{root}/shapes.yaml", imgsz=64, batch=16, device="cpu", plots=False)
print(f"validation (32 scenes): precision {m.box.mp:.3f} recall {m.box.mr:.3f} mAP50 {m.box.map50:.3f} mAP50-95 {m.box.map:.3f}")
print("files written:", sorted(os.listdir(f"{root}/run/weights")))1 0.539062 0.117188 0.203125 0.203125
0 0.875000 0.234375 0.218750 0.218750
classes now: {0: 'square', 1: 'circle', 2: 'triangle'}
validation (32 scenes): precision 0.599 recall 0.866 mAP50 0.895 mAP50-95 0.656
files written: ['best.pt', 'last.pt']
The label lines show the format: scene 1's circle [28, 1, 41, 14] becomes class 1 at centre with size . After training, the model's class names are the three shapes, and train saved best.pt and last.pt under run/weights/. Three epochs on 128 scenes, starting from COCO weights, already give mAP50 0.895 and mAP50-95 0.656 on the 32 validation scenes (Ultralytics' own validator: COCO-style AP, low confidence threshold); precision 0.599 and recall 0.866 are reported at the confidence that maximises F1. These numbers are from 32 scenes and three epochs: a smoke test of the pipeline, not a result. A real run uses hundreds of images per class, a separate test set and tens to hundreds of epochs (fine-tuning recipe).
The same workflow as files and commands, as you would use it on a real project (not run here: it needs a real data set and, for a reasonable time, a GPU):
# data.yaml: paths relative to "path"; one label .txt per image under labels/ with the same name
path: /data/helmets
train: images/train
val: images/val
test: images/test
names:
0: helmet
1: head# Not run here: needs a real data set and a GPU for a useful training run.
from ultralytics import YOLO
model = YOLO("yolo11n.pt") # start from COCO weights
model.train(data="data.yaml", epochs=100, imgsz=640, batch=16, patience=20) # early stopping after 20 flat epochs
metrics = model.val(split="test") # report the test split once, at the end
print(metrics.box.map50, metrics.box.map)
model.export(format="onnx", imgsz=640) # also "engine" (TensorRT), "openvino", "coreml", "tflite"The command-line interface does the same: yolo detect train data=data.yaml model=yolo11n.pt epochs=100 imgsz=640, yolo detect predict model=best.pt source=video.mp4.
COCO classes: what the pretrained model knows
The pretrained weights know exactly the 80 COCO classes, and their definitions come from COCO's annotation guidelines:
- No class means no detection. There is no rocket, face, helmet, licence plate, crack or product SKU. For those you fine-tune on your own labels.
- Broad classes.
personcovers every person, any pose, size or clothing; it does not distinguish workers from visitors or children from adults.car,truckandbusare split by COCO's labellers' judgement, and vans fall in between. - Ids. Ultralytics numbers the 80 classes 0 to 79. The original COCO annotation files use category ids from 1 to 90 with gaps (91 categories were defined, 80 used), so converting between the two needs a lookup table, not an offset (box formats).
- Licences. The Ultralytics code and its pretrained weights are released under AGPL-3.0, with a commercial licence for closed-source use; check before shipping a product. COCO's images come from Flickr under various Creative Commons licences (licensing).
Pitfalls
- RGB arrays passed as BGR. NumPy arrays are read as BGR; an RGB array swaps red and blue, which quietly lowers scores (orange becomes blue).
- Evaluating at the default
conf=0.25. Usemodel.val(it uses 0.001) or your own AP with a low threshold; 0.25 is a display setting. - Trusting four images. As the YOLOv8n against YOLO11n comparison showed, single images show different mistakes, not which model is better.
- Wrong label normalisation. YOLO labels are normalised by the image's own width and height, centre format. Corners or pixel values in the
.txtgive silent garbage; plot a few labels before training. - Letterbox in your own pre-processing. If you run an exported ONNX model yourself, you must letterbox, scale to 0 to 1, convert to RGB and undo the padding on the outputs exactly as above.
- Training-set leaks. Frames of one video, or photos of one object, in both train and val inflate mAP (split strategies).
Practice
- A 1080 x 1920 video frame is predicted at
imgsz=640. What is , the letterboxed input size, and how many pixels tall is a person who is 90 pixels tall in the frame when the network sees them?
Answer
. The frame becomes 360 x 640, padded to 384 x 640 (next multiple of 32). The person is 30 pixels tall, small for a nano model; imgsz=1280 would give 60 pixels.
- In the argument sweep, why did
iou=0.95give 20 boxes butiou=0.3only 7?
Answer
iou is the NMS threshold: a box is removed only if it overlaps a better box by more than it. At 0.95 almost no duplicate overlaps that much, so neighbouring predictions on the same object all survive. At 0.3 boxes are removed generously, which can also remove a real neighbouring object.
- You need to detect hard hats on a building site. What can the pretrained COCO model do, and what do you need?
Answer
It finds person boxes, which can be used to crop heads, but it has no helmet class. Collect and label images from the sites (helmet and head classes), with consent and privacy rules for the workers, write a data YAML, fine-tune from yolo11n.pt or a larger model, and evaluate AP on a test set from sites not used for training.
Test yourself
What does conf change in model.predict?
- The NMS IoU threshold
- The minimum score a box needs to be returned
- The input size
- The number of classes
Why did the rocket photo give no detection?
- The image is too large
- COCO has no rocket class and nothing else in it passed the 0.25 threshold
- The image is grey
- NMS removed the rocket
A 300 x 1201 image is predicted at imgsz 640 with rectangular letterboxing. What input shape does the network see?
- 640 x 640
- 160 x 640
- 300 x 1201
- 320 x 1280
Which file format holds YOLO training labels?
- One JSON file for the whole set with [x, y, w, h] in pixels
- One .txt per image, one line
class cx cy w hnormalised to 0..1 - XML per image with corners
- A CSV of corners in pixels