Sub topic 8
Running a pretrained YOLO model
This chapter shows how to run a pretrained YOLO detector on an image and read its output. It also covers the two thresholds that shape the result and the mistakes people make most often. It assumes you know basic Python, can picture an image as an array of pixels, and have read the earlier chapters on box formats, intersection over union (IoU) and non-maximum suppression (NMS).
What "pretrained" means here
A pretrained model is a set of weights already trained on a large labeled dataset. The standard YOLOv8 checkpoints from Ultralytics were trained on COCO, which has 80 everyday classes such as person, bus, dog and traffic light. You can use them as they are, or later fine-tune them on your own data.
The checkpoints come in several sizes. Larger models are usually more accurate and slower.
| Checkpoint | Relative size | Typical use |
|---|---|---|
| `yolov8n.pt` | Smallest | Quick tests, CPU, edge devices |
| `yolov8s.pt` | Small | Balanced speed and accuracy |
| `yolov8m.pt` | Medium | Accuracy matters more than speed |
| `yolov8l.pt` / `yolov8x.pt` | Largest | GPU servers, offline batch jobs |
If a checkpoint is not on disk, the library downloads it the first time you name it.
What happens during one prediction
A call to predict runs a fixed pipeline. Knowing the stages tells you where each setting acts.
- Load and letterbox. The image is resized so its longer side matches
imgsz(default 640). It is padded with gray to keep its aspect ratio, so objects are not stretched. - Forward pass. The network produces a large grid of candidate boxes, each with class scores.
- Confidence filter. Candidates whose best class score is below
confare dropped. - NMS. Overlapping boxes of the same class are merged using the
iouthreshold. - Rescale. The surviving boxes are mapped back to the coordinates of your original image.
Step 5 matters. The boxes you read back are in the pixel coordinates of the file you passed in, not the 640-pixel padded input.
Your first prediction
Install the package with pip install ultralytics. Place a test image such as bus.jpg in the working directory. Then run the following.
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
results = model.predict("bus.jpg", conf=0.25, iou=0.7)
for r in results:
for box in r.boxes:
cls_id = int(box.cls[0])
score = float(box.conf[0])
x1, y1, x2, y2 = box.xyxy[0].tolist()
print(model.names[cls_id], round(score, 2), [round(v) for v in (x1, y1, x2, y2)])Each line of output has the class name, the confidence score and the box as [x1, y1, x2, y2] in pixels. For a street photo you might see lines such as person 0.87 [48, 398, 245, 902]. The exact numbers depend on the image and model.
Why there is an outer loop
predict always returns a list with one Results object per input image. With a single image the list has one item, but the loop keeps your code correct when you later pass a folder or a list of paths.
Reading the Results object
Each Results object holds the original image and a boxes collection. Every element of boxes exposes the same detection in several forms.
| Attribute | Contents |
|---|---|
| `box.xyxy` | Corner format in pixels: x1, y1, x2, y2 |
| `box.xywh` | Center x, center y, width, height in pixels |
| `box.xyxyn` | Corner format normalized to 0–1 |
| `box.xywhn` | Center format normalized to 0–1 (same as the YOLO label format) |
| `box.conf` | Confidence score |
| `box.cls` | Class index, stored as a float |
Each attribute is a tensor with a leading dimension of one, which is why the code indexes [0]. Call .tolist() to get plain Python numbers. Use model.names, a dictionary from index to name, to turn cls into a label.
You can also collect everything at once:
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
r = model.predict("bus.jpg", conf=0.25, verbose=False)[0]
detections = [
{
"label": r.names[int(c)],
"score": float(s),
"xyxy": [float(v) for v in b],
}
for b, s, c in zip(r.boxes.xyxy.tolist(), r.boxes.conf.tolist(), r.boxes.cls.tolist())
]
print(len(detections), "objects found")
counts = {}
for d in detections:
counts[d["label"]] = counts.get(d["label"], 0) + 1
print(counts)Here r.boxes.xyxy is the whole set of boxes as one tensor, so you can iterate over it directly. A dictionary of plain values is also easier to save as JSON or pass to other code than tensors are.
The two thresholds
Two arguments control which detections survive. They act at different stages and fail in different ways.
conf(default 0.25) is the minimum score. Raising it removes uncertain detections. You get fewer false positives and more missed objects.iou(default 0.7) is the NMS overlap limit. Two boxes of the same class that overlap more than this are treated as duplicates, and only the higher-scoring one is kept.
The iou setting is easy to misread. A lower value is stricter about overlap, so it removes more boxes. A higher value keeps more boxes. In a crowded scene, where real objects overlap, a low iou may delete correct detections. In a sparse scene with duplicate boxes on single objects, a lower iou cleans them up.
A quick experiment makes the effect visible. Run the same image at several confidence values and count the results:
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
for conf in (0.1, 0.25, 0.5, 0.75):
r = model.predict("bus.jpg", conf=conf, verbose=False)[0]
print(f"conf={conf}: {len(r.boxes)} detections")The count falls as conf rises. Compare which objects disappear first. They are usually small, distant or partly hidden.
Other useful arguments
imgsz: input size. Larger values help with small objects and cost time. Use a multiple of 32.classes: a list of class indices to keep, for exampleclasses=[0]for people only.max_det: the cap on detections per image (default 300).device:"cpu",0for the first GPU, and so on. By default the library picks a GPU if one is available.save=True: writes an annotated copy of the image underruns/detect/.
You can pass many kinds of source. A path, a URL, a folder, a list of paths, a NumPy array or a PIL image all work. Be careful with NumPy arrays. OpenCV loads images in BGR channel order, and the library expects BGR for NumPy input, so pass the array as OpenCV returns it. Converting it to RGB first swaps red and blue and lowers accuracy without raising an error.
For video or a long folder, set stream=True. The call then returns a generator instead of a list, so results are produced one at a time and memory stays flat.
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
for r in model.predict("videos/street.mp4", stream=True, conf=0.4, verbose=False):
people = sum(1 for c in r.boxes.cls.tolist() if int(c) == 0)
print("people in frame:", people)Common mistakes
- Mixing up coordinate formats.
xyxyandxywhhave the same four-number shape. Drawing anxywhbox as if it werexyxyproduces boxes that are too small and shifted. Check which attribute you read. - Assuming normalized values.
xyxyis in pixels. Usexyxynif you want fractions of the image. - Forgetting
int()on the class.box.clsis a float tensor, somodel.names[box.cls[0]]fails or misbehaves. Convert it first. - Expecting classes outside COCO. A pretrained COCO model cannot find a "forklift" or a specific product. It will miss the object or label it as the nearest class. That is the signal to fine-tune on your own data.
- Judging quality from one image. One good result says little. Measure on a labeled set, as the metrics chapter shows.
- Reusing one threshold everywhere. The default
conf=0.25suits demos. A safety alert may need a lower value to avoid misses, and an automated count may need a higher one to avoid false alarms.
Checking your understanding
Exercise
You run a pretrained model on a photo of a crowded market. Two real people standing shoulder to shoulder produce heavily overlapping boxes, and only one of them is reported. Which argument would you adjust, in which direction, and what risk does the change add?
Show answer
Raise the NMS iou threshold, for example from 0.7 to 0.85. A higher value treats only very highly overlapping boxes as duplicates, so the second person's box survives. The risk is that true duplicate boxes on a single object are also kept more often, which adds repeated detections.
Exercise
The code model.names[box.cls[0]] raises an error. Write the corrected expression and explain the cause.
Show answer
Use model.names[int(box.cls[0])]. The cls value is a float tensor element, while model.names is a dictionary keyed by integer class index, so the value must be converted to an int before the lookup.
Exercise
You loaded an image with OpenCV and call model.predict(img). A colleague suggests converting it to RGB first with cv2.cvtColor. Is that correct?
Show answer
No. For NumPy array input the library expects the BGR order that OpenCV returns. Converting to RGB swaps the red and blue channels, which lowers accuracy without raising an error.