Sub topic 5
Reading a detector's output: boxes, scores and classes
This chapter assumes you know the box formats (xyxy, xywh, normalized) and intersection over union (IoU) from earlier chapters. It also assumes you know basic Python and what a convolutional network outputs. Here you will learn what a YOLO model actually produces for one image, how to turn that raw output into a list of detections, and where the common mistakes are.
From one image to a grid of predictions
A single-stage detector does not output "three objects" directly. It outputs a large, fixed-size set of candidate predictions. Each candidate is tied to a location in the image, and most candidates describe nothing useful.
The network looks at the image at several scales. At each scale it produces a feature map, and every cell of that map predicts one candidate. For a 640x640 input, YOLO commonly uses strides of 8, 16 and 32. The number of cells is:
| Stride | Grid size | Cells |
|---|---|---|
| 8 | 80 x 80 | 6400 |
| 16 | 40 x 40 | 1600 |
| 32 | 20 x 20 | 400 |
That gives 8400 candidates per image. Small strides see fine detail and suit small objects. Large strides see coarse context and suit large objects.
What each candidate contains
Each candidate holds two groups of numbers: a box and a set of class scores.
- Box: four numbers that locate the object. In the YOLOv8 family these are usually the center x, center y, width and height in input-image pixels (xywh format).
- Class scores: one number per class, for example 80 numbers for the COCO dataset.
So the raw output for one image has shape (4 + num_classes, 8400). For COCO that is (84, 8400). Many export tools transpose it to (8400, 84). Always check the shape before indexing.
Objectness: older and newer layouts
Older YOLO versions (v3 to v5) add a fifth box-related number called objectness. It estimates how likely it is that any object is centered in this cell. The final score for a class is then:
score(class) = objectness * class_probabilityRow length in those models is 5 + num_classes. Newer models such as YOLOv8 drop the objectness term. Each class score is predicted directly, and it already reflects both "is something here" and "which class is it". Mixing these layouts up is a common source of bugs, because the slice indices differ by one.
Decoding the raw tensor by hand
The following code decodes a YOLOv8-style tensor in NumPy. It uses random numbers in place of a real network output, so you can run it anywhere and watch the shapes change. It does not run NMS yet. That comes in the next step of the pipeline.
import numpy as np
rng = np.random.default_rng(0)
num_classes = 80
raw = rng.random((4 + num_classes, 8400)).astype(np.float32)
# Make the box values look like pixel coordinates.
raw[:4] *= 640
pred = raw.T # shape (8400, 84)
boxes_xywh = pred[:, :4] # cx, cy, w, h
class_scores = pred[:, 4:] # shape (8400, 80)
best_class = class_scores.argmax(axis=1)
best_score = class_scores.max(axis=1)
conf_thr = 0.9
mask = best_score >= conf_thr
cx, cy, w, h = boxes_xywh[mask].T
boxes_xyxy = np.stack([cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2], axis=1)
print("candidates:", len(pred))
print("kept after confidence filter:", int(mask.sum()))
print("first kept box:", boxes_xyxy[0].round(1), "class", best_class[mask][0])The steps are:
- Transpose so each row is one candidate.
- Split the row into box values and class scores.
- Take the highest class score per candidate. That is the candidate's confidence, and its position is the predicted class.
- Keep candidates whose confidence passes the threshold.
- Convert xywh to xyxy, so the IoU function from earlier works on them.
Why one object produces many candidates
A single car is covered by many cells. The cell at its center, and several neighbors, will all predict a box around the car with a high score. The network is trained to make these cells agree, so they produce near-duplicate boxes.
This is the reason a confidence filter alone is not enough. After filtering, you may still have 10 or 20 boxes for one car. The next chapter covers non-maximum suppression, which removes those duplicates. Decoding and NMS together form the post-processing step, and it runs after the network, not inside the training loss.
Two ways to count a score
A score is easy to misread. Keep these points in mind.
- A score is not a probability of being correct. It is a model output that is trained to correlate with correctness. A score of 0.8 does not mean 80% of such boxes are right. Calibration varies between models and datasets.
- Scores are not comparable across models. A threshold of 0.25 on one model may behave like 0.5 on another.
- Classes may use sigmoid, not softmax. YOLOv8 scores each class independently with a sigmoid function. Two classes can both score high for one box, for example "dog" and "cat" on an ambiguous animal. With softmax, class scores would sum to 1. Do not assume they do.
Reading the output of the Ultralytics API
You rarely decode the tensor yourself. The Ultralytics package does the decoding and NMS and gives you a Results object. The code below prints the main fields. It assumes bus.jpg exists in the working directory.
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
result = model.predict("bus.jpg", conf=0.25, verbose=False)[0]
print("image size (h, w):", result.orig_shape)
print("detections:", len(result.boxes))
boxes = result.boxes
print("xyxy :", boxes.xyxy.shape) # pixels, original image
print("xywh :", boxes.xywh.shape) # pixels, center format
print("xyxyn :", boxes.xyxyn.shape) # normalized 0-1
print("conf :", boxes.conf.shape)
print("cls :", boxes.cls.shape)
for xyxy, conf, cls_id in zip(boxes.xyxy, boxes.conf, boxes.cls):
name = result.names[int(cls_id)]
print(f"{name:10s} {float(conf):.2f}", [round(float(v)) for v in xyxy])Notes on this output:
xyxy,xywhandxyxynare three views of the same boxes. Use whichever your downstream code expects.xyxyandxywhare in pixels of the original image, not the resized 640x640 input. Ultralytics rescales the boxes back for you.clsis a float tensor of class indices. Cast it withint()before looking up a name.result.namesmaps index to label, for example{0: "person", 5: "bus"}.
Letterboxing and coordinate mapping
The network input is a fixed square, but your image rarely is. Detectors usually apply letterboxing: resize the image so its long side fits, then pad the short side with gray. The boxes the network predicts live in this padded coordinate system.
To map a box back to the original image, you must subtract the padding and divide by the scale factor:
def unletterbox(box, scale, pad_x, pad_y):
# box is (x1, y1, x2, y2) in letterboxed input pixels.
x1, y1, x2, y2 = box
return (
(x1 - pad_x) / scale,
(y1 - pad_y) / scale,
(x2 - pad_x) / scale,
(y2 - pad_y) / scale,
)
# A 1280x720 image resized into 640x640: scale 0.5, vertical padding 140.
print(unletterbox((100, 200, 300, 400), scale=0.5, pad_x=0, pad_y=140))
# (200.0, 120.0, 600.0, 520.0)Skipping this step is the most common reason boxes look shifted or stretched when you draw them yourself. If you use result.boxes.xyxy, the library already did it.
Common errors
| Symptom | Likely cause |
|---|---|
| Boxes are shifted vertically or horizontally | Letterbox padding not removed |
| Boxes are the right shape but the wrong size | Scale factor not applied, or normalized coordinates treated as pixels |
| Class names are off by one | Used an objectness-style slice (`5:`) on a model without objectness |
| Many overlapping boxes per object | NMS missing or IoU threshold too high |
| Hundreds of tiny boxes with low scores | Confidence threshold too low |
| `TypeError` when indexing `names` | Class index is a float, not an int |
Summary of the output contract
A detector's output for one image is, conceptually, a list of rows. After post-processing, each row holds:
- A box, in a known format and coordinate system.
- A confidence score.
- A class index, which you map to a name.
Before post-processing, there are thousands of such rows, most of them background and many of them duplicates. Knowing which stage you are looking at tells you how to interpret the numbers.
Exercise
A YOLOv8 model with 3 classes runs on a 320x320 input with strides 8, 16 and 32. (a) How many candidates does it produce, and what is the raw output shape before transposing? (b) One candidate has class scores [0.10, 0.72, 0.31] and box (cx=160, cy=100, w=60, h=40). What are its predicted class index, its confidence, and its xyxy box?
Show answer
(a) Grids are 40x40 = 1600, 20x20 = 400 and 10x10 = 100, so 2100 candidates. The raw shape is (4 + 3, 2100) = (7, 2100). (b) The highest score is 0.72 at index 1, so the class index is 1 and the confidence is 0.72. The box is x1 = 160 - 30 = 130, y1 = 100 - 20 = 80, x2 = 160 + 30 = 190, y2 = 100 + 20 = 120, giving (130, 80, 190, 120).
Exercise
You draw boxes from a 1280x720 image that was letterboxed to 640x640. Your boxes appear about 70 pixels too high in the drawn image's half-scale view, and everything else looks right. Which step did you most likely skip, and what values do you need?
Show answer
You skipped removing the letterbox padding. The scale is 0.5 (640/1280), the resized height is 360, so the vertical padding is (640 - 360) / 2 = 140 pixels on top. Subtract pad_y = 140 from the y values, then divide all coordinates by 0.5. Subtracting the padding first and then dividing is the correct order.