6.3 Computer Vision
6.3 Computer Vision
Key Concepts
6.3.1 Computer Vision Tasks Overview
Computer vision encompasses several fundamental tasks, each with increasing complexity:
Image Classification Object Detection Semantic Segmentation Instance Segmentation
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ │ │ ┌───┐ │ │▓▓▓▓▓▓▓▓▓▓▓▓▓│ │▓▓▓▓▓▓▓▓▓▓▓▓▓│
│ 🐕 │ │ │🐕 │ ┌──┐ │ │▓▓▓🐕▓▓▓🐕▓▓▓│ │▓▓▓🐕₁▓▓🐕₂▓▓│
│ │ │ └───┘ │🐕│ │ ▓▓▓▓▓▓▓▓▓▓▓▓▓ │ │▓▓▓▓▓▓▓▓▓▓▓▓▓│
└─────────────┘ └────────└──┘─┘ └─────────────┘ └─────────────┘
Output: "dog" Output: boxes + Output: pixel-wise Output: pixel-wise
class labels class labels + instance IDs| Task | Input | Output | Example |
|---|---|---|---|
| Classification | Image | Single label | "This is a cat" |
| Localization | Image | Label + 1 bounding box | "Cat at (x,y,w,h)" |
| Object Detection | Image | Multiple boxes + labels | All objects with locations |
| Semantic Segmentation | Image | Pixel-wise class labels | Every pixel labeled |
| Instance Segmentation | Image | Pixel-wise + instance IDs | Separate each object |
6.3.2 Object Detection Fundamentals
Object detection = Classification + Localization for multiple objects.
Bounding Box Representation
┌────────────────────┐
│ (x₁, y₁) │
│ ┌─────────┐ │
│ │ │ h │
│ │ object │ │
│ │ │ │
│ └─────────┘ │
│ w (x₂,y₂)│
└────────────────────┘
Formats:
- (x₁, y₁, x₂, y₂): corner coordinates
- (x_center, y_center, w, h): center + dimensions
- (x₁, y₁, w, h): corner + dimensionsIntersection over Union (IoU)
IoU measures overlap between predicted and ground truth boxes:
IoU = Area of Intersection / Area of Union
┌─────────┐
│ A │
│ ┌─────┼───┐
│ │ A∩B │ │
└───┼─────┘ │
│ B │
└─────────┘
IoU = |A ∩ B| / |A ∪ B|- IoU = 1.0: Perfect overlap
- IoU = 0.0: No overlap
- IoU > 0.5: Typically considered a "good" detection
Non-Maximum Suppression (NMS)
NMS removes duplicate detections for the same object:
def nms(boxes, scores, iou_threshold=0.5):
# 1. Sort boxes by confidence score (descending)
# 2. Select highest scoring box, add to output
# 3. Remove all boxes with IoU > threshold with selected box
# 4. Repeat until no boxes remain
selected = []
while boxes:
best = boxes.pop(0) # Highest score
selected.append(best)
boxes = [b for b in boxes if iou(best, b) < iou_threshold]
return selectedAnchor Boxes (Prior Boxes)
Pre-defined boxes of various sizes and aspect ratios at each location:
At each grid cell, multiple anchors:
┌─────────────────┐
│ ┌──┐ ┌────┐ │
│ │ │ │ │ ┌─┐ │ Different aspect ratios:
│ └──┘ │ │ │ │ │ - 1:1 (square)
│ └────┘ │ │ │ - 1:2 (tall)
│ └─┘ │ - 2:1 (wide)
└─────────────────┘Network predicts offsets from anchors rather than absolute coordinates.
6.3.3 Two-Stage Detectors
Two-stage detectors first propose regions, then classify them.
R-CNN Family Evolution
R-CNN (2014) → Fast R-CNN (2015) → Faster R-CNN (2015)R-CNN (Regions with CNN)
Image → Selective Search (2000 proposals) → CNN (each region) → SVM classifier
→ Bbox regressorProblems:
- Very slow: CNN runs 2000 times per image
- Multi-stage training (CNN, SVM, regressor separately)
Fast R-CNN
Image → CNN (once) → Feature Map → RoI Pooling → FC → Classifier
↑ → Bbox regressor
Selective Search proposalsImprovements:
- CNN runs once on entire image
- RoI Pooling extracts fixed-size features from proposals
- End-to-end training
Faster R-CNN
Image → Backbone CNN → Feature Map → Region Proposal Network (RPN) → proposals
↓ ↓
RoI Pooling ←─────────────────────────────────────┘
↓
FC → Classifier + Bbox regressorKey innovation: Region Proposal Network (RPN)
- Replaces selective search with learned proposals
- Shares features with detection network
- Predicts objectness score + box refinement for each anchor
RPN Details:
Feature Map (H×W×C)
↓
3×3 conv (sliding window)
↓
┌─────────────────┐
↓ ↓
1×1 conv 1×1 conv
(2k scores) (4k coords)
objectness box deltas6.3.4 One-Stage Detectors (YOLO, SSD)
One-stage detectors predict boxes and classes directly without region proposals.
YOLO (You Only Look Once)
Core idea: Treat detection as a single regression problem.
Image → CNN → S×S×(B×5 + C) tensor
S×S grid cells
B bounding boxes per cell
5 values per box: (x, y, w, h, confidence)
C class probabilities per cellYOLO v1 Architecture:
Input (448×448)
↓
24 Conv layers + 2 FC layers
↓
Output: 7×7×30 tensor
For PASCAL VOC (20 classes):
- 7×7 grid
- 2 boxes per cell
- 30 = 2×5 + 20 = 10 (box params) + 20 (class probs)Grid Cell Responsibility:
┌───┬───┬───┬───┬───┬───┬───┐
│ │ │ │ │ │ │ │
├───┼───┼───┼───┼───┼───┼───┤
│ │ │ ● │ │ │ │ │ ● = object center
├───┼───┼───┼───┼───┼───┼───┤ This cell predicts
│ │ │ │ │ │ │ │ the object
├───┼───┼───┼───┼───┼───┼───┤
│ │ │ │ │ │ │ │
└───┴───┴───┴───┴───┴───┴───┘
Cell containing object center is responsible for detecting itYOLO Loss Function:
L = λ_coord × Σ(localization loss) # Box coordinates
+ Σ(confidence loss for objects) # Objectness
+ λ_noobj × Σ(confidence loss for no objects)
+ Σ(classification loss) # Class probabilitiesYOLO Evolution:
| Version | Key Improvements |
|---|---|
| YOLOv1 | Single-shot detection, real-time |
| YOLOv2 | Batch norm, anchor boxes, multi-scale |
| YOLOv3 | Multi-scale predictions, better backbone |
| YOLOv4 | CSPDarknet, PANet, many tricks |
| YOLOv5 | PyTorch, easy to use, various sizes |
| YOLOv8 | Anchor-free, decoupled head |
SSD (Single Shot MultiBox Detector)
Image → VGG-16 backbone → Multi-scale feature maps → Predictions
↓
┌─────────┼─────────┐
↓ ↓ ↓
38×38 19×19 10×10 ... (different scales)
(small) (medium) (large objects)Key features:
- Multi-scale feature maps for different object sizes
- Default boxes (anchors) at each scale
- Predictions from multiple layers
6.3.5 Modern Object Detection
Feature Pyramid Network (FPN)
Builds multi-scale feature pyramid with top-down pathway:
Bottom-up Top-down + Lateral connections
(backbone) (FPN)
C5 ────────────────→ P5 (1/32)
↑ ↓ (upsample + add)
C4 ──────────────────→ P4 (1/16)
↑ ↓
C3 ──────────────────→ P3 (1/8)
↑ ↓
C2 ──────────────────→ P2 (1/4)
Each P level used for detecting objects of different sizesAnchor-Free Detectors
Modern trend: eliminate anchor boxes entirely.
FCOS (Fully Convolutional One-Stage):
- Predicts (l, t, r, b) distances from each pixel to box edges
- Centerness score to down-weight low-quality predictions
CenterNet:
- Detects object centers as keypoints
- Predicts size from center location
6.3.6 Face Recognition
Face recognition involves two main tasks:
- Face Verification: Is this person A? (1:1 matching)
- Face Identification: Who is this person? (1:N matching)
Pipeline
Image → Face Detection → Alignment → Feature Extraction → Matching
↓ ↓
Landmarks Embedding (128-512 dim)FaceNet (2015)
Key innovation: Learn embeddings where distance = similarity.
Triplet Loss:
┌─────────┐
│ Anchor │──┐
└─────────┘ │
├── d(A,P) < d(A,N) + margin
┌─────────┐ │
│Positive │──┤ Same person: close
└─────────┘ │
│
┌─────────┐ │
│Negative │──┘ Different person: far
└─────────┘
L = max(0, d(A,P) - d(A,N) + margin)Training:
- Sample triplets: (anchor, positive, negative)
- Hard negative mining: select challenging negatives
- Learn 128-dimensional embeddings
Inference:
# Verification
embedding1 = model(face1)
embedding2 = model(face2)
distance = euclidean_distance(embedding1, embedding2)
same_person = distance < threshold
# Identification
query_embedding = model(query_face)
best_match = argmin([distance(query_embedding, db[i]) for i in database])ArcFace (2019)
Key innovation: Additive Angular Margin Loss for better discrimination.
Standard Softmax:
L = -log(e^(W_y·x) / Σe^(W_j·x))
ArcFace (Additive Angular Margin):
L = -log(e^(s·cos(θ_y + m)) / (e^(s·cos(θ_y + m)) + Σe^(s·cos(θ_j))))
Where:
- θ = angle between feature and weight
- m = angular margin (typically 0.5)
- s = scale factor (typically 64)Why angular margin works:
Feature space visualization:
Softmax: ArcFace:
Class 1 Class 1
/\ /\
/ \ / \
/ \ / m \ ← margin
/ \ /──────\
────────── ──────────
Class 2 Class 2
Larger margin → better separation → better generalizationComparison
| Method | Loss | Key Feature |
|---|---|---|
| FaceNet | Triplet Loss | Direct embedding learning |
| SphereFace | A-Softmax | Multiplicative angular margin |
| CosFace | LMCL | Additive cosine margin |
| ArcFace | AAM | Additive angular margin |
6.3.7 Evaluation Metrics for Detection
Precision and Recall
Precision = TP / (TP + FP) # Of detections, how many are correct?
Recall = TP / (TP + FN) # Of ground truths, how many are detected?
TP: IoU ≥ threshold (typically 0.5)
FP: IoU < threshold or duplicate detection
FN: Ground truth not detectedAverage Precision (AP)
Area under Precision-Recall curve:
Precision
│
1.0 ├──┐
│ └──┐
│ └──┐
│ └──┐
│ └──
└──────────────── Recall
0 1.0
AP = ∫ Precision(r) drMean Average Precision (mAP)
mAP = (1/C) × Σ AP_c # Average AP across all classes
Common variants:
- [email protected]: IoU threshold = 0.5
- [email protected]: IoU threshold = 0.75
- mAP@[0.5:0.95]: Average over IoU thresholds 0.5 to 0.95Questions & Answers
Q1: How does YOLO work for object detection?
Answer:
YOLO (You Only Look Once) treats object detection as a single regression problem, predicting bounding boxes and class probabilities directly from full images in one evaluation.
Core mechanism:
-
Divide image into S×S grid (e.g., 7×7)
- Each cell responsible for detecting objects whose center falls in it
-
Each cell predicts:
- B bounding boxes (x, y, w, h, confidence)
- C class probabilities
-
Single forward pass:
Image (448×448) → CNN → 7×7×30 tensor → NMS → Final detections
Bounding box prediction:
(x, y): Center relative to grid cell (0-1)
(w, h): Width/height relative to image (0-1)
confidence: P(Object) × IoU(pred, truth)Final prediction:
Class-specific confidence = P(Class_i | Object) × P(Object) × IoU
= P(Class_i) × IoUAdvantages:
- Extremely fast (45-155 FPS depending on version)
- Global context: sees entire image, fewer background errors
- Generalizes well to new domains
Limitations:
- Struggles with small objects (grid cell limitation)
- Each cell predicts limited boxes (misses nearby objects)
- Localization errors (coarse grid)
Modern YOLO versions address these with:
- Multi-scale predictions (YOLOv3+)
- Anchor boxes
- Better backbones
- Anchor-free designs (YOLOv8)
Q2: What is the difference between one-stage and two-stage detectors?
Answer:
The fundamental difference is whether region proposals are generated as a separate step.
Two-Stage Detectors (e.g., Faster R-CNN):
Stage 1: Region Proposal
Image → Backbone → RPN → ~2000 region proposals
Stage 2: Classification + Refinement
Proposals → RoI Pooling → Classifier → Final detections
→ Box regressorOne-Stage Detectors (e.g., YOLO, SSD):
Single Stage: Direct Prediction
Image → Backbone → Dense predictions → NMS → Final detections
(all locations)Comparison:
| Aspect | Two-Stage | One-Stage |
|---|---|---|
| Speed | Slower (5-20 FPS) | Faster (30-150+ FPS) |
| Accuracy | Generally higher | Slightly lower (gap closing) |
| Architecture | Complex (RPN + detector) | Simpler |
| Small objects | Better | Historically worse |
| Training | More complex | End-to-end |
| Memory | Higher | Lower |
Why the accuracy difference?
-
Class imbalance:
- Two-stage: RPN filters most background → balanced training
- One-stage: Dense predictions → massive foreground/background imbalance
-
Feature reuse:
- Two-stage: RoI pooling extracts features per proposal
- One-stage: Shared features for all predictions
Bridging the gap:
Modern one-stage detectors close the accuracy gap with:
- Focal Loss (RetinaNet): Down-weights easy negatives
- Feature Pyramid Networks: Multi-scale features
- Better architectures: CSPNet, PANet
- Anchor-free designs: FCOS, CenterNet
When to use which:
| Use Case | Recommendation |
|---|---|
| Real-time applications | One-stage (YOLO, SSD) |
| Highest accuracy needed | Two-stage (Faster R-CNN) |
| Edge deployment | One-stage (smaller models) |
| Small object detection | Two-stage or FPN-based |
| Research baseline | Faster R-CNN |
| Production deployment | YOLOv5/v8 |
Interview tip: Mention that the gap has narrowed significantly—modern one-stage detectors like YOLOv8 achieve competitive accuracy while maintaining speed advantages. The choice often depends on specific latency and accuracy requirements.