30 Mins

6. Object Detection & Segmentation Basics

Taxonomy: Classification, Detection, and Segmentation

In computer vision, the complexity of understanding an image grows from recognizing 'what' is in a frame to 'where' it is located, and finally to 'which' pixels belong to a specific object. Image classification assigns a single global label to an entire image, ignoring spatial structure. Object detection extends this by identifying multiple instances of objects, localizing them with bounding boxes, and providing a class score for each box.

Semantic segmentation represents the pinnacle of pixel-level understanding. Unlike object detection, which treats objects as discrete entities within boxes, segmentation assigns a class label to every individual pixel in the image. This allows for fine-grained morphological understanding, which is critical for tasks like autonomous driving, where the exact boundary of a sidewalk or pedestrian is required for safety-critical navigation.

Operator Note: Think of classification as a high-level summary, detection as localized identification, and segmentation as a comprehensive map of the image contents.
Python 3
import torch
# Mocking outputs for 3 different vision heads
# Classification: 10 classes
cls_out = torch.randn(1, 10)
# Detection: 4 coordinates (x,y,w,h) + class confidence
det_out = torch.randn(1, 5, 4) 
# Segmentation: 5 classes (H, W)
seg_out = torch.randn(1, 5, 224, 224)
print(f'Detection shape: {det_out.shape}, Seg shape: {seg_out.shape}')

Bounding Boxes and Anchor Mechanics

Bounding boxes are typically represented either by top-left (x1, y1) and bottom-right (x2, y2) coordinates or by the center point (cx, cy) and dimensions (width, height). Most modern detectors, such as Faster R-CNN or YOLO, utilize 'anchor boxes'—predefined reference boxes of various aspect ratios and scales—to handle objects of different shapes within a single feature map cell.

The network's task is then transformed into a regression problem: predict the offsets (delta_x, delta_y, delta_w, delta_h) to transform the anchor box into the ground-truth box. This shift from absolute prediction to relative offset prediction significantly stabilizes training, allowing the model to focus on adjusting standard shapes rather than learning raw coordinate values from scratch.

Operator Note: Using anchor boxes helps the model solve the problem of spatial scale invariance by providing a fixed set of search targets for the regressor.
Python 3
def calculate_iou(box1, box2):
    # box = [x1, y1, x2, y2]
    x1 = max(box1[0], box2[0]); y1 = max(box1[1], box2[1])
    x2 = min(box1[2], box2[2]); y2 = min(box1[3], box2[3])
    intersection = max(0, x2 - x1) * max(0, y2 - y1)
    area1 = (box1[2]-box1[0]) * (box1[3]-box1[1])
    area2 = (box2[2]-box2[0]) * (box2[3]-box2[1])
    return intersection / (area1 + area2 - intersection + 1e-6)

Evaluating Detection: IoU and mAP

To evaluate a detector, we use Intersection over Union (IoU), which is the ratio of the overlap area between the predicted box and the ground truth to their union area. A threshold is typically applied; for instance, an IoU >= 0.5 usually classifies a prediction as a True Positive. Precision and recall are then calculated based on these TP/FP classifications.

The mean Average Precision (mAP) is the industry-standard metric. It is the average of the Average Precision (AP) values calculated for each object class. AP is the area under the Precision-Recall curve. By calculating mAP at different IoU thresholds, or averaging across them, we get a holistic sense of how well the model balances localization accuracy and classification confidence.

Operator Note: mAP is preferred over accuracy because in object detection, the background usually dominates, making simple accuracy metrics highly misleading.
Python 3
import numpy as np
# Example of computing mAP across classes
def compute_map(precisions, recalls):
    # Integrate area under the PR curve
    return np.trapz(precisions, recalls)
# Mock values
ap_classes = [0.85, 0.72, 0.91]
print(f'Mean Average Precision: {np.mean(ap_classes):.2f}')

Segmentation Architectures: The U-Net Paradigm

Semantic segmentation often relies on an Encoder-Decoder architecture. The encoder acts as a feature extractor, downsampling the input to learn high-level semantic abstractions, while the decoder upsamples the feature map back to the original input resolution to make pixel-wise predictions.

The defining feature of the U-Net architecture is the use of 'skip connections'. These connections concatenate high-resolution feature maps from the encoder directly to the corresponding layers in the decoder. This allows the model to preserve spatial information—like sharp boundaries—that is often lost during the aggressive downsampling required for abstract feature representation.

Operator Note: Skip connections act as a bridge, ensuring that the decoder has access to the fine-grained edge details found in the encoder's early layers.
Python 3
import torch.nn as nn
# Mock Skip Connection block
class SkipBlock(nn.Module):
    def forward(self, encoder_feat, decoder_feat):
        # Concatenate along channel dimension
        return torch.cat([encoder_feat, decoder_feat], dim=1)
print('Skip connection allows spatial recovery in U-Net')

Knowledge Check

Ready to test your understanding of 6. Object Detection & Segmentation Basics?

Back