Skip to main content
LearnMLAcademy
Advanced10 min read

Object Detection, Segmentation and Grad-CAM

Detect bounding boxes and explain convolutional feature maps with Grad-CAM, with feature-map visuals, architecture comparisons, and image exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Deep Learning · Visual Understanding

Classification tells us what an image contains. Many real systems must also say where each object is, which pixels belong to it, or which regions influenced a prediction. This lesson separates those questions, calculates bounding-box overlap, explains duplicate removal, follows an encoder–decoder segmentation network, and computes a small Grad-CAM heatmap without treating it as proof.

Choose the Output Before Choosing the Model

A warehouse camera may need to answer “is a helmet visible?” That is classification. If it must count workers without helmets, it needs a location for each person: object detection. If a robot must grasp the exact visible shape of every package, boxes are too coarse and instance masks are more useful.

Four questions produce four different outputs

The same street scene is represented differently according to the task.

Comparison of image classification, object detection, semantic segmentation and instance segmentationFour stylized street scenes show a whole image label, bounding boxes, one class color for all cars, and a different instance color for each car.Classificationcars presentone label for imageObject detectionclass + box per objectSemantic segmentationclass for every pixelInstance segmentationseparate mask per object
Semantic segmentation labels both cars as the same class. Instance segmentation additionally tells us that they are two distinct cars. Panoptic segmentation combines instance-aware “things” with semantic background “stuff.”
TaskExpected outputExample use
Image classificationOne or more labels for the whole imageProduct type, disease present/absent
Object detectionClass, confidence and bounding box for each objectCount vehicles; locate safety equipment
Semantic segmentationA class label for every pixelRoad versus pavement; tumour region
Instance segmentationSeparate pixel mask for every objectOutline and count touching cells
Panoptic segmentationSemantic labels for all pixels plus separate countable instancesComplete autonomous-driving scene map

A Detector Predicts What, Where and How Confident

A bounding box is commonly stored as its top-left and bottom-right coordinates: (xmin, ymin, xmax, ymax). The origin is usually the top-left of the image; x grows right and y grows down. A detector returns many candidate boxes, each with class scores and a confidence/objectness value.

Class

What object might be here?

forklift

Box

Where is it?

[120, 45, 310, 220]

Score

How strongly did the model support it?

0.87

The box numbers are model-produced pixel coordinates: left x=120, top y=45, right x=310 and bottom y=220. The score 0.87 is also produced by the model. A developer chooses a score threshold that decides whether this candidate is shown; the threshold is not learned automatically by this output.

Training usually combines several losses. A classification term teaches the class, a localization term teaches box coordinates, and some detectors add objectness or mask losses. Their weights affect the trade-off; a low total number is meaningful only with the exact loss definition and validation metrics.

Simplified multi-task loss

Ltotal = Lclass + λboxLbox + λobjLobjectness

Each λ is a developer-selected hyperparameter that controls a term's relative contribution. It is multiplied by a loss because the raw terms can have different scales and priorities. The exact losses, weights and matching process differ across detector families.

class loss
0.40

box loss
0.20 × λ=5

objectness
0.10 × λ=1

total
0.40+1.00+0.10=1.50

These small values and weights are manually chosen only to demonstrate the arithmetic. During real training, the model produces the three losses from its predictions and labels; the training configuration supplies the λ values.

Calculate Intersection over Union

A predicted box can name the right class but be badly placed. Intersection over Union (IoU) compares its overlap with a labelled ground-truth box while accounting for their combined area.

Intersection over Union measures box overlap

ground truth Aprediction Boverlap

Intersection over Union

IoU = area(A ∩ B) / area(A ∪ B)

The union includes every point covered by either box, counting the overlap once.

IoU = 1 means identical boxes; 0 means no overlap. A threshold such as 0.5 is a task/evaluation choice, not a universal definition of a correct detection.

Worked box example

Ground truth A = (10, 10, 50, 50). Prediction B = (30, 20, 70, 60). Coordinates are (xmin, ymin, xmax, ymax).

1. Areas
A=(50−10)(50−10)=1600
B=(70−30)(60−20)=1600

2. Intersection
width=min(50,70)−max(10,30)=20
height=30
area=600

3. Union
1600+1600−600
=2600

4. IoU
600/2600
≈ 0.231

Interpretation: only about 23.1% of the combined covered region overlaps. At IoU threshold 0.5 this prediction would not match the ground-truth object.

Why One Object Can Produce Several Boxes

Detectors examine many locations, scales or region proposals. Several candidates can surround the same car. Non-maximum suppression (NMS) is a post-processing step that keeps a high-scoring box and suppresses lower-scoring boxes of the same class that overlap it too strongly.

Non-maximum suppression turns duplicate proposals into cleaner detections

1 · Rank

A: 0.92, B: 0.78, C: 0.61

→

2 · Keep A

highest confidence

→

3 · Compare

IoU(A,B)=0.72; IoU(A,C)=0.08

→

4 · Suppress B

keep A and C

With an NMS IoU threshold of 0.5, B is removed because it overlaps A heavily and has a lower score. C remains because it likely describes another object. Crowded objects can challenge greedy NMS; soft-NMS reduces scores instead of immediately deleting boxes.

One-stage detectors such as YOLO, SSD and RetinaNet predict dense boxes/classes in one main pass and are often chosen for speed. Two-stage detectors such as Faster R-CNN first generate promising regions, then classify/refine them; they can offer strong accuracy but often cost more latency. This is a family-level tendency, not a guarantee for every model and device.

Segmentation Predicts a Class at Pixel Resolution

A semantic segmentation model produces a C × H × W grid of logits: C class scores at every pixel location. C is chosen from the number of categories in the task; H and W are the output grid's height and width. During training, the target is an H × W grid of class IDs supplied by the labelled mask.

A U-Net preserves detail while learning context

U-Net encoder, decoder and skip connectionsAn encoder reduces spatial resolution, a decoder restores resolution, and skip connections bring high-resolution encoder features to matching decoder stages.encoder: what is present?decoder: where are its pixels?128×128features 3264×64features 6432×32features 12832×32decode64×64decode128×128pixel classesskip connections restore fine spatial detail
The encoder sees larger context as resolution shrinks. The decoder upsamples. Skip connections concatenate corresponding encoder features so boundaries do not have to be reconstructed only from the smallest bottleneck.

In the teaching diagram, 128 → 64 → 32 is caused by two downsampling steps that each halve height and width. The channel counts 32 → 64 → 128 are designer-selected capacities, not spatial measurements. The decoder reverses the spatial changes, while skip connections copy same-resolution encoder features across so boundary detail is available again.

U-Net uses an encoder to build context and a decoder to restore resolution. Same-scale skip connections recover fine detail. DeepLab families use atrous (dilated) convolution and multi-scale context so filters see wider regions without downsampling as aggressively. Mask R-CNN extends a detector with a mask branch for each detected instance.

Pixel IoU for one class

IoU = TP / (TP + FP + FN)

TP: correctly predicted class pixels; FP: extra predicted pixels; FN: missed class pixels.

Dice coefficient

Dice = 2TP / (2TP + FP + FN)

Dice emphasizes overlap and ranges from 0 to 1 under this definition.

Tiny mask example: imagine the labelled object contains 80 pixels. The model correctly marks 60 of them (TP=60), misses 20 (FN=20), and incorrectly adds 10 background pixels (FP=10). IoU=60/(60+10+20)=0.667 and Dice=120/(120+10+20)=0.800. Both measure overlap, but Dice counts the correctly overlapping area twice.

Grad-CAM Explains a Class Score With a Coarse Heatmap

A classifier gives a label but no box. Grad-CAM uses gradients of one selected class score with respect to a convolutional feature tensor. It averages those gradients to assign one importance weight to each feature channel, combines the channel maps, and applies ReLU so positive support remains.

Grad-CAM asks which final feature-map regions supported one class score

product image

→

class logit

“defective”

→

gradients

weight feature maps

→

coarse heatmap

A warm region means changing features there would strongly affect the selected class score. It does not prove causality, fairness or correct reasoning, and the final convolutional maps make the localization coarse.

Grad-CAM for class c

αkc = (1/Z) Σi,j ∂yc/∂Ai,jk    Lc = ReLU(Σk αkcAk)

Ak is feature map k produced by the model, yc is the selected class logit, Z is the calculated number of spatial cells, and α is that map's average sensitivity for class c. Division by Z turns a sum over locations into an average so channel weights remain comparable across the map.

Two 2 × 2 feature maps

We manually choose the two small feature maps so every cell is visible. Backpropagation would calculate four class-score gradients per map; averaging those four gradients produces α₁=0.5 and α₂=−0.25 for this teaching example.

A₁=[[1,2],[0,1]], A₂=[[0,1],[2,1]]
weight and add matching cells: 0.5A₁−0.25A₂
= [[0.50,0.75],[−0.50,0.25]]
keep positive support with ReLU: Lᶜ=[[0.50,0.75],[0,0.25]]

Interpretation: the top-right cell provides the strongest positive support for class c in this coarse map. A negative combined cell becomes zero; Grad-CAM is showing supporting evidence, not a pixel-accurate object mask.

Evaluate the Whole Detection System

Detection evaluation must match predicted boxes to ground truth at an IoU threshold. Precision asks how many reported detections were correct; recall asks how many labelled objects were found. Varying the confidence threshold creates a precision–recall curve. Average Precision (AP) summarizes that curve for a class under a specified evaluation protocol; mAP averages AP across classes and sometimes across multiple IoU thresholds.

FailureWhat it changesWhat to inspect
Correct class, poor boxIoU and localization AP fallBox annotation consistency; small-object resolution; regression loss
Many duplicate boxesPrecision fallsNMS threshold, class-aware suppression and score calibration
Missed small objectsRecall and small-object AP fallInput resolution, feature pyramid, label quality and cropping
Good masks, rough boundariesBoundary quality weak despite acceptable region IoUAnnotation resolution, decoder detail, loss and post-processing
Grad-CAM highlights backgroundPossible shortcut learningBackground diversity, occlusion tests and counterfactual data—not heatmap alone

Run a Pretrained Detector Before Training One

This PyTorch example loads both pretrained weights and their matching preprocessing. A detector expects a list of C × H × W image tensors and returns one dictionary per image.

detect.py
import torch
from torchvision.io import decode_image
from torchvision.models.detection import (
    fasterrcnn_resnet50_fpn_v2,
    FasterRCNN_ResNet50_FPN_V2_Weights,
)

weights = FasterRCNN_ResNet50_FPN_V2_Weights.DEFAULT
model = fasterrcnn_resnet50_fpn_v2(
    weights=weights, box_score_thresh=0.80
)
model.eval()

image = decode_image("warehouse.jpg")      # [C, H, W], uint8
input_image = weights.transforms()(image)   # matching preprocessing

with torch.no_grad():
    prediction = model([input_image])[0]

labels = [weights.meta["categories"][i] for i in prediction["labels"]]
for label, score, box in zip(labels, prediction["scores"], prediction["boxes"]):
    print(label, round(float(score), 3), box.tolist())

# Each box is [x_min, y_min, x_max, y_max].

For custom training, each target must contain correctly typed boxes of shape [N,4], integer labels, and optional [N,H,W] masks. In the pretrained torchvision detection convention, class index 0 represents background. Transform boxes and masks with the image.

Choose the Simplest Output That Solves the Product Need

NeedStarting task/model directionTrade-off
Say whether one condition existsClassification + Grad-CAM for investigationCheapest labels; heatmap is not localization ground truth
Count and locate separate objectsObject detectorBox annotation costs more than image labels
Fast edge detectionLightweight one-stage detectorBenchmark device latency and small-object recall
High-quality general detection baselinePretrained Faster R-CNN-family modelOften slower and heavier
Label every pixel by categoryU-Net/DeepLab semantic segmentationPixel masks are expensive to annotate
Separate touching objectsMask R-CNN or instance-segmentation modelMore complex targets and evaluation

Limits You Must Not Hide

Annotation cost

Boxes are slower to label than classes; high-quality masks are slower still. Ambiguous boundaries create disagreement.

Small and crowded objects

Downsampling removes detail, while NMS can suppress neighbouring instances. Report metrics by size and density.

Domain shift

Weather, camera, hospital or production-line changes can break performance even when benchmark mAP is strong.

Metric dependence

AP changes with IoU thresholds, class averaging, max detections and dataset protocol. State the exact metric.

Heatmap over-trust

Grad-CAM is coarse and class-specific. Use it for investigation with other tests, not as proof of model reasoning.

Real-time claims

Frames per second depends on resolution, batch size, preprocessing, post-processing, hardware and runtime. Measure end to end.

The Connected Picture

  • Classification labels an image; detection adds boxes; segmentation assigns pixel labels; instance segmentation separates objects.
  • IoU measures geometric overlap and supports matching, NMS and evaluation.
  • NMS removes lower-scoring duplicate detections but needs careful thresholds in crowded scenes.
  • U-Net combines contextual encoding with detail-preserving skip connections.
  • Grad-CAM uses class gradients to weight feature maps and creates a coarse supporting-evidence map.
  • Choose the output and metric from the real decision the system must support.

Continue Learning

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Object Detection, Segmentation and Grad-CAM"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Summary / Key Takeaways

  • Detection predicts object classes and bounding boxes.
  • Intersection over Union measures predicted-target overlap.
  • Non-maximum suppression removes redundant overlapping detections.
  • Segmentation predicts pixel-level regions.
  • Grad-CAM highlights influential regions but is not causal proof.
  • Thresholds, small objects, imbalance, labels, and speed affect evaluation.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
How does object detection differ from image classification?
Question 2 of 5numerical/formula
A predicted box overlaps a target with intersection 40 and union 100. What is IoU?
Question 3 of 5conceptual
What problem does non-maximum suppression address?
Question 4 of 5interpretation
Why does segmentation require more spatial detail than detection?
Question 5 of 5practical selection
What is an important limit of Grad-CAM?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1How does object detection differ from image classification?▼

Correct Answer: It predicts classes and locations for multiple objects

Detection must say what objects are present and where each one is located.

2A predicted box overlaps a target with intersection 40 and union 100. What is IoU?▼

Correct Answer: 0.40

IoU is intersection divided by union: 40/100=0.40.

3What problem does non-maximum suppression address?▼

Correct Answer: Many overlapping detections of the same object

NMS retains a strong box and suppresses lower-scoring boxes with excessive overlap.

4Why does segmentation require more spatial detail than detection?▼

Correct Answer: It assigns a label to individual pixels

Pixel masks must preserve boundaries that a coarse box can ignore.

5What is an important limit of Grad-CAM?▼

Correct Answer: A heatmap is not proof of causal reasoning

Grad-CAM shows sensitivity of a score to regions, not a guaranteed causal explanation.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next