Angad Sandhu
Search
Browse
On this page

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
TaskInputOutputExample
ClassificationImageSingle label"This is a cat"
LocalizationImageLabel + 1 bounding box"Cat at (x,y,w,h)"
Object DetectionImageMultiple boxes + labelsAll objects with locations
Semantic SegmentationImagePixel-wise class labelsEvery pixel labeled
Instance SegmentationImagePixel-wise + instance IDsSeparate 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 + dimensions

Intersection 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 selected

Anchor 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 regressor

Problems:

  • 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 proposals

Improvements:

  • 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 regressor

Key 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 deltas

6.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 cell

YOLO 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 it

YOLO Loss Function:

L = λ_coord × Σ(localization loss)      # Box coordinates
  + Σ(confidence loss for objects)       # Objectness
  + λ_noobj × Σ(confidence loss for no objects)
  + Σ(classification loss)               # Class probabilities

YOLO Evolution:

VersionKey Improvements
YOLOv1Single-shot detection, real-time
YOLOv2Batch norm, anchor boxes, multi-scale
YOLOv3Multi-scale predictions, better backbone
YOLOv4CSPDarknet, PANet, many tricks
YOLOv5PyTorch, easy to use, various sizes
YOLOv8Anchor-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 sizes

Anchor-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:

  1. Face Verification: Is this person A? (1:1 matching)
  2. 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 generalization

Comparison

MethodLossKey Feature
FaceNetTriplet LossDirect embedding learning
SphereFaceA-SoftmaxMultiplicative angular margin
CosFaceLMCLAdditive cosine margin
ArcFaceAAMAdditive 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 detected

Average Precision (AP)

Area under Precision-Recall curve:

Precision
    │
1.0 ├──┐
    │  └──┐
    │     └──┐
    │        └──┐
    │           └──
    └──────────────── Recall
    0              1.0

AP = ∫ Precision(r) dr

Mean 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.95

Questions & 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:

  1. Divide image into S×S grid (e.g., 7×7)

    • Each cell responsible for detecting objects whose center falls in it
  2. Each cell predicts:

    • B bounding boxes (x, y, w, h, confidence)
    • C class probabilities
  3. 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) × IoU

Advantages:

  • 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 regressor

One-Stage Detectors (e.g., YOLO, SSD):

Single Stage: Direct Prediction
Image → Backbone → Dense predictions → NMS → Final detections
                   (all locations)

Comparison:

AspectTwo-StageOne-Stage
SpeedSlower (5-20 FPS)Faster (30-150+ FPS)
AccuracyGenerally higherSlightly lower (gap closing)
ArchitectureComplex (RPN + detector)Simpler
Small objectsBetterHistorically worse
TrainingMore complexEnd-to-end
MemoryHigherLower

Why the accuracy difference?

  1. Class imbalance:

    • Two-stage: RPN filters most background → balanced training
    • One-stage: Dense predictions → massive foreground/background imbalance
  2. 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 CaseRecommendation
Real-time applicationsOne-stage (YOLO, SSD)
Highest accuracy neededTwo-stage (Faster R-CNN)
Edge deploymentOne-stage (smaller models)
Small object detectionTwo-stage or FPN-based
Research baselineFaster R-CNN
Production deploymentYOLOv5/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.

Browse the library