Sub topic 8
Running a Pretrained YOLO Model
This chapter assumes you know basic Python, image pixels, neural networks, and the idea of a bounding box. It also assumes that you know a detector returns a box, a class, and a score for each possible object.
A pretrained model has already learned from a labeled dataset. You can use it to detect common objects without training it yourself. This is useful for testing an idea quickly or creating a baseline before fine-tuning on custom data.
Install and load the model
Install the Ultralytics package in your Python environment:
pip install ultralyticsLoad a small YOLO model with Python:
from ultralytics import YOLO
model = YOLO("yolov8n.pt")The n means nano. It is small and fast, but usually less accurate than larger variants such as s, m, l, and x. On the first run, Ultralytics downloads the weight file if it is not already available.
A forward pass sends an image through the network and produces raw predictions. The library then decodes those predictions and applies filtering and non-maximum suppression.
Run inference and read detections
The predict method accepts an image path. The conf argument sets the minimum confidence score. The iou argument sets the overlap threshold used by non-maximum suppression.
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
results = model.predict("bus.jpg", conf=0.25, iou=0.7)
for result in results:
for box in result.boxes:
class_id = int(box.cls[0])
score = float(box.conf[0])
x1, y1, x2, y2 = box.xyxy[0].tolist()
print(
model.names[class_id],
round(score, 2),
[round(value) for value in (x1, y1, x2, y2)],
)Here, box.xyxy contains pixel coordinates in the form (left, top, right, bottom). box.conf contains the confidence score, and box.cls contains the integer class index. The class index maps to a readable name through model.names.
A single image can produce several results when the input is a batch. The outer loop handles each result, even though this example uses one image.
Understand the thresholds
Increasing conf removes more low-scoring detections. This often improves precision but can reduce recall. Lowering it finds more possible objects but may add false positives.
The iou argument affects duplicate removal. A lower IoU threshold removes boxes that overlap even moderately. A higher threshold allows more overlapping boxes to remain. Tune both values on validation images rather than choosing them from one convenient example.
Exercise
What changes when you raise the confidence threshold from 0.25 to 0.75?
Show answer
The model keeps only higher-scoring detections, so false positives may decrease, but missed objects may increase because lower-scoring true detections are discarded.