Beyond Classification: Detection and Segmentation at a Glance
Compare the outputs of classification, detection, semantic segmentation and instance segmentation; compute IoU by hand and with torchvision.ops, remove duplicate boxes with non-maximum suppression, work out average precision on a toy set of detections, inspect the output format of a torchvision detector, and pick a pretrained model family for each task.
Contentsand lesson path
On this page
- Why it matters
- Intersection over union
- Removing duplicates with non-maximum suppression
- Precision, recall and average precision
- Masks, model outputs and choosing a model family
- Check your understanding
- Apply it
- Review prompt
Lessons of CNNs & Computer Vision
- Convolutions: Filters, Strides and Shapes Concept · 20 min
- Lab: Train a Small CNN with Augmentation Lab · 30 min
- Why Residual Networks Train Deeper Concept · 15 min
- Lab: Transfer Learning with a Pretrained Backbone Lab · 30 min
- Beyond Classification: Detection and Segmentation at a Glance Concept · 15 min
- Check: Reading and Adapting a CNN Knowledge check · 8 questions
What you will learn
- Describe how object detection and segmentation outputs and metrics (IoU, mAP) differ from classification and pick a suitable pretrained model family for each task.
Prerequisites: Deep Learning Fundamentals
01. Why it matters
A classifier answers one question: what is in this image? It returns one score per class for the whole image. Many products need to know where things are as well, and each way of answering that changes the output, the loss and the metric. Four tasks cover most needs.
- Classification: one label per image, from a vector of class scores. Typical models are ResNet, which you fine-tuned in the transfer-learning lab, and the Vision Transformer (ViT).
- Object detection: for every object, a bounding box (a rectangle given by its corners), a class label and a confidence score. Two-stage detectors such as Faster R-CNN first propose candidate regions and then classify them; one-stage detectors such as RetinaNet and the YOLO family predict boxes in a single pass, which usually makes them faster.
- Semantic segmentation: a class id for every pixel, so the output has the height and width of the image. U-Net and DeepLab are common choices. Two touching objects of the same class become one region.
- Instance segmentation: a separate pixel mask for every object, plus its label and score. Mask R-CNN adds a mask branch to Faster R-CNN.
This lesson works through the pieces that all detection and instance-segmentation systems share: overlap between boxes, removing duplicates, and the metric used to compare detectors. You need Python 3.12, PyTorch 2, torchvision and SciPy; nothing is downloaded.
02. Intersection over union
A predicted box is rarely exactly on top of the true one, so you need a measure of how well two boxes agree. Intersection over union (IoU) divides the area where the boxes overlap by the area that either box covers: IoU = overlap / (area A + area B − overlap). It is 1 for identical boxes and 0 for boxes that do not touch. Subtracting the overlap matters, because otherwise it would be counted twice. torchvision stores boxes as (x1, y1, x2, y2), the top-left and bottom-right corners in pixels; torchvision.ops.box_iou compares every box in one set with every box in another.
import torch
from torchvision.ops import box_iou
def iou(a, b):
"""IoU of two boxes given as (x1, y1, x2, y2) in pixels."""
ix = max(0, min(a[2], b[2]) - max(a[0], b[0])) # width of the overlap
iy = max(0, min(a[3], b[3]) - max(a[1], b[1])) # height of the overlap
inter = ix * iy
area = lambda r: (r[2] - r[0]) * (r[3] - r[1])
return inter / (area(a) + area(b) - inter)
truth = (10, 10, 50, 50) # a 40 x 40 ground-truth box
pred = (30, 20, 70, 60) # a 40 x 40 prediction, shifted
print("overlap 20 x 30 = 600, union 1600 + 1600 - 600 = 2600")
print(f"IoU by hand: {iou(truth, pred):.4f}")
gts = torch.tensor([[10, 10, 50, 50], [60, 60, 100, 90]], dtype=torch.float)
preds = torch.tensor([[30, 20, 70, 60], # the shifted box
[12, 12, 48, 48], # inside the first box, slightly small
[62, 58, 101, 92]], # close to the second box
dtype=torch.float)
print("box_iou(preds, gts), one row per prediction:")
for row in box_iou(preds, gts).tolist():
print(" " + " ".join(f"{v:.4f}" for v in row))python iou.pyoverlap 20 x 30 = 600, union 1600 + 1600 - 600 = 2600
IoU by hand: 0.2308
box_iou(preds, gts), one row per prediction:
0.2308 0.0000
0.8100 0.0000
0.0000 0.8225The shifted box overlaps the truth on 20 × 30 = 600 pixels out of a union of 2,600, so IoU is 0.23 although the boxes clearly cover the same object in part. The box drawn slightly inside the first ground truth scores 0.81. Benchmarks call a detection correct when its IoU with an unclaimed ground-truth box reaches a threshold, most often 0.5. If your labels use another format, such as (x, y, width, height), convert them first with torchvision.ops.box_convert; box_iou assumes both sets are corners.
03. Removing duplicates with non-maximum suppression
A detector scores thousands of candidate boxes, and several of them usually land on the same object. Non-maximum suppression (NMS) cleans this up. It takes the box with the highest score, removes every remaining box whose IoU with it is above a threshold, and repeats with the next highest box that is still left. torchvision.ops.nms does exactly this for one class; batched_nms runs it separately per class, so a dog box does not suppress an overlapping person box.
import torch
from torchvision.ops import box_iou, nms
# raw detector output for one image: two cars, several boxes on each
boxes = torch.tensor([[10, 10, 50, 50], # car 1
[14, 12, 54, 52], # car 1 again, slightly shifted
[ 8, 14, 46, 54], # car 1 a third time
[80, 20, 120, 60], # car 2
[86, 24, 128, 66]], # car 2 again
dtype=torch.float)
scores = torch.tensor([0.90, 0.75, 0.60, 0.85, 0.40])
ious = box_iou(boxes[:1], boxes)[0]
print("IoU of each box with box 0:", [round(v, 2) for v in ious.tolist()])
keep = nms(boxes, scores, iou_threshold=0.5)
print("kept after NMS at 0.5 (by descending score):", keep.tolist())
print("IoU between boxes 3 and 4:", round(box_iou(boxes[3:4], boxes[4:5]).item(), 2))python nms.pyIoU of each box with box 0: [1.0, 0.75, 0.71, 0.0, 0.0]
kept after NMS at 0.5 (by descending score): [0, 3]
IoU between boxes 3 and 4: 0.57Boxes 1 and 2 overlap box 0 with IoU 0.75 and 0.71, above 0.5, so they are removed. Box 4 overlaps box 3 with IoU 0.57 and goes too. One box per car remains. The threshold is a trade-off: set it low and two real objects standing close together can suppress each other; set it high and duplicates survive and count as false detections.
04. Precision, recall and average precision
Accuracy does not fit detection: there is no fixed list of answers, and a detector can find an object, miss it, or report something that is not there. Evaluation therefore ranks all detections of one class by score, across all images, and walks down the list. A detection is a true positive (TP) if it reaches the IoU threshold with a ground-truth box that no higher-ranked detection has already claimed; otherwise it is a false positive. After each rank you compute precision, the share of detections so far that are correct, and recall, the share of all ground-truth objects found so far.
Average precision (AP) is the area under the resulting precision-recall curve. It summarises every score cut-off at once, so you do not have to choose a confidence threshold to compare two detectors. The script makes precision non-increasing before taking the area (each point takes the best precision at that recall or higher), which is how common benchmarks compute it.
import torch
from torchvision.ops import box_iou
# one class ("car") on two images: ground truth and ranked detections
truth = {0: [[10, 10, 50, 50], [60, 10, 100, 50]],
1: [[20, 20, 60, 60], [70, 30, 110, 70]]}
dets = [ # (image, score, box)
(0, 0.95, [11, 11, 51, 49]),
(1, 0.90, [22, 18, 62, 58]),
(0, 0.85, [12, 13, 52, 51]), # a second box on the first car
(1, 0.80, [72, 40, 112, 80]),
(0, 0.70, [61, 25, 101, 65]),
(1, 0.50, [150, 150, 190, 190]), # nothing there
]
def average_precision(iou_thr):
n_truth = sum(len(b) for b in truth.values())
used = {img: [False] * len(b) for img, b in truth.items()}
rows, tp = [], 0
for rank, (img, score, box) in enumerate(sorted(dets, key=lambda d: -d[1]), 1):
ious = box_iou(torch.tensor([box], dtype=torch.float),
torch.tensor(truth[img], dtype=torch.float))[0]
best = int(ious.argmax())
hit = ious[best] >= iou_thr and not used[img][best]
if hit:
used[img][best] = True # each object can be found only once
tp += hit
rows.append((rank, score, ious[best].item(), hit, tp / rank, tp / n_truth))
# area under the precision-recall curve, with precision made non-increasing
ap, prev_recall = 0.0, 0.0
for i, (*_, prec, rec) in enumerate(rows):
best_prec_after = max(r[4] for r in rows[i:])
ap += (rec - prev_recall) * best_prec_after
prev_recall = rec
return rows, ap
rows, ap50 = average_precision(0.5)
print("rank score best-IoU TP precision recall")
for rank, score, iou, hit, prec, rec in rows:
print(f"{rank:4d} {score:5.2f} {iou:8.2f} {'yes' if hit else ' no':>3s}"
f" {prec:10.3f} {rec:6.2f}")
print(f"AP at IoU 0.5: {ap50:.3f}")
print(f"AP at IoU 0.75: {average_precision(0.75)[1]:.3f}")python ap.pyrank score best-IoU TP precision recall
1 0.95 0.90 yes 1.000 0.25
2 0.90 0.82 yes 1.000 0.50
3 0.85 0.82 no 0.667 0.50
4 0.80 0.55 yes 0.750 0.75
5 0.70 0.44 no 0.600 0.75
6 0.50 0.00 no 0.500 0.75
AP at IoU 0.5: 0.688
AP at IoU 0.75: 0.500Rank 3 overlaps a car well but is a false positive, because rank 1 had already found that car. Rank 5 overlaps its car with IoU 0.44, below 0.5, and rank 6 covers empty road. Recall stops at 0.75: one car was never found. The area is 0.25 × 1.0 + 0.25 × 1.0 + 0.25 × 0.75 = 0.688. At a threshold of 0.75 the detection at rank 4 (IoU 0.55) also becomes a false positive, and AP falls to 0.500: a stricter threshold rewards boxes that fit tightly.
mAP (mean average precision) is the AP averaged over all classes. [email protected] uses an IoU threshold of 0.5, the PASCAL VOC convention. The COCO benchmark reports mAP@[.5:.95], the average over ten thresholds from 0.50 to 0.95 in steps of 0.05, and simply calls it AP. When you read a paper or a model card, check which of the two is meant, because the COCO number is much lower for the same detector.
05. Masks, model outputs and choosing a model family
Segmentation outputs come in two shapes. A semantic map is one (H, W) array of class ids. Instance masks are a stack of N boolean (H, W) masks, one per object. The script draws two people who touch and stores them both ways.
import numpy as np
import torch
from scipy import ndimage
from torchvision.ops import masks_to_boxes
H, W = 6, 10
person_a = np.zeros((H, W), dtype=bool)
person_a[1:6, 1:5] = True
person_b = np.zeros((H, W), dtype=bool)
person_b[1:6, 5:8] = True # touches person A at column 5
semantic = np.zeros((H, W), dtype=np.int64) # one class id per pixel: 0 = background
semantic[person_a | person_b] = 1 # 1 = person
print("semantic map (H, W), class ids:")
print(semantic)
_, regions = ndimage.label(semantic == 1)
print("connected 'person' regions in the semantic map:", regions)
instances = torch.from_numpy(np.stack([person_a, person_b])) # (N, H, W)
print("instance masks:", tuple(instances.shape), "pixels per mask:",
instances.sum(dim=(1, 2)).tolist())
print("boxes from the instance masks (x1, y1, x2, y2):")
print(masks_to_boxes(instances).int().tolist())python masks.pysemantic map (H, W), class ids:
[[0 0 0 0 0 0 0 0 0 0]
[0 1 1 1 1 1 1 1 0 0]
[0 1 1 1 1 1 1 1 0 0]
[0 1 1 1 1 1 1 1 0 0]
[0 1 1 1 1 1 1 1 0 0]
[0 1 1 1 1 1 1 1 0 0]]
connected 'person' regions in the semantic map: 1
instance masks: (2, 6, 10) pixels per mask: [20, 15]
boxes from the instance masks (x1, y1, x2, y2):
[[1, 1, 4, 5], [5, 1, 7, 5]]In the semantic map the two people form one connected region of 1s, so the map cannot tell you there are two of them. The instance masks keep them apart, and masks_to_boxes turns each mask into the box around it; its corners are inclusive pixel indices. Instance segmentation therefore gives you everything detection gives, plus the outline.
Next, the output format of a real detector. The script builds torchvision's Faster R-CNN with random weights (weights=None, weights_backbone=None), so nothing is downloaded and the boxes themselves are meaningless; only the format matters here. Building it and running two small images takes several seconds and about 0.6 GB of memory.
import torch
from torchvision.models.detection import fasterrcnn_resnet50_fpn
torch.manual_seed(0)
# random weights: nothing is downloaded; the point is the input and output format
model = fasterrcnn_resnet50_fpn(weights=None, weights_backbone=None, num_classes=3,
min_size=320, max_size=320)
model.eval()
images = [torch.rand(3, 240, 320), torch.rand(3, 300, 300)] # a list, sizes may differ
with torch.no_grad():
out = model(images)
print("one dict per image:", len(out), sorted(out[0].keys()))
for i, o in enumerate(out):
print(f"image {i}: boxes {tuple(o['boxes'].shape)} {o['boxes'].dtype}, "
f"labels {tuple(o['labels'].shape)} {o['labels'].dtype}, "
f"scores {tuple(o['scores'].shape)}")
b = out[0]["boxes"] # (x1, y1, x2, y2) in input pixels
inside = bool((b[:, 2] <= 320).all() and (b[:, 3] <= 240).all())
print("boxes of image 0 lie inside its 320 x 240 frame:", inside)
print("label ids in image 0 (0 is reserved for background):",
out[0]["labels"].unique().tolist())
print("parameters:", f"{sum(p.numel() for p in model.parameters()):,}")python detector.pyone dict per image: 2 ['boxes', 'labels', 'scores']
image 0: boxes (100, 4) torch.float32, labels (100,) torch.int64, scores (100,)
image 1: boxes (100, 4) torch.float32, labels (100,) torch.int64, scores (100,)
boxes of image 0 lie inside its 320 x 240 frame: True
label ids in image 0 (0 is reserved for background): [2]
parameters: 41,357,406The model takes a list of (C, H, W) tensors, which may have different sizes, and returns one dictionary per image with boxes (N, 4) in the pixel coordinates of that input image, labels and scores. Label 0 is reserved for background, so a model for two object classes is built with num_classes=3. By default it keeps up to 100 detections with a score above 0.05 per image, which is why each image returns 100 boxes here; in an application you then pick your own score threshold. In training mode the same call needs the targets and returns a dictionary of losses instead; without them it stops with AssertionError: targets should not be none when in training mode. maskrcnn_resnet50_fpn returns the same keys plus masks.
To choose a pretrained model, start from the output you need. For boxes, torchvision offers Faster R-CNN, RetinaNet, FCOS and SSD with COCO weights (the Faster R-CNN ResNet-50 FPN weights are a 160 MB download); YOLO-family models come from separate libraries, so check their licences. For instance masks, Mask R-CNN. For semantic maps, DeepLabV3, FCN and LR-ASPP are in torchvision, and U-Net, common in medical imaging, is available in other libraries. For one label per image, a ResNet or ViT classifier. Then fine-tune on your own classes, as in the transfer-learning lab, and evaluate with the metric that matches the output.
06. Check your understanding
07. Apply it
The practice project for this skill is a classification task. Write a short note next to it on how the project would change if the requirement moved beyond one label per image.
- Pick one of your classes and describe a product need for each of detection, semantic segmentation and instance segmentation on your images.
- For each, name the output format, a torchvision or third-party model family, and the metric you would report (for example
[email protected]or COCO AP for boxes, mean IoU per class for semantic maps). - Estimate the labelling cost: drawing a box takes much less time than tracing a mask, and that often decides the task more than the model does.
08. Review prompt
Without looking back, describe the output of classification, detection, semantic segmentation and instance segmentation and name a model family for each; write the IoU formula and say why the overlap is subtracted in the union; explain what NMS does and what its threshold trades off; describe how detections are ranked and matched to compute precision, recall and AP; and explain the difference between [email protected] and COCO AP.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.