Sub topic 2
Reading a Detector's Output: Boxes, Scores and Classes
This chapter assumes you know basic Python, can install packages with pip, and understand that a neural network produces numbers from its inputs. You should also know how an image classifier labels a whole picture.
Reading a detector's output
A detector returns a list of detections. Each detection has three parts: a bounding box, a class index, and a confidence score between 0 and 1. The box is usually stored in xyxy format: left x, top y, right x, bottom y, measured in pixels.
Removing duplicate boxes with non-maximum suppression
One object often triggers several overlapping boxes. Non-maximum suppression (NMS) keeps the highest-scoring box and removes any other box of the same class whose intersection over union (IoU) with it exceeds a threshold, often 0.5 to 0.7. IoU is the overlap area divided by the combined area of the two boxes.
Backbone, neck and head
The backbone extracts features from the image at several scales. The neck combines those features so that small and large objects are both represented. The head converts each feature location into box coordinates, an objectness score, and class scores.
Running a pretrained YOLO model
The following code loads a small pretrained model and prints each detection. It assumes bus.jpg is in the working directory.
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)])The conf argument drops detections below that score. The iou argument sets the NMS threshold.
Preparing a dataset in YOLO format
YOLO expects one text file per image. Each line in that file describes one object:
# class_id x_center y_center width height (all normalized to 0-1)
0 0.512 0.430 0.200 0.350A YAML file tells the trainer where the images are and what each class index means:
path: datasets/my_data
train: images/train
val: images/val
names:
0: cat
1: dogExercise
A detector outputs two boxes for one dog, with IoU 0.8 between them and scores 0.91 and 0.64. If NMS uses an IoU threshold of 0.5, how many boxes remain?
Show answer
One box remains. The 0.64 box overlaps the 0.91 box above the threshold, so NMS removes it.