Vision in Practice: Object Detection (IoU/NMS), U-Net Segmentation & Transfer Learning
How real-world vision systems go beyond classification — bounding-box IoU & Non-Maximum Suppression (NMS), U-Net encoder–decoder skip bridges for segmentation, and production Transfer Learning.
95% of real-world Computer Vision projects NEVER train a CNN from scratch — they fine-tune a pretrained backbone into a Detector (YOLO) or Segmenter (U-Net)!
Understanding IoU, NMS, Focal Loss for class-imbalanced anchor boxes, and U-Net skip bridges (which also power Stable Diffusion!) is mandatory for vision & multimodal roles.
Knowing when to freeze early layers vs. unfreeze with a 10× smaller backbone LR turns a 500-image medical or retail dataset into a 95%+ accuracy model in 10 minutes.
Classic Computer Vision system design & coding favorite: 'Implement IoU and Non-Maximum Suppression (NMS) from scratch, and explain why U-Net concatenates encoder features instead of just upsampling from the bottleneck!'
Two identical 100 × 100 bounding boxes overlap by a 50 × 100 rectangle (half of each box). What is their exact Intersection over Union (IoU)?
- Distinguish Classification, Localization, Object Detection (YOLO/Faster R-CNN), and Semantic/Instance Segmentation
- Compute Intersection over Union (IoU) and execute Non-Maximum Suppression (NMS) step-by-step
- Explain why U-Net concatenates encoder skip features into the decoder to recover sharp pixel boundaries
- Design the optimal Transfer Learning strategy (Freeze vs. Fine-Tune + Discriminative LR) based on dataset size and domain shift
If Image Classification asks 'Is there a dog in this photo?', Object Detection draws a tight rectangle around every dog and car (IoU + NMS), and Segmentation (U-Net) colors every single pixel of the dog like a digital coloring book! And Transfer Learning is like hiring a veteran chef who already knows knife skills and heat control — you only have to teach them your restaurant's 10 signature dishes instead of teaching them how to boil water!
1. The Computer Vision Task Ladder & Object Detection (IoU + NMS)
Drag Box B and adjust the NMS threshold below to watch when NMS deletes a duplicate box vs. keeps a genuinely separate nearby object!
Exact IoU & Non-Maximum Suppression (NMS)
Given two axis-aligned boxes and :
- One-Stage Detectors (YOLO, RetinaNet): Predict boxes + class probabilities directly on a dense spatial grid in 1 fast forward pass (using Focal Loss from Ch 6 to handle 10,000:1 background-to-object imbalance!).
- NMS: Sort boxes by confidence descending → keep top box → discard remaining boxes with → repeat!
Interactive IoU & NMS Box Cleaner
2. U-Net Segmentation: Why Encoder–Decoder Skip Bridges Matter
A plain encoder shrinks a 256×256 medical MRI down to a 16×16 semantic bottleneck — great for knowing what tumor is present, terrible for knowing which exact boundary pixels belong to it! U-Net bridges high-resolution encoder maps straight across to the decoder.
Semantic vs. Instance Segmentation & Dice Loss
- Semantic Segmentation: Classifies every pixel into a category (
road,car,sky) without separating two adjacent cars. - Instance Segmentation (Mask R-CNN, SAM): Produces a separate pixel mask for each individual object.
- Dice Loss: For tiny medical lesions (1% of pixels), directly optimizes pixel overlap (like a smooth differentiable F1/IoU!).
3. U-Net Skip Bridges & Production Transfer Learning Playbook
Early CNN layers learn universal Gabor edges and color blobs shared across all natural and medical images — only the final layers specialize to ImageNet classes. Test your scenario in the Transfer Learning Planner below!
The 4-Quadrant Transfer Learning Playbook
- Small Dataset + Similar Domain: Freeze backbone (
p.requires_grad = False), train only a fresh linear/MLP classifier head! - Small Dataset + Different Domain (X-rays / Satellite): Freeze early layers (edges still apply!), fine-tune last 1–2 stages with strong augmentation.
- Large Dataset + Similar Domain: Unfreeze all with a small discriminative LR (
3e-5backbone,3e-4head) + warmup. - Large Dataset + Different Domain: Full fine-tuning starting from pretrained weights — still converges 3× faster and generalizes better than random init!
IoU = Area(A ∩ B) / (Area(A) + Area(B) − Area(A ∩ B))
Exact pixel area covered by BOTH predicted and ground-truth boxes (0 if disjoint).
(0,0,10,10) and Box B (5,0,15,10) overlap by 5×10 = 50, with union 100+100−50 = 150 → IoU = 50/150 = 0.333!Worked Example: Running Greedy NMS on 3 Overlapping Predictions
Boxes: A (score=0.95), B (score=0.80, IoU(A,B)=0.72), C (score=0.75, IoU(A,C)=0.10). NMS threshold τ = 0.50.
Add A to kept = [A].
Why does U-Net concatenate encoder feature maps directly into the decoder (torch.cat([dec, enc], dim=1))?
Why does nn.ConvTranspose2d (transposed convolution) in U-Net decoders sometimes create 'checkerboard artifacts', and what cleaner 2-line alternative do modern U-Nets use?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Standard class-wise NMS runs separately per predicted class (so a person box and a bicycle box overlapping heavily won't suppress each other!).
Transfer Learning Strategy & U-Net Skip-Flow Planner
Choose your dataset size and domain similarity to ImageNet to get the optimal production fine-tuning recipe.
Prevents overfitting your small dataset while reusing rich ImageNet features cleanly.
Autonomous Driving & Robotics (YOLO / DETR)
Real-time pedestrian, lane, and traffic-sign detection at 60+ FPS using IoU losses and NMS.
Medical Imaging (U-Net)
MRI tumor segmentation, retinal vessel tracing, and cell counting with Dice + BCE loss.
Generative Diffusion Models (Stable Diffusion)
Latent Diffusion denoises images using a Time-Conditioned U-Net with Attention skip bridges!
Industrial Transfer Learning
Fine-tuning pretrained ConvNeXt/ViT backbones on 500–2,000 labeled defect photos.
import torch
import torch.nn as nn
# 1. From-Scratch Box IoU (exact vectorized math)
def box_iou_scratch(box_a: torch.Tensor, box_b: torch.Tensor) -> torch.Tensor:
# box_a, box_b: (4,) as [x1, y1, x2, y2]
ix1 = torch.maximum(box_a[0], box_b[0])
iy1 = torch.maximum(box_a[1], box_b[1])
ix2 = torch.minimum(box_a[2], box_b[2])
iy2 = torch.minimum(box_a[3], box_b[3])
inter = (ix2 - ix1).clamp(min=0) * (iy2 - iy1).clamp(min=0)
area_a = (box_a[2] - box_a[0]).clamp(min=0) * (box_a[3] - box_a[1]).clamp(min=0)
area_b = (box_b[2] - box_b[0]).clamp(min=0) * (box_b[3] - box_b[1]).clamp(min=0)
return inter / (area_a + area_b - inter + 1e-7)
# 2. Idiomatic U-Net Decoder Up-Block (Resize-Conv + Skip Concatenation)
class UnetUpBlock(nn.Module):
def __init__(self, dec_ch: int, skip_ch: int, out_ch: int):
super().__init__()
self.up = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
self.conv = nn.Sequential(
nn.Conv2d(dec_ch + skip_ch, out_ch, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True),
)
def forward(self, dec: torch.Tensor, skip: torch.Tensor) -> torch.Tensor:
x = self.up(dec) # double (H, W)
x = torch.cat([x, skip], dim=1) # fuse high-res skip edges along channels!
return self.conv(x)
.clamp(min=0) when computing intersection width/height in IoU.min(x2) − max(x1) is negative; multiplying two negatives would give a fake positive area![0.485, 0.456, 0.406] and std [0.229, 0.224, 0.225] used during pre-training.10 × 10 boxes overlap in a 5 × 10 region. What is their IoU?