Advanced Computer Vision: Detection and Segmentation
Modern computer vision systems do three related but distinct jobs. Classification assigns a label to an image, detection locates every instance with a box plus a label, and segmentation assigns a class to every pixel. Production systems usually combine them, and the interesting engineering lives in the seams: how boxes are matched, how duplicates are suppressed, how small objects survive a stride-32 backbone, and how much augmentation the model can absorb before the labels stop being true. This lesson works through each of those with runnable PyTorch.
Detection as dense prediction
A detector reframes detection as a regression and classification problem over a grid. The image passes through a backbone that reduces spatial resolution while growing channel depth, a neck that merges features from several scales, and heads that emit, for every anchor or cell, an objectness score, box coordinates, and class probabilities. Multi-scale heads matter because a stride-32 feature map cannot localise an object that occupies four pixels, while a stride-8 map lacks the semantic context to tell a fire hydrant from a bollard.
Everything after the forward pass is bookkeeping. Scores below a confidence threshold are dropped, overlapping boxes are merged, and the survivors become the prediction. That bookkeeping is where many home-grown detectors fail, not in the architecture.
IoU, matching, and non-maximum suppression
Intersection over union is the currency of detection evaluation: the overlap area divided by the union area, giving zero for disjoint boxes and one for identical ones. During training, anchors are matched to ground truth at an IoU threshold, typically 0.5 for a permissive match and 0.7 for a strict one. During evaluation, average precision integrates precision over recall, and mean average precision averages that across classes.
| Concept | Typical threshold | What it controls |
|---|---|---|
| Anchor to ground-truth match | 0.5 | Which positives each anchor is responsible for |
| Non-maximum suppression | 0.45 | How aggressively duplicate boxes merge |
| Confidence filter | 0.25 to 0.4 | Recall versus false positive volume |
| Eval IoU for a true positive | 0.5 or 0.75 | Strictness of the reported metric |
Non-maximum suppression sorts detections by score, keeps the strongest, and removes every remaining box whose IoU with it exceeds the threshold. It is greedy and approximate, which is why dense scenes with heavy overlap sometimes lose genuine instances, and why learned alternatives such as non-maximum suppression free decoders exist for crowded imagery.
import torch
def iou_matrix(boxes_a: torch.Tensor, boxes_b: torch.Tensor) -> torch.Tensor:
"""Pairwise IoU for two sets of xyxy boxes."""
tl = torch.max(boxes_a[:, None, :2], boxes_b[None, :, :2])
br = torch.min(boxes_a[:, None, 2:], boxes_b[None, :, 2:])
inter = (br - tl).clamp(min=0).prod(dim=2)
area_a = (boxes_a[:, 2:] - boxes_a[:, :2]).prod(dim=1)
area_b = (boxes_b[:, 2:] - boxes_b[:, :2]).prod(dim=1)
union = area_a[:, None] + area_b[None, :] - inter
return inter / union.clamp(min=1e-8)
def non_max_suppression(dets: torch.Tensor, iou_thresh: float = 0.45,
score_thresh: float = 0.25) -> torch.Tensor:
"""dets: rows of x1, y1, x2, y2, score, class."""
keep = []
dets = dets[dets[:, 4] > score_thresh]
while dets.numel():
order = dets[:, 4].argmax()
best = dets[order]
keep.append(best)
if dets.size(0) == 1:
break
rest = torch.cat([dets[:order], dets[order + 1:]])
overlap = iou_matrix(best[None, :4], rest[:, :4]).squeeze(0)
dets = rest[overlap <= iou_thresh]
return torch.stack(keep) if keep else torch.empty(0, 6)
predictions = torch.tensor([
[10.0, 10.0, 60.0, 60.0, 0.92, 0.0],
[12.0, 14.0, 58.0, 62.0, 0.81, 0.0],
[200.0, 40.0, 260.0, 120.0, 0.67, 1.0],
[40.0, 300.0, 90.0, 380.0, 0.31, 2.0],
])
print(non_max_suppression(predictions))
A minimal multi-scale detector
The head below shows the shape arithmetic that trips people up. Convolutional output has channels equal to anchors times the sum of box offsets, objectness, and classes, and it must be reshaped so that anchors, grid cells, and predictions line up before any loss is computed. Getting the reshape right is half the debugging work in a new detector: a silent off-by-one in the grid dimension produces a loss that looks fine numerically while the model learns nothing useful.
When you assemble the full detector, remember that each output scale needs its own assignment logic. Coarse grids with large receptive fields should claim large objects, while fine grids claim small ones; letting every scale compete for every box produces duplicate detections that only the final suppression stage can remove, which is wasteful and error-prone. Ground-truth matching therefore assigns each object to the single best-fitting scale and then to the best anchors at that scale.
import torch
import torch.nn as nn
class ConvBlock(nn.Module):
def __init__(self, in_ch: int, out_ch: int, stride: int = 1):
super().__init__()
self.block = nn.Sequential(
nn.Conv2d(in_ch, out_ch, 3, stride=stride, padding=1, bias=False),
nn.BatchNorm2d(out_ch),
nn.SiLU(inplace=True),
)
def forward(self, x):
return self.block(x)
class DetectionHead(nn.Module):
def __init__(self, in_ch: int, num_classes: int, num_anchors: int = 3):
super().__init__()
self.num_anchors = num_anchors
self.num_classes = num_classes
self.pred = nn.Conv2d(in_ch, num_anchors * (5 + num_classes), 1)
def forward(self, x):
batch, _, h, w = x.size()
raw = self.pred(x)
raw = raw.view(batch, self.num_anchors, 5 + self.num_classes, h, w)
return raw.permute(0, 1, 3, 4, 2).contiguous()
class TinyDetector(nn.Module):
def __init__(self, num_classes: int = 4):
super().__init__()
self.backbone = nn.Sequential(
ConvBlock(3, 16, stride=2),
ConvBlock(16, 32, stride=2),
ConvBlock(32, 64, stride=2),
ConvBlock(64, 128, stride=2),
)
self.head = DetectionHead(128, num_classes)
def forward(self, x):
return self.head(self.backbone(x))
model = TinyDetector(num_classes=4)
out = model(torch.randn(2, 3, 256, 256))
print(out.shape)
In a real training loop this tensor is compared against assigned targets with a box loss, an objectness loss, and a classification loss, usually balanced so that the abundant easy negatives do not drown the rare positives. Focal loss performs exactly that reweighting by down-weighting confident negatives and leaving hard positives dominant, which is why it remains the default for one-stage detectors even years after its introduction. The balance between the three loss components also needs tuning per dataset; a scene where objects rarely overlap may tolerate a higher classification weight, while crowded traffic footage often demands stronger box regression supervision so that adjacent vehicles do not collapse into a single detection.
Semantic segmentation with U-Net
Segmentation keeps resolution instead of collapsing it. U-Net is the reference architecture: a contracting encoder extracts context through strided convolutions, and an expanding decoder restores spatial detail with transposed convolutions, while skip connections pass high-resolution features straight across so boundaries stay sharp.
import torch
import torch.nn as nn
import torch.nn.functional as F
class DoubleConv(nn.Module):
def __init__(self, in_ch: int, out_ch: int):
super().__init__()
self.block = nn.Sequential(
nn.Conv2d(in_ch, out_ch, 3, padding=1),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True),
nn.Conv2d(out_ch, out_ch, 3, padding=1),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True),
)
def forward(self, x):
return self.block(x)
class UNet(nn.Module):
def __init__(self, in_ch: int = 3, num_classes: int = 8):
super().__init__()
self.enc1 = DoubleConv(in_ch, 64)
self.enc2 = DoubleConv(64, 128)
self.enc3 = DoubleConv(128, 256)
self.pool = nn.MaxPool2d(2)
self.bottleneck = DoubleConv(256, 512)
self.up3 = nn.ConvTranspose2d(512, 256, 2, stride=2)
self.dec3 = DoubleConv(512, 256)
self.up2 = nn.ConvTranspose2d(256, 128, 2, stride=2)
self.dec2 = DoubleConv(256, 128)
self.up1 = nn.ConvTranspose2d(128, 64, 2, stride=2)
self.dec1 = DoubleConv(128, 64)
self.out = nn.Conv2d(64, num_classes, 1)
@staticmethod
def _match(x, target):
diff_y = target.size(2) - x.size(2)
diff_x = target.size(3) - x.size(3)
return F.pad(x, [diff_x // 2, diff_x - diff_x // 2,
diff_y // 2, diff_y - diff_y // 2])
def forward(self, x):
e1 = self.enc1(x)
e2 = self.enc2(self.pool(e1))
e3 = self.enc3(self.pool(e2))
b = self.bottleneck(self.pool(e3))
d3 = self.dec3(torch.cat([self._match(self.up3(b), e3), e3], dim=1))
d2 = self.dec2(torch.cat([self._match(self.up2(d3), e2), e2], dim=1))
d1 = self.dec1(torch.cat([self._match(self.up1(d2), e1), e1], dim=1))
return self.out(d1)
def dice_coeff(pred: torch.Tensor, target: torch.Tensor, eps: float = 1e-6) -> float:
pred = pred.float().reshape(-1)
target = target.float().reshape(-1)
return float((2 * (pred * target).sum() + eps) / (pred.sum() + target.sum() + eps))
net = UNet(in_ch=3, num_classes=8)
print(net(torch.randn(1, 3, 128, 128)).shape)
Class imbalance is severe in segmentation, because a background class can occupy ninety percent of the image. Pairing cross-entropy with a Dice or Tversky loss usually recovers the rare foreground classes that accuracy alone would ignore.
Augmentation that actually moves the metric
Augmentation is often the cheapest accuracy available. Geometric transforms must keep labels consistent, so a flip or a crop has to be applied identically to the image and its mask, while photometric transforms such as brightness or blur act only on the image. Beyond the basics, MixUp blends two images and both label vectors, and CutMix pastes a patch from one image into another with the labels mixed in proportion to the removed area. Both regularise effectively because they defeat the shortcut of memorising texture in one corner.
import numpy as np
class MixUpCutMix:
def __init__(self, alpha: float = 1.0, seed: int = 0):
self.alpha = alpha
self.rng = np.random.default_rng(seed)
def mixup(self, images: np.ndarray, labels: np.ndarray):
lam = self.rng.beta(self.alpha, self.alpha)
index = self.rng.permutation(images.size(0))
mixed = lam * images + (1 - lam) * images[index]
return mixed, labels, labels[index], lam
def cutmix(self, images: np.ndarray, labels: np.ndarray):
lam = self.rng.beta(self.alpha, self.alpha)
index = self.rng.permutation(images.size(0))
_, h, w, _ = images.shape
cut_h, cut_w = int(h * np.sqrt(1 - lam)), int(w * np.sqrt(1 - lam))
cy, cx = self.rng.integers(h), self.rng.integers(w)
y1, y2 = max(0, cy - cut_h // 2), min(h, cy + cut_h // 2)
x1, x2 = max(0, cx - cut_w // 2), min(w, cx + cut_w // 2)
mixed = images.copy()
mixed[:, y1:y2, x1:x2, :] = images[index, y1:y2, x1:x2, :]
actual = 1 - ((y2 - y1) * (x2 - x1)) / (h * w)
return mixed, labels, labels[index], actual
aug = MixUpCutMix(alpha=0.4)
batch = np.random.rand(4, 64, 64, 3)
targets = np.eye(10)[[2, 5, 7, 1]]
mixed, a, b, lam = aug.cutmix(batch, targets)
print(mixed.shape, round(float(lam), 3))
Apply these in the training loop only. Mixing images at evaluation time makes the labels meaningless and guarantees a confusing score.
Vision transformers and patch tokenisation
A Vision Transformer treats an image as a sequence of patches. A convolution with a kernel and stride equal to the patch size projects non-overlapping regions into the embedding space, a learned class token is prepended, positional embeddings are added, and a standard encoder processes the result. Classification reads only the class token output.
| Decision | Common choice | Effect of raising it |
|---|---|---|
| Patch size | 16 on 224 pixel inputs | Fewer tokens, cheaper compute, coarser detail |
| Embedding width | 768 | More capacity, more memory and data required |
| Depth | 12 layers | Stronger representations, harder optimisation |
| Heads | 12 | finer attention splits, same parameter count |
Transformers need more data than convolutional networks, so practitioners either pretrain on large corpora or use a data-efficient variant with a distillation token that mimics a teacher model. For small industrial datasets, a convolutional backbone with a strong augmentation recipe still tends to win, and the honest benchmark is a head-to-head run on your own splits rather than a leaderboard from a different domain.
Common Mistakes
Tuning the backbone while confidence and IoU thresholds stay at library defaults
Fix: Sweep the confidence and non-maximum suppression thresholds against your precision and recall targets first, since they move the metric more than most architecture changes.
Applying MixUp or CutMix during validation
Fix: Restrict aggressive label-mixing augmentation to training, and keep evaluation transforms deterministic so scores are comparable between runs.
Reporting accuracy alone on a heavily imbalanced segmentation task
Fix: Report per-class IoU and Dice alongside mean IoU so a dominant background class cannot hide collapsed foreground predictions.
Best Practices
- Use multi-scale feature maps so tiny objects still have a usable stride
- Pair cross-entropy with Dice or Tversky loss for imbalanced masks
- Keep evaluation transforms fixed and deterministic across experiments
- Benchmark against a simple convolutional baseline before adopting a Vision Transformer
- Log the thresholds used for every reported detection result
Key Takeaways
- IoU underpins anchor matching, non-maximum suppression, and evaluation alike
- Multi-scale heads exist because a single stride cannot serve both small and large objects
- Skip connections are what let a decoder recover sharp boundaries
- MixUp and CutMix improve generalisation only when labels are mixed consistently
- Patch size trades spatial detail against sequence length in a Vision Transformer