Skip to main content
Web lecture note covering the computer-vision task landscape, CNN and Vision Transformer backbones, object detection from R-CNN to DETR, semantic and instance segmentation, pose estimation, and multi-object tracking.
Modified

November 16, 2026

APM 5DA12 TP · Deep Learning for Computer Vision

From pixels to structured scene understanding

Lecture 1 · Jhony H. Giraldo · Télécom Paris, Institut Polytechnique de Paris

Lecture: 13 November 2026Web note revised: 16 November 2026Click any figure to enlarge it

A classifier looks at an image and returns one word. A vision system usually needs much more: where each object is, how many there are, which pixels belong to the road, where a person’s joints are, and whether the person in this frame is the one from the last frame. Each of these questions has its own output representation, loss, and metric.

This note first recaps computer vision, convolutional networks (CNNs), and Vision Transformers (ViTs), then climbs the ladder of structured outputs: object detection, segmentation, pose estimation, and multi-object tracking. One idea organizes everything: the backbone is reusable; the representation, head, loss, metric, and inference must match the task. Most figures annotate the same street scene with the outputs of real pretrained models, so the numbers in the figures are measurements, not illustrations.

1 Learning objectives

After studying this note, you should be able to:

  1. place a vision problem in the task taxonomy and name its output, loss, and metric;
  2. compute the output size, parameter count, and receptive field of convolution layers;
  3. write the Vision Transformer forward pass, from patches to the class token, with tensor shapes;
  4. compute IoU, precision, and recall, and explain anchors, NMS, and the focal loss;
  5. explain what changed from R-CNN to Fast R-CNN to Faster R-CNN, and how DETR removes anchors and NMS;
  6. design a segmentation network from an encoder, a decoder, skip connections, and atrous convolutions;
  7. describe Mask R-CNN and Keypoint R-CNN as heads on a shared detector;
  8. assemble a tracking-by-detection loop with a cost matrix and one-to-one assignment.

What you should already know

Linear algebra (vectors, matrices, tensors, dot products), optimization (gradients, SGD, regularization), basic deep learning (losses, backpropagation, CNN basics), and Python with basic PyTorch. The recaps below are compact; the preliminary notes of Machine Learning with Graphs cover the perceptron, MLPs, backpropagation, and SGD from scratch.

Part IComputer vision recap

2 What can machines understand from pixels?

The street scene annotated with a pixel zoom, an image label, detection boxes, road and sidewalk masks, and pedestrian tracks, beside a legend of five output types
Figure 1: One image, five outputs of increasing structure: (1) raw pixels — the zoom shows the RGB values of the red traffic light; (2) one class for the whole image; (3) boxes with classes and scores; (4) a class for every pixel; (5) identities over time.
Table 1: Output representations covered in this lecture.
Output Formal object Question it answers
1 pixels \(\mathbf{x}\in[0,255]^{H\times W\times 3}\) raw measurements, no meaning
2 class \(y\in\{1,\dots,C\}\) what is the scene? (no where)
3 boxes \(\{(\mathbf{b}_k,c_k,s_k)\}_{k=1}^{K}\) what and where, for every object
4 masks \(\mathbf{M}\in\{1,\dots,C\}^{H\times W}\) which class at every pixel?
5 tracks \(\{(t,\mathbf{b}^i_t,\mathrm{ID}_i)\}\) who is who, over time?

Here \(H\) and \(W\) are the image height and width in pixels, and \(C\) is the number of classes. A detection is a box \(\mathbf{b}_k\) with class \(c_k\) and confidence score \(s_k\), and \(K\) is the number of detections. A mask \(\mathbf{M}\) stores one class per pixel. A track pairs a frame index \(t\) with the box \(\mathbf{b}^i_t\) of object \(i\) and its identity \(\mathrm{ID}_i\).

Each step down the table makes the output more structured and the supervision costlier. In practice many engineering tricks are needed to make each of these systems work; this lecture cannot cover them all, but you should expect to meet them.

2.1 Encode, then decode

Three boxes: image x, representation z equals f theta of x, prediction y hat equals g phi of z
Figure 2: The common template: an encoder turns the image into a representation, and a task-specific head turns the representation into a prediction.

\[ \mathbf{z}=f_\theta(\mathbf{x}), \qquad \hat{\mathbf{y}}=g_\phi(\mathbf{z}), \]

where \(\mathbf{x}\) is the image (or video), \(f_\theta\) is a neural network — convolution- or attention-based — with parameters \(\theta\), \(\mathbf{z}\) is the representation, and \(g_\phi\) is a second network, the prediction head, with parameters \(\phi\), producing the prediction \(\hat{\mathbf{y}}\). The central learning question is: what representation makes the target predictable from finite data?

2.2 Computer vision is an inverse problem

A 3D scene with a light, a camera, a cube, a sphere, and a cylinder, with arrows labelled graphics render and vision infer
Figure 3: Graphics renders an image \(I\) from a world \(S\); vision must infer \(\hat S\) from \(I\). A smaller object closer to the camera produces the same image as a larger one farther away.

Image formation can be written as

\[ I=R(S,\ell,c)+\varepsilon, \]

where \(I\) is the observed image, \(S\) is the 3D world (shape, pose, material), \(\ell\) the lighting, \(c\) the camera, \(R\) the image-formation (rendering) process, and \(\varepsilon\) noise or unmodelled effects. Vision must recover an estimate \(\hat S\) of the world from \(I\). The problem is ill-posed: a different world \(S'\neq S\) can produce the same \(I\). Vision succeeds by combining data with priors — assumptions about which worlds are plausible.

2.3 Why computer vision is hard

Street scene with a red box labelled same car and a blue box labelled small plus far around a bus
Figure 4: The same car can look large and near or small and far: pixel size is not object size.
  • Projection: depth collapses onto the image plane.
  • Appearance: lighting, weather, texture, sensor noise.
  • Geometry: viewpoint, deformation, articulation, scale.
  • Visibility: occlusion, clutter.
  • Semantics: context and ambiguous categories.
  • Open world: rare and unseen cases matter.

Useful invariance (a shifted car is still a car) must coexist with sensitivity to location, shape, and identity (the box must move with the car).

2.4 Task taxonomy

Table 2: The output space determines annotation cost, architecture, loss, inference, and metric.
Task Output unit Central question
Classification image What is present?
Localization one box + class Where is the main object?
Detection set of boxes What objects, and where?
Semantic segmentation pixel Which class per pixel?
Instance segmentation object mask Which pixels belong together?
Pose estimation keypoint / part Where are the articulated parts?
Tracking trajectory + ID Which observation is the same entity?
Five thumbnails of the scene with an image label, boxes, a dense class map, keypoints, and identities over time
Figure 5: One image, progressively richer annotations: more spatial structure, more annotation, more ways to be wrong.

3 A brief history

A timeline from 1959 to 2023 with eight milestones and three era labels
Figure 6: Milestones: the visual cortex (Hubel and Wiesel 1962), the Summer Vision Project (Papert 1966), LeNet (LeCun et al. 1998), SIFT and HOG (Lowe 2004; Dalal and Triggs 2005), ImageNet (Deng et al. 2009), AlexNet (Krizhevsky et al. 2012), ViT (Dosovitskiy et al. 2021), and foundation models. Three eras: hand-designed features, supervised deep learning, and pretraining at scale.

3.1 From handcrafted features to learned representations

Top, the HOG pipeline with gradients, cells, orientation histograms, and an SVM; bottom, a CNN with stacked feature blocks
Figure 7: Then: the HOG pedestrian detector, with a hand-designed descriptor and a learned linear SVM. Now: a CNN in which every filter and weight is learned and the loss gradient trains all stages jointly.

The HOG detector (Dalal and Triggs 2005) computes the image gradient \(\nabla I\) of the input image \(I\) with the filter \([-1,0,1]\), divides a \(64\times128\) window into \(8\times16\) cells of \(8\times8\) pixels, builds a 9-bin orientation histogram per cell, normalizes overlapping \(2\times2\)-cell blocks, and concatenates everything into a descriptor \(\mathbf{x}\in\mathbb{R}^{3780}\) (\(7\times15\) blocks \(\times\) 4 cells \(\times\) 9 bins). A linear SVM then predicts the label \(\hat y=\operatorname{sign}(\mathbf{w}^\top\mathbf{x}+b)\), where \(\mathbf{w}\) and \(b\) are the learned SVM weights and bias.

Every stage has a CNN counterpart — gradient filters are a first convolution, histograms are a nonlinearity plus pooling, block normalization is a normalization layer, the SVM is a linear head — but in a CNN all of them are learned jointly from the loss. End-to-end learning replaces hand-designed interfaces, but not the need for good assumptions or evaluation.

3.2 Why deep learning changed computer vision

Four circles labelled data scale, GPU compute, useful bias, and pre-training, pointing to transferable visual features
Figure 8: Data scale, GPU compute, a useful inductive bias, and pretraining together produce transferable visual features optimized end to end.

Convolution encoded locality; attention later added adaptive global interaction. Large labelled datasets made comparisons credible, and large unlabelled datasets widened pretraining. Better optimization, normalization, and residual connections made much deeper networks trainable.

4 Supervised learning for images

Given a training set \(\mathcal{D}_{\text{train}}=\{(\mathbf{x}_i,\mathbf{y}_i)\}_{i=1}^{N}\) and predictions \(\hat{\mathbf{y}}_i=f_\theta(\mathbf{x}_i)\), we learn

\[ \theta^{*}=\arg\min_{\theta}\;\frac{1}{N}\sum_{i=1}^{N}\mathcal{L}\big(f_\theta(\mathbf{x}_i),\mathbf{y}_i\big)+\lambda\,\Omega(\theta), \]

where \(\mathbf{x}_i\) is input image \(i\), \(\mathbf{y}_i\) its target (label), \(N\) the number of training examples, \(f_\theta\) the model with parameters (weights) \(\theta\), \(\mathcal{L}\) the loss — how wrong one prediction is — \(\Omega(\theta)\) a regularizer with strength \(\lambda\ge0\), and \(\theta^*\) the learned parameters.

The loss is optimized on the training data; choices (architecture, learning rate, epochs) are made on the validation data; the test set estimates final generalization and is used once, at the very end.

4.1 Image classification

A classifier outputs one score per class and turns the scores into probabilities with a softmax:

\[ \mathbf{s}=f_\theta(\mathbf{x})\in\mathbb{R}^{C}, \qquad p(y=c\mid\mathbf{x})=\frac{e^{s_c}}{\sum_{k=1}^{C}e^{s_k}}, \qquad \mathcal{L}_{\text{CE}}=-\log p(y\mid\mathbf{x}), \]

where \(\mathbf{x}\) is the input image, \(C\) the number of classes, \(\mathbf{s}\) the class scores (logits), \(s_c\) the score of class \(c\), \(k\) an index over all classes, \(p(y=c\mid\mathbf{x})\) the predicted probability of class \(c\), \(y\) the true class, and \(\mathcal{L}_{\text{CE}}\) the cross-entropy loss. Cross-entropy rewards probability on the ground-truth class.

Table 3: A ResNet’s prediction for the street scene.
class street scene parking lot bus station other
probability 0.84 0.09 0.05 0.02

If the true class is “street scene”, \(\mathcal{L}_{\text{CE}}=-\ln0.84=0.17\); had the model given it only \(0.09\), the loss would be \(-\ln0.09=2.41\).

4.2 A machine-learning pipeline for images

Six connected panels: dataset and splits, augment and normalize, model, loss and optimizer, metrics, deploy and monitor
Figure 9: The pipeline: dataset and splits, augmentation and normalization, the model, loss and optimizer, metrics, and deployment with monitoring. New failures become new data.

Each training step normalizes and augments the images, then updates the weights on a mini-batch:

\[ \tilde{\mathbf{x}}=\frac{\mathbf{x}-\boldsymbol\mu}{\boldsymbol\sigma}, \qquad \ell_i=-\log p_\theta(y_i\mid\tilde{\mathbf{x}}_i), \qquad \mathcal{L}(\theta)=\frac1B\sum_{i=1}^{B}\ell_i, \qquad \theta\leftarrow\theta-\eta\,\nabla_\theta\mathcal{L}, \]

where \(\boldsymbol\mu\) and \(\boldsymbol\sigma\) are the per-channel mean and standard deviation, \(\tilde{\mathbf{x}}\) the normalized image, \(p_\theta(y\mid\tilde{\mathbf{x}})\) the predicted class probabilities, \(\ell_i\) the loss of example \(i\), \(B\) the batch size, \(\mathcal{L}(\theta)\) the batch loss, \(\eta\) the learning rate, and \(\nabla_\theta\mathcal{L}\) the gradient with respect to \(\theta\).

Before training, and the most common leakage

Before training: define the target, fix the split, inspect the labels, and establish a simple baseline.

Leakage: the validation or test data are not truly independent of the training data, so the measured performance looks better than the model’s real ability to generalize — for example, consecutive frames of one video split across train and test. Split by the unit you want to generalize over (video, patient, location).

Part IIRecap: convolutional neural networks

5 Convolutional networks

5.1 Convolution: a learned local pattern detector

A grayscale crop, an 8 by 8 grid of pixel values with a highlighted window, a Sobel kernel, the response 906, and the output feature map
Figure 10: A Sobel-\(x\) kernel slid over a \(64\times64\) grayscale crop around the traffic light. The zoom shows real pixel values; the highlighted \(3\times3\) window straddles the pole’s edge and gives \(906\). The output map is red for dark → bright and blue for bright → dark.

\[ y_{i,j}=b+\sum_{u,v,c}K_{u,v,c}\,x_{i+u,\,j+v,\,c}, \tag{1}\]

where \(\mathbf{x}\) is the input image, \(\mathbf{y}\) the output feature map, \(K\) the kernel weights, \(b\) the bias, \((i,j)\) the output row and column, \((u,v)\) the offset inside the kernel, and \(c\) the input channel (a single one for a grayscale image).

Worked example — One output of the Sobel filter

With \(K=\begin{bmatrix}-1&0&1\\-2&0&2\\-1&0&1\end{bmatrix}\), the window’s left column \((21,19,23)\), right column \((248,247,246)\), and \(b=0\): \[ y=-21+248-2\cdot19+2\cdot247-23+246=906 . \] A large positive value means “dark on the left, bright on the right”: a vertical edge.

The same weights are used at every location; a high response means a local pattern match; training learns \(K\), and sliding records where the pattern occurs. Convolution is a local linear operator with shared parameters.

5.2 Channels, kernels, and feature maps

An RGB crop split into channels, four colour-coded kernels, and four feature maps
Figure 11: A layer with \(C_{\text{in}}=3\) input and \(C_{\text{out}}=4\) output channels. Each kernel is \(3\times3\times3\) and produces one feature map after ReLU: vertical edges, horizontal edges, red minus green, and green minus red and blue.

A layer maps an input \(\mathbf{x}\) of size \(H\times W\times C_{\text{in}}\) to an output of size \(H'\times W'\times C_{\text{out}}\), where \(H,W\) are the input height and width, \(H',W'\) the output height and width, and \(C_{\text{in}},C_{\text{out}}\) the numbers of input and output channels. Output channel \(k\) is \(\operatorname{ReLU}(K_k*\mathbf{x}+b_k)\), where \(K_k\) and \(b_k\) are the weights and bias of kernel \(k\) and \(*\) is convolution. With kernel side \(K\),

\[ \#\text{params}=K^{2}C_{\text{in}}C_{\text{out}}+C_{\text{out}}, \]

which for Figure 11 is \(3^2\cdot3\cdot4+4=112\), independent of \(H\) and \(W\). Each output channel mixes all input channels but only a local spatial neighbourhood. A \(1\times1\) convolution changes the number of channels without enlarging the spatial receptive field.

5.3 Stride, padding, and dilation

Three grids illustrating padding, stride two, and dilation two
Figure 12: Padding adds a border, stride moves the kernel by more than one pixel, and dilation spaces the kernel taps apart.

For one spatial dimension,

\[ H'=\left\lfloor\frac{H+2P-D(K-1)-1}{S}\right\rfloor+1, \tag{2}\]

where \(H\) is the input size, \(H'\) the output size, \(K\) the kernel size, \(P\) the zero padding per side, \(S\) the stride (sampling step), \(D\) the dilation (spacing inside the kernel), and \(\lfloor\cdot\rfloor\) rounds down. The effective kernel size is \(D(K-1)+1\).

For example, \(H=32\), \(K=3\), \(S=2\), \(P=1\), \(D=1\) gives \(H'=\lfloor31/2\rfloor+1=16\); reducing the stride to \(S=1\) gives \(H'=32\). These hyperparameters determine resolution, compute, and visible context.

5.4 Pooling: invariance versus spatial precision

A 4 by 4 grid reduced to 2 by 2 by max pooling and by average pooling
Figure 13: \(2\times2\) max and average pooling with stride 2 on a \(4\times4\) map.

For the top-left window \(\{1,7,3,4\}\), max pooling keeps \(7\) and average pooling gives \(15/4=3.75\). Pooling summarizes a neighbourhood and reduces resolution and compute. It increases tolerance to small shifts, but exact boundaries and keypoints become harder to recover. Modern networks often downsample with a strided convolution instead.

5.5 Receptive field

Four stacked grids with highlighted squares of growing size, r0 equals 1 up to r3 equals 7
Figure 14: Three stacked \(3\times3\) convolutions with stride 1: one unit of layer 3 sees a \(7\times7\) patch of the input.

\[ j_\ell=j_{\ell-1}\,s_\ell, \qquad r_\ell=r_{\ell-1}+(k_\ell-1)\,d_\ell\,j_{\ell-1}, \qquad j_0=r_0=1, \]

where \(\ell\) is the layer index (\(\ell=0\) is the input), \(k_\ell\), \(s_\ell\), \(d_\ell\) are the kernel size, stride, and dilation of layer \(\ell\), \(j_\ell\) is the number of input pixels between neighbouring units of layer \(\ell\), and \(r_\ell\) is the receptive-field size of one unit, in input pixels.

With \(k_\ell=3\) and \(s_\ell=d_\ell=1\), \(r_\ell=1+2\ell\). If instead the second layer has stride \(s_2=2\), then \(j_2=2\) and \(r_3=5+2\cdot2=9\). Depth, stride, and dilation expand context; dense prediction needs both broad context and high-resolution detail.

5.6 The recurring CNN architecture pattern

A block diagram above ResNet-18 activation maps shrinking from 224 by 224 to 7 by 7, ending in class probabilities
Figure 15: Real activations of an ImageNet ResNet-18 on the car crop. Each stage is conv → norm → activation → downsample; the stem and four stages reduce \(224^2\times3\) to \(7^2\times512\) (written \(H\times W\times\) channels); global average pooling and a linear head give the class probabilities.

Here \(H,W\) are the feature-map height and width, and each \(\downarrow2\) halves both. Two trades happen together. Spatial trade: \(H,W\) decrease while the receptive field and semantic abstraction increase. Channel trade: more channels preserve diverse evidence as resolution shrinks. A classifier discards spatial detail at the end; dense tasks tap the intermediate maps.

5.7 VGG: small filters, deep and simple

Two 3 by 3 boxes approximately equal to one 5 by 5 box with weight counts 18 C squared and 25 C squared
Figure 16: Two stacked \(3\times3\) convolutions cover a \(5\times5\) region with two nonlinearities and fewer weights.

If every layer has \(C\) input and output channels, two \(3\times3\) layers cost \(18C^2=2\times(3\cdot3\cdot C\cdot C)\) weights against \(25C^2\) for one \(5\times5\) layer — cheaper, and with two nonlinearities instead of one. VGG (Simonyan and Zisserman 2015) uses only \(3\times3\) convolutions in 16 or 19 weight layers; VGG-16 has about 138M parameters, most of them in its heavy fully connected classifier. Its clean design became a template, even though later networks are far more efficient.

5.8 ResNet: learn a residual correction

A block diagram with x passing through two conv layers and an identity path, added, then sigma
Figure 17: A residual block: the input skips the convolutional branch along the identity path and is added to its output.

Before ResNet, deeper models were not better than shallower ones, although a deeper model contains the shallower one (extra layers could copy their input). The problem was optimization, not capacity. ResNet (He et al. 2016) makes the identity easy to learn:

\[ \mathbf{y}=\sigma\big(\mathcal{F}(\mathbf{x};\theta)+\mathbf{x}\big), \]

where \(\mathbf{x}\) is the block input, \(\mathbf{y}\) the block output, \(\mathcal{F}\) the residual branch (the convolutional layers) with weights \(\theta\), and \(\sigma\) the activation (ReLU). Identity paths carry signal and gradients — ignoring \(\sigma\), \(\partial\mathbf{y}/\partial\mathbf{x}=\mathbf{I}+\partial\mathcal{F}/\partial\mathbf{x}\) — so very deep networks become trainable and reusable.

5.9 Normalization and activations

Plot of the ReLU and GELU activation functions
Figure 18: ReLU and GELU.

Batch normalization (Ioffe and Szegedy 2015) works per channel:

\[ \hat x=\frac{x-\mu_{\mathcal{B}}}{\sqrt{\sigma_{\mathcal{B}}^{2}+\epsilon}}, \qquad y=\gamma\hat x+\beta, \]

where \(\mathcal{B}\) is the current mini-batch, \(x\) one activation of the channel, \(\mu_{\mathcal{B}}\) and \(\sigma^2_{\mathcal{B}}\) its mean and variance over \(\mathcal{B}\), \(\epsilon\) a tiny constant that avoids division by zero, \(\hat x\) the normalized activation, \(\gamma\) and \(\beta\) a learned scale and shift, and \(y\) the output. It improves optimization and permits larger learning rates, but its behaviour depends on batch statistics and on train/eval mode (model.eval() switches to running averages). LayerNorm normalizes within one token or example and needs no batch statistics.

For an activation function \(\sigma(x)\) with input \(x\): ReLU, \(\max(0,x)\), is cheap, sparse, and piecewise linear; GELU (Hendrycks and Gimpel 2016) is a smooth gate common in transformers.

5.10 Transfer learning

A pretrained backbone provides generic visual features; a new head maps them to the \(C\) classes of the target data.

Table 4: Transfer-learning strategies.
Strategy Trainable weights Best when Main risk
Linear probe head only little data; diagnose the representation under-adaptation
Partial fine-tune head + late blocks moderate data / related domain difficult layer choice
Full fine-tune all weights enough data and compute overfitting / forgetting

Always adapt the preprocessing and normalization to the exact pretrained checkpoint.

5.11 A hierarchy of visual features

Panels of first-layer filters, part detectors, class activation maps, and a detection head output
Figure 19: What ResNet-18 computes on the scene. Early: 64 first-layer filters (\(7\times7\times3\)) detect edges, colour, and micro-texture. Middle: the patches that most activate three layer-3 units look like wheels, heads, and legs. Late: class activation maps (Zhou et al. 2016) localize whole objects. A task head reads these features.

Resolution decreases and abstraction increases with depth. Classification can use the final semantic vector; detection and segmentation combine late semantics with earlier spatial detail. “Features” are task- and training-dependent, not a universal visual vocabulary.

5.12 Feature pyramids

Backbone maps C2 to C5 connected by lateral convolutions and top-down arrows to pyramid maps P2 to P5, with detections on the scene
Figure 20: A feature pyramid network on ResNet-50, from torchvision’s Faster R-CNN on the scene. Backbone outputs \(C_2\)–\(C_5\) (left) become pyramid outputs \(P_2\)–\(P_5\) (right), all with 256 channels. Each detection is coloured by the level that predicted it: small pedestrians on \(P_2\), the car and the nearest person on \(P_3\).

Objects come in very different sizes. A feature pyramid network (Lin, Dollár, et al. 2017) gives every scale strong semantics:

\[ P_5=\operatorname{conv}_{1\times1}(C_5), \qquad P_\ell=\operatorname{conv}_{3\times3}\!\Big(\operatorname{conv}_{1\times1}(C_\ell)+\operatorname{up}_{2\times}(P_{\ell+1})\Big), \]

where \(\ell\in\{2,\dots,5\}\) is the stage or pyramid level, \(C_\ell\) is the backbone output after stage \(\ell\) (stride \(2^\ell\)), \(P_\ell\) the pyramid output at the same stride with 256 channels, \(\operatorname{conv}_{k\times k}\) a convolution with a \(k\times k\) kernel, and \(\operatorname{up}_{2\times}\) a \(2\times\) upsampling (doubling \(H\) and \(W\)). Each level predicts objects of a suitable size: objects of 224 pixels or more go to \(P_4\), of 448 or more to \(P_5\).

5.13 CNN strengths: a useful inductive bias

Definition 1 — Translation equivariance

If \(T_\delta\) shifts an image \(\mathbf{x}\) by \(\delta\) pixels, convolution with a kernel \(K\) shifts the feature map by the same amount: \[ K*(T_\delta\mathbf{x})=T_\delta(K*\mathbf{x}). \]

Equivariance preserves where; pooling can later create partial invariance. CNNs also build in locality (nearby pixels interact first), parameter sharing (the same detector works everywhere), hierarchical composition (local evidence builds into parts and objects), data efficiency (built-in assumptions constrain the hypothesis space), and multi-scale maps for dense tasks. A good inductive bias says which solutions should be easy to learn.

5.14 CNN limitations: global context is indirect

A triangular lattice of units over a row of patches, with red and blue paths meeting at layer 4
Figure 21: Two patches \(d=8\) positions apart. With \(3\times3\) convolutions the receptive field (RF) grows by 2 per layer, so the first unit that sees both is in layer 4; one self-attention layer connects them directly.

With kernel size \(k\), two inputs at distance \(d\) first interact after about \(d/(k-1)\) layers (\(8/2=4\) here). Long-range interaction therefore needs depth, large kernels, dilation, or pooling; repeated downsampling discards fine detail; fixed local mixing does not adapt its connectivity to the image; and strong locality can favour texture or shortcuts over global shape (Geirhos et al. 2019). Modern CNNs can nevertheless be very strong (Liu et al. 2022), and transformers introduce their own costs.

Part IIIRecap: Vision Transformers

6 Vision Transformers

6.1 Attention: content-dependent interaction

The scene split into patches with arcs from one pedestrian patch to other patches labelled with attention weights
Figure 22: The image is cut into \(7\times3\) patches, each becoming a token. The pedestrian’s query patch \(i\) attends most to the other people, wherever they are.

\[ \mathbf{z}'_i=\sum_{j}\alpha_{ij}\,\mathbf{v}_j, \qquad \sum_{j}\alpha_{ij}=1, \]

where \(i\) is the query token (patch), \(j\) ranges over all \(N\) tokens (including \(i\)), \(\mathbf{v}_j\) is the value vector — the content — of token \(j\), \(\alpha_{ij}\) the attention weight of \(i\) on \(j\), and \(\mathbf{z}'_i\) the updated vector of token \(i\). The weights depend on token content; interaction is global; geometry must be supplied through position information; and full attention costs \(O(N^2)\) token interactions.

6.2 From an image to a sequence of patches

A car image with a 14 by 14 patch grid, one patch flattened and projected, and the token sequence with a CLS token
Figure 23: Patchification in ViT-B/16: a \(224\times224\) image becomes \(14\times14=196\) patches of \(16\times16\) pixels; each patch is flattened to 768 numbers and projected by a shared learned matrix \(\mathbf{E}\); a class token and position embeddings are added.

\[ N=\frac{HW}{P^2}, \qquad \mathbf{z}_0=\big[\mathbf{x}_{\text{cls}};\,\mathbf{x}_p^{1}\mathbf{E};\,\dots;\,\mathbf{x}_p^{N}\mathbf{E}\big]+\mathbf{E}_{\text{pos}}\in\mathbb{R}^{(N+1)\times D}, \]

where \(H,W\) are the image height and width, \(P\) the patch side, \(N\) the number of patches, \(\mathbf{x}_p^{k}\) the flattened patch \(k\) (with \(P^2\cdot3\) values), \(\mathbf{E}\) the learned projection to the token width \(D\), \(\mathbf{x}_{\text{cls}}\) a learned class token, \(\mathbf{E}_{\text{pos}}\) learned position embeddings, \([\,\cdot\,;\,\cdot\,]\) stacking as rows, and \(\mathbf{z}_0\) the transformer input.

For ViT-B/16 at \(224^2\): \(P=16\), \(N=14\cdot14=196\), \(P^2\cdot3=768\) values per patch, and \(D=768\). \(D\) is a design choice (ViT-S uses 384, ViT-L 1024). Smaller patches preserve detail but increase \(N\) and the attention cost. The class token is a learnable global readout; averaging the patch tokens is an alternative.

6.3 The Vision Transformer pipeline

Pipeline from patches through embeddings and L transformer blocks to a classification head and a dense decoder
Figure 24: Patchify and project; add position embeddings and the class token; apply \(L\) transformer encoder blocks (\(L=12\) in ViT-B); read out. Classification uses the class token (or the mean of the patch tokens) and a linear head; dense prediction reshapes the patch tokens into a map for a decoder.

Here \(L\) is the number of encoder blocks and \(\mathbf{W}\) the weights of the linear head. Every block keeps the shape \((N+1)\times D\): self-attention mixes all tokens, then an MLP processes each token (Dosovitskiy et al. 2021).

6.4 Self-attention: query, key, value

Six token thumbnails, their query, key, and value vectors, and a 6 by 6 attention matrix with the pedestrian row highlighted
Figure 25: Self-attention on six tokens of the scene. The pedestrian’s row of the attention matrix puts most weight on the cyclist and the woman, so the new pedestrian token is mostly a mix of their values. Weights are illustrative.

\[ \mathbf{Q}=\mathbf{X}\mathbf{W}_Q, \quad \mathbf{K}=\mathbf{X}\mathbf{W}_K, \quad \mathbf{V}=\mathbf{X}\mathbf{W}_V, \qquad \mathbf{A}=\operatorname{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^{\top}}{\sqrt{d_k}}\right), \qquad \operatorname{Attn}(\mathbf{X})=\mathbf{A}\mathbf{V}, \tag{3}\]

where \(\mathbf{X}\in\mathbb{R}^{N\times D}\) holds the input tokens, one per row (\(\mathbf{x}_i\) is row \(i\)); \(\mathbf{W}_Q,\mathbf{W}_K,\mathbf{W}_V\) are learned projection matrices; \(\mathbf{Q},\mathbf{K},\mathbf{V}\) are the queries, keys, and values (rows \(\mathbf{q}_i,\mathbf{k}_i,\mathbf{v}_i\)); \(d_k\) is the query and key length; \(\mathbf{K}^\top\) is the transpose of \(\mathbf{K}\); \(\mathbf{A}\) is the \(N\times N\) matrix of attention weights; and \(\operatorname{Attn}(\mathbf{X})\) holds the new tokens (Vaswani et al. 2017).

  • The query \(\mathbf{q}_i\) is what token \(i\) seeks, the key \(\mathbf{k}_j\) what token \(j\) offers, the value \(\mathbf{v}_j\) what it passes on.
  • \(\mathbf{q}_i\cdot\mathbf{k}_j\) scores the compatibility of every pair, so \(\mathbf{Q}\mathbf{K}^\top\) is \(N\times N\).
  • Dividing by \(\sqrt{d_k}\) keeps the scores at a workable scale: with unit-variance entries, \(\mathbf{q}\cdot\mathbf{k}\) has variance \(d_k\), which would saturate the softmax.
  • The row-wise softmax makes each query’s weights positive and sum to one; output row \(i\) is a weighted mix of the values.

6.5 Multi-head attention

The scene with a query patch and four attention heat maps for heads 5, 6, 7, and 9, feeding a concatenation and output projection
Figure 26: Real attention maps of ViT-B/16, layer 9, for the same pedestrian query: four of the twelve heads attend to other people, the pedestrian’s own body, building façades, and the road and car.

\[ \operatorname{MHA}(\mathbf{X})=\operatorname{Concat}(\text{head}_1,\dots,\text{head}_h)\,\mathbf{W}_O, \]

where \(\mathbf{X}\) holds the input tokens, \(h\) is the number of heads (12 here), \(\text{head}_m\) is the output of head \(m\) with its own \(\mathbf{W}_Q,\mathbf{W}_K,\mathbf{W}_V\), \(\operatorname{Concat}\) places the heads side by side, and \(\mathbf{W}_O\) is a learned output projection. Heads provide separate learned subspaces, not guaranteed human-interpretable roles.

6.6 The transformer block

A vertical block diagram with LayerNorm, multi-head attention, an MLP, and two residual additions
Figure 27: A pre-norm transformer block: LayerNorm, multi-head attention, residual addition; LayerNorm, MLP \(D\to4D\to D\), residual addition.

\[ \mathbf{X}'=\mathbf{X}_\ell+\operatorname{MHA}\big(\operatorname{LN}(\mathbf{X}_\ell)\big), \qquad \mathbf{X}_{\ell+1}=\mathbf{X}'+\operatorname{MLP}\big(\operatorname{LN}(\mathbf{X}')\big), \]

where \(\mathbf{X}_\ell\) are the tokens entering block \(\ell\), \(\mathbf{X}_{\ell+1}\) those leaving it, \(\operatorname{LN}\) is LayerNorm, and the MLP maps the token width \(D\) to \(4D\) and back. Attention mixes information between tokens; the MLP mixes information between channels, independently at each token. Residual paths stabilize deep optimization, pre-normalization is common in modern variants, and position information prevents permutation ambiguity.

6.7 Hybrid and hierarchical vision models

A pipeline from an image through a conv stem, windowed tokens, patch merging, shifted window attention, and a multi-scale pyramid
Figure 28: A convolutional stem captures local detail and reduces resolution; attention runs inside local windows; patch merging concatenates each \(2\times2\) group of tokens and maps \(4C\to2C\); shifted windows let information cross window borders; the result is a feature pyramid for detection and segmentation.

Here \(H,W\) are the height and width of the token grid and \(C\) the channels per token. The Swin Transformer (Liu et al. 2021) combines three ideas: local windows reduce the attention cost (attention is computed only inside small windows, so the cost grows linearly with the number of tokens); shifted windows exchange information between windows; and a hierarchy — patch merging halves \(H,W\) and doubles \(C\) — produces multiple scales for detection and segmentation.

6.8 The backbone: a reusable feature extractor

An image feeding a backbone that feeds a detection head, a segmentation decoder, and a pose or tracking head
Figure 29: One backbone (ResNet, ConvNeXt, ViT, Swin), several heads: detection, segmentation, pose, and tracking.

A backbone outputs feature vectors or maps; the head maps them to a task representation. Pretraining can be supervised, self-supervised, or multimodal.

Classification is not enough

“Street scene, \(0.84\)” discards the object count, each object’s location and scale, their overlaps and relationships, and the uncertainty per object. Mapping an image to a set of objects changes both the prediction space and the evaluation protocol.

Part IVObject detection

7 The detection problem

7.1 Localization versus detection

Two versions of the scene, one with a single box, one with six labelled boxes
Figure 30: Localization predicts one box for one known object category. Detection must handle unknown categories and an unknown number of objects.

\[ \text{localization: } f_\theta(I)=(\mathbf{p},\mathbf{b}),\ \mathbf{b}\in\mathbb{R}^4; \qquad \text{detection: } f_\theta(I)=\{(\mathbf{p}_i,\mathbf{b}_i)\}_{i=1}^{N}, \]

where \(I\) is the input image, \(f_\theta\) the network with weights \(\theta\), \(\mathbf{p},\mathbf{p}_i\) class probabilities, \(\mathbf{b},\mathbf{b}_i\) boxes (four real numbers each), \(N\) the number of objects in the image, and \(i\) the object index. Detection adds a cardinality problem: the model must decide which candidates correspond to real objects.

7.2 Bounding-box parameterization

The car with its box annotated with corners, centre, width 308, and height 152
Figure 31: The car’s box in the \(1672\times941\) image, with the origin at the top left and \(y\) pointing down.

\[ (x_1,y_1,x_2,y_2)=(558,469,866,621) \;\Longleftrightarrow\; (c_x,c_y,w,h)=(712,545,308,152), \]

where \((x_1,y_1)\) is the top-left corner, \((x_2,y_2)\) the bottom-right corner, \((c_x,c_y)\) the box centre, and \(w,h\) the box width and height, all in pixels. Dividing by the image width and height \((W,H)=(1672,941)\) gives \((0.426,0.579,0.184,0.162)\). Normalize coordinates by the image size, enforce \(w,h>0\) through a suitable transform, and regress relative offsets, which are easier to learn across scales.

7.3 The detection output

A detector emits a fixed budget of predictions

\[ \hat{\mathcal{Y}}=\{(\hat{\mathbf{p}}_i,\hat{\mathbf{b}}_i)\}_{i=1}^{K}, \qquad \hat{\mathbf{p}}_i\in[0,1]^{C+1}, \qquad \hat{\mathbf{b}}_i\in\mathbb{R}^4, \]

where the hat marks predicted values, \(i\) indexes predictions, \(K\) is the (fixed) number of predictions, \(C\) the number of object classes (plus one “no object” or background class), \(\hat{\mathbf{p}}_i\) the class probabilities, and \(\hat{\mathbf{b}}_i\) the box. The number of true objects \(N\) varies, and usually \(K\gg N\); assignment and filtering select the detections. Producing predictions is easy to tensorize — deciding which ones count is the central difficulty.

7.4 Detection as multitask learning

The scene with three numbered candidate boxes above a table of IoU, class head output, box head status, and loss
Figure 32: Three candidates (dashed) and the box head’s refinements (solid). Candidates 1 and 2 match the car and a person and are refined; candidate 3 is background and receives no box loss.

\[ \mathcal{L}_i=\mathcal{L}_{\text{cls}}(\mathbf{p}_i,c_i)+\lambda\,\mathbf{1}[c_i\neq\varnothing]\,\mathcal{L}_{\text{box}}(\mathbf{b}_i,\mathbf{b}_i^{*}), \tag{4}\]

where \(\mathcal{L}_i\) is the loss of candidate \(i\), \(\mathcal{L}_{\text{cls}}\) a classification loss, \(\mathcal{L}_{\text{box}}\) a box-regression loss, \(\mathbf{p}_i\) the class probabilities, \(c_i\) the assigned true class, \(\varnothing\) background, \(\mathbf{1}[\cdot]\) equal to 1 if its argument is true and 0 otherwise, \(\mathbf{b}_i\) the predicted box, \(\mathbf{b}_i^{*}\) the matched true box, and \(\lambda\) a loss weight. Every candidate learns foreground versus background; only matched positives receive box supervision; the loss scales must be balanced.

7.5 Intersection over Union

The car with overlapping predicted and true boxes, and three examples with IoU 0.18, 0.56, and 0.89
Figure 33: IoU between Faster R-CNN’s box for the car and a hand-drawn true box: \(45\,979/50\,011=0.92\). Shifting or scaling the true box gives IoU \(0.18\), \(0.56\), and \(0.89\).

\[ \operatorname{IoU}(A,B)=\frac{|A\cap B|}{|A\cup B|}\in[0,1], \]

where \(A\) and \(B\) are two boxes (for example the true box \(B_{\text{gt}}\) and the predicted box \(B_{\text{pred}}\)), \(|\cdot|\) is an area in pixels², and \(\cap,\cup\) are intersection and union. IoU is \(0\) for disjoint boxes and \(1\) for identical ones; it is scale invariant and used both for matching and for evaluation.

7.6 Precision and recall for detection

Three crops with true-positive and false-positive boxes above a table of thresholds with TP, FP, FN, precision, and recall
Figure 34: Matching before counting on the scene’s 11 true objects. False positives include a duplicate box (\(0.80\)) and a detection of background (\(0.21\)). The table sweeps the score threshold.

A prediction is a true positive (TP) when its class is correct, its IoU with a true object is at least \(\tau\) (the IoU threshold, e.g. \(0.5\)), and that object is not already matched; otherwise it is a false positive (FP). True objects left unmatched are false negatives (FN, missed objects). Then

\[ \mathrm{P}=\frac{\mathrm{TP}}{\mathrm{TP}+\mathrm{FP}}, \qquad \mathrm{R}=\frac{\mathrm{TP}}{\mathrm{TP}+\mathrm{FN}}, \]

where P is the precision — how accurate the predictions are — and R the recall — how good the detector is at finding all objects. On the scene, a score threshold of \(0.995\) gives P \(=1.00\) and R \(=7/11=0.64\); a threshold of \(0.05\) gives R \(=1.00\) but P \(=11/21=0.52\). Raising the threshold usually raises precision and lowers recall; duplicates count as false positives. A detector is therefore evaluated over a confidence sweep: the area under the precision–recall curve is the average precision (AP), and its mean over classes is the mAP (Everingham et al. 2010; Lin et al. 2014).

8 Two-stage detectors

8.1 Why not slide a classifier everywhere?

The scene covered by red windows, with three example windows and their car scores
Figure 35: Running an ImageNet ResNet-18 on 1611 windows of three sizes takes 29.4 s on a CPU; 116 windows fire on the one car and 1383 are background.

Adjacent windows repeat almost identical computation; object size and aspect ratio are unknown; one object activates many overlapping windows; and background windows vastly outnumber objects. The question that drives everything below: which computation can be shared across all windows?

8.2 Proposals, then decisions

A pipeline: image, backbone, proposals, RoI features, class plus box, detections
Figure 36: A two-stage detector: stage 1 asks where? and produces proposals; stage 2 asks what exactly?, pools features for each region of interest (RoI), and outputs a class and a box.

Object detectors come in two families: two-stage and one-stage. A two-stage detector applies expensive per-object reasoning only to a sparse proposal set, at the cost of extra latency and pipeline complexity. Its key component is the region-proposal step.

8.3 Region proposals

Three stages of hierarchical region merging on the scene and the resulting proposal boxes
Figure 37: A simplified selective search on the scene: over-segment into 1147 small regions of similar colour; repeatedly merge the most similar neighbours (by colour histograms, size, and how well they fill their joint box); take the box of every region as a proposal. With 4 segmentation scales this gives 3576 boxes, whose best boxes cover 7 of 9 objects at IoU \(\ge0.5\).

A region-proposal algorithm such as selective search (Uijlings et al. 2013) or EdgeBoxes (Zitnick and Dollár 2014) returns a few thousand class-agnostic boxes that probably contain an object; it never says which class — stage 2 decides. The goal is high recall with few boxes (thousands, not millions of windows), using generic cues only: colour, texture, edges, closed contours. Most proposals are background, which the detector rejects. Selective search takes about 2 s per image on a CPU.

8.4 Non-maximum suppression

A car covered with 79 red boxes and the same car with one green box, above a table of scores, IoUs, and fates
Figure 38: 79 raw “car” boxes with score above 0.05 around one car; NMS at \(\tau=0.5\) keeps one. Over the whole image and all classes, 3394 raw boxes become 636.

Detectors produce many overlapping boxes per object. Non-maximum suppression (Neubeck and Van Gool 2006) keeps one:

  1. select the highest-scoring box (score = detector confidence);
  2. remove every remaining box of the same class whose IoU with it exceeds the threshold \(\tau_{\text{nms}}\);
  3. repeat until no candidates remain.
A cyclist crop with overlapping person and bicycle boxes and the outcome of NMS
Figure 39: The cyclist and the bicycle overlap with IoU \(0.31\): per-class NMS keeps both, but class-agnostic NMS at \(\tau=0.3\) deletes the bicycle. The same happens within one class in crowds.

NMS has limitations: real objects may overlap strongly in crowds; one threshold \(\tau\) does not fit every class and scale; and NMS is a discrete step, not learned end to end.

8.5 R-CNN: a CNN on every region proposal

Four steps: region proposals, warped crops, a CNN per crop, and per-class SVMs and box regressors, ending in detections
Figure 40: R-CNN: about 2000 class-agnostic proposals from selective search; each is cropped and warped to \(227\times227\) (the car is squashed, the traffic light stretched); a CNN runs on every crop; one linear SVM per class on the 4096-d feature and a per-class box regressor classify and refine; per-class NMS gives one box per object.

R-CNN (Girshick et al. 2014) is trained in separate stages: fine-tune the CNN on warped crops, fit one SVM per class on its (cached) features, then fit the box regressors — three separate objectives. Its bottleneck is step 3: about 2000 CNN passes per image recompute the same convolutions on overlapping crops, about 47 s per image with VGG-16 on a GPU.

8.6 Fast R-CNN: one CNN pass, then pool every proposal

Pipeline: image with proposals, a shared feature map, RoI pooling into 7 by 7 bins, and two sibling heads for class and box
Figure 41: Fast R-CNN: the CNN runs once on the whole image (one \(47\times84\) feature map at stride 16, shared by all RoIs); each proposal is projected onto the map (box coordinates divided by 16); RoI pooling max-pools it into \(7\times7\) bins whatever its size; two sibling heads output a softmax over \(K+1\) classes and per-class box offsets.

Fast R-CNN (Girshick 2015) shares the convolutions and is trained jointly, given the proposals, with one multitask loss per RoI:

\[ L=\mathcal{L}_{\text{cls}}(\mathbf{p},u)+\lambda\,[u\ge1]\,\mathcal{L}_{\text{loc}}(\mathbf{t}^{u},\mathbf{v}), \qquad \mathcal{L}_{\text{cls}}=-\log p_u, \qquad \mathcal{L}_{\text{loc}}=\sum_{i\in\{x,y,w,h\}}\operatorname{smooth}_{L_1}\!\big(t_i^{u}-v_i\big), \]

where \(\mathbf{p}\) is the softmax over \(K+1\) classes (\(K\) object classes plus background), \(u\) the true class (\(0\) for background), \(\mathbf{t}^{u}\) the predicted box offsets for class \(u\), \(\mathbf{v}\) the target offsets, \(i\) one of \(x,y,w,h\), \([u\ge1]\) equal to 1 for an object and 0 for background, and \(\lambda\) a balance weight (1 in the paper). The robust loss \(\operatorname{smooth}_{L_1}(z)\) equals \(0.5z^2\) if \(|z|<1\) and \(|z|-0.5\) otherwise.

Shared convolutions bring the cost from 47 s to about 0.32 s per image (VGG-16), with no SVMs. The bottleneck is now the proposals: selective search still takes about 2 s per image. The next step is to make the proposals learnable.

8.7 Anchor boxes

The car with nine anchor boxes of different sizes and shapes centred on one grid cell
Figure 42: Anchors at one cell of a stride-16 grid: three sizes (64, 128, 256 px) times three aspect ratios — 9 anchors per cell, \(104\times59\times9=55\,224\) over the image. The best anchor for the car is 256 px at \(1:2\), with IoU \(0.71\).

Each location owns reference boxes \(\mathbf{a}=(c_x^a,c_y^a,w_a,h_a)\) with several scales and aspect ratios (Ren et al. 2015; Liu et al. 2016). The head predicts objectness, class, and offsets \((t_x,t_y,t_w,t_h)\), decoded as

\[ \hat c_x=c_x^a+t_x w_a, \qquad \hat c_y=c_y^a+t_y h_a, \qquad \hat w=w_a e^{t_w}, \qquad \hat h=h_a e^{t_h}, \tag{5}\]

where \((c_x^a,c_y^a)\) is the anchor centre, \(w_a,h_a\) its width and height, and \((\hat c_x,\hat c_y,\hat w,\hat h)\) the centre and size of the predicted box \(\hat{\mathbf{b}}\). The exponential keeps the size positive.

Worked example — The car against its best anchor

With \(\mathbf{a}=(712,552,362,181)\) and the car at \((712,545,308,152)\), inverting Equation 5 gives \[ t_x=0,\quad t_y=\tfrac{545-552}{181}=-0.039,\quad t_w=\ln\tfrac{308}{362}=-0.162,\quad t_h=\ln\tfrac{152}{181}=-0.175, \] small targets of order \(0.1\) whatever the size of the object.

8.8 Anchor matching

The car covered by a grid of coloured dots, with example anchors labelled negative, ignore, and positive
Figure 43: Each dot is one cell, coloured by its best anchor’s IoU with the car. Over the whole image and its 11 objects, the 55 224 anchors split into 22 positives, 1607 ignored, and 53 595 negatives.

\[ y(\mathbf{a},\mathbf{g})= \begin{cases} +1 & \operatorname{IoU}(\mathbf{a},\mathbf{g})\ge\tau_+,\\ 0 & \operatorname{IoU}(\mathbf{a},\mathbf{g})<\tau_-,\\ \perp & \text{otherwise}, \end{cases} \]

where \(\mathbf{a}\) is an anchor, \(\mathbf{g}\) a ground-truth box, \(y(\mathbf{a},\mathbf{g})\) the training label of \(\mathbf{a}\) (\(+1\) object, \(0\) background, \(\perp\) ignored, no label), and \(\tau_+,\tau_-\) the positive and negative IoU thresholds (\(0.7\) and \(0.3\) in the Faster R-CNN RPN). Thresholds are design choices, not universal constants; ignored anchors contribute no classification loss; and the assignment defines the labels seen during training.

8.9 Faster R-CNN: Fast R-CNN + a learned RPN

Faster R-CNN pipeline with a shared backbone, RPN objectness map, top proposals, RoIAlign crops, class and box outputs, and final detections
Figure 44: Faster R-CNN with ResNet-50-FPN on the scene. (1) The backbone and FPN are computed once and shared. (2) The region proposal network (RPN) predicts, for \(k\) anchors at every cell, an objectness score and 4 offsets: 257 796 anchors are scored and 1000 class-agnostic boxes survive NMS. (3) RoIAlign pools a \(7\times7\times256\) feature per proposal. (4) The second stage classifies and refines each RoI.

Faster R-CNN (Ren et al. 2015) replaces selective search by a learned region proposal network that reuses the detector’s feature map. Per cell, \(k\) anchors give objectness plus 4 offsets, and NMS keeps the top \(N\) proposals (\(k=9\), \(N=300\) in the paper). Proposals are class-agnostic; the second stage classifies and refines each RoI. Proposals now take about 10 ms instead of about 2 s, and the whole detector runs at about 5 frames per second.

8.10 From R-CNN to Faster R-CNN: what changed

A table of the four steps of R-CNN, Fast R-CNN, and Faster R-CNN, with a log-scale bar chart of test time and their mAP
Figure 45: The four steps of the three detectors, their test time per image, and their PASCAL VOC 2007 mAP (all VGG-16): R-CNN 47 s and 66.0; Fast R-CNN 0.32 s plus about 2 s of proposals and 66.9; Faster R-CNN 0.2 s in total and 69.9.
Table 5: Each step removed the slowest part: the CNN moved before the cropping (Fast), then the proposals were learned (Faster).
Proposals CNN Per-region features Training
R-CNN (2014) selective search, CPU on every warped crop — CNN → SVMs → regressors
Fast R-CNN (2015) selective search, CPU once per image RoI pooling one multitask loss
Faster R-CNN (2015) learned RPN on shared features once per image RoI pooling (RoIAlign today) RPN and detector jointly

9 One-stage detectors

Three brightened copies of the scene for pyramid levels P3, P4, and P5, and the final detections
Figure 46: RetinaNet’s dense head on the scene. The same head runs at every location of every pyramid level, predicting \(K\) class scores and 4 box offsets per anchor: \(P_3\) (stride 8, 145 152 predictions) fires on the small pedestrians, \(P_4\) (stride 16, 36 288) on the bus and the cyclist, \(P_5\) (stride 32, 9072) on the car — 193 374 anchors in total with \(P_6\) and \(P_7\).

A one-stage detector (Liu et al. 2016; Lin, Goyal, et al. 2017) has no explicit proposal or RoI stage: it predicts densely at several resolutions in one pass, with \(K\) the number of classes. This gives low latency and simple batching, and the multi-scale maps serve different object sizes — but dense supervision creates severe class imbalance.

9.1 YOLO

The scene with a coarse grid and the car's box in the cell containing its centre
Figure 47: The historical YOLOv1 view: the grid cell containing an object’s centre is responsible for predicting it.

YOLO (Redmon et al. 2016) maps pixels directly to an output tensor of size

\[ S\times S\times(B\cdot5+C), \]

where \(S\) is the grid size, \(B\) the number of boxes per cell, \(5\) the values per box (\(x,y,w,h\), confidence), and \(C\) the number of classes. One network maps pixels directly to detections and reasons with global image context. Modern YOLO variants use different heads and assignment rules.

9.2 The problem with one-stage detectors

The scene with grey negative and green positive anchors, and boxes counting negatives and positives
Figure 48: RetinaNet’s anchors on the scene: 192 556 negatives — mostly easy background (sky, road, walls) with almost no useful signal — against 288 positives, about 1 positive for every 669 negatives.

A one-stage detector classifies every anchor — here 193 374 anchors densely cover the image — which creates a foreground–background imbalance. Two-stage detectors avoid it by filtering first: about 2000 proposals, then mini-batches sampled with about 25% positives.

9.3 Motivation of the focal loss

The cross-entropy curve with a hard and an easy example marked, and the total losses of many hard and easy examples
Figure 49: Cross-entropy as a function of \(p_t\). A very hard example (\(p_t=0.1\)) costs 2.30; a well-classified one (\(p_t=0.9\)) costs 0.105. 100 hard examples add 230; 100 000 easy ones add about 10 500 — about 46 times more, although each is almost correct.

Recall the cross-entropy of the true class:

\[ \operatorname{CE}(p_t)=-\log p_t, \qquad p_t=\begin{cases}p & \text{if } y=1,\\ 1-p & \text{otherwise},\end{cases} \]

where \(p\) is the predicted probability of “object”, \(y\in\{0,1\}\) the true label, and \(p_t\) the probability given to the true class: a hard example has small \(p_t\) (a mistake), an easy one has \(p_t\) close to 1. On the scene, RetinaNet’s 191 102 easy negatives, each with \(p_t\approx0.9994\), still make 84.2% of the total cross-entropy, while the positives make only 3.6%. Many tiny losses dominate the total loss and its gradient. How can we down-weight the examples that are already well classified?

9.4 The focal loss

Scene with example anchors, a bar chart of loss shares under cross-entropy and focal loss, and loss curves for several gamma values
Figure 50: A sample of RetinaNet anchors and the share of the total loss of each group. With cross-entropy, easy negatives make 84.2% of the loss; with the focal loss (\(\alpha=0.25\), \(\gamma=2\)), positives make 72.0%, hard negatives 27.2%, and easy negatives 0.9%.

\[ \operatorname{FL}(p_t)=-\alpha_t\,(1-p_t)^{\gamma}\log p_t, \]

where \(p_t\) is the probability of the true class, \(\alpha_t\) a class weight, \(\gamma\ge0\) the focusing parameter, and \((1-p_t)^\gamma\) the modulating factor (Lin, Goyal, et al. 2017). The factor is near 0 for already-correct examples (\(p_t\to1\)) and near 1 for mistakes, so it suppresses the gradients of easy examples. With \(\gamma=0\) the focal loss is weighted cross-entropy; larger \(\gamma\) focuses learning on hard mistakes. For an easy negative with \(p_t=0.9994\) and \(\gamma=2\), the factor is \((0.0006)^2\approx3.6\times10^{-7}\). The focal loss enabled accurate dense one-stage detection in RetinaNet.

10 Modern detectors with transformers

10.1 Detection as set prediction

Six prediction slots connected by coloured lines to four targets and a no-object node
Figure 51: Six prediction slots and four targets. Each target gets exactly one slot; the rest learn “no object” — here \(q_2\) duplicates the car and \(q_4\) is background, so both are matched to \(\varnothing\). There are no anchors and no NMS.

DETR (Carion et al. 2020) predicts a fixed-size unordered set of \(N\) slots (\(N=100\)), where \(q_i\) is prediction slot \(i\), \(g_j\) ground-truth object \(j\), \(\varnothing\) the “no object” class, and \(p\) a predicted class score. Each object is matched to exactly one slot; unmatched slots are trained as “no object”. Because a duplicate is penalized, duplicate removal is part of the learning objective — no NMS is needed.

10.2 DETR

The DETR pipeline: image, CNN tokens with positional encoding, transformer encoder and decoder with object queries, and class and box heads
Figure 52: A ResNet-50 turns the image into a \(24\times42\times2048\) map, projected to 1008 tokens of width \(d=256\) with positional encodings; a transformer encoder lets every token attend to every token; the decoder turns \(N=100\) learned object queries into one box per object, and the other queries predict \(\varnothing\). Attention and outputs are illustrative.

Here \(H,W\) are the image height and width, \(d\) is the token dimension, and \(q_i\) is learned object query \(i\). Global attention connects distant image regions; learned queries compete for objects in parallel; and a bipartite set loss trains the complete pipeline. The original DETR converges slowly and struggles with small objects; Deformable DETR (Zhu et al. 2021) addresses both.

10.3 Hungarian matching

A 6 by 4 table of costs with four green cells marking the optimal assignment
Figure 53: Pairwise matching costs between 6 slots \(q_i\) (rows) and 4 targets \(g_j\) (columns). The optimal one-to-one assignment (green) has total cost \(-2.8\), the minimum over all 360 assignments; \(q_2\) and \(q_4\) go to \(\varnothing\).

\[ \mathcal{C}(i,j)=-p_i(c_j)+\lambda_1\lVert\mathbf{b}_i-\mathbf{b}_j\rVert_1+\lambda_g\mathcal{L}_{\text{GIoU}}(\mathbf{b}_i,\mathbf{b}_j), \qquad \hat\sigma=\arg\min_{\sigma}\sum_{j}\mathcal{C}\big(\sigma(j),j\big), \]

where \(\mathcal{C}(i,j)\) is the cost of slot \(q_i\) for target \(g_j\), \(c_j\) the class of \(g_j\), \(p_i(c_j)\) slot \(i\)’s score for \(c_j\), \(\mathbf{b}_i,\mathbf{b}_j\) the predicted and target boxes, \(\lambda_1,\lambda_g\) weights, \(\mathcal{L}_{\text{GIoU}}\) one minus the generalized IoU (Rezatofighi et al. 2019) (an IoU that still gives a useful signal when boxes do not overlap), \(\sigma\) an assignment \(j\mapsto\sigma(j)\), and \(\hat\sigma\) the cheapest one, found by the Hungarian algorithm (Kuhn 1955). For \(q_3\) against \(g_1\) (the car) with \(\lambda_1=5\), \(\lambda_g=2\): \(-0.96+5\cdot0.009+2\cdot0.06=-0.80\). Match first; then compute the class and box losses on the selected pairs.

Part VSegmentation

11 Semantic segmentation

The scene with building, road, and sidewalk regions overlaid
Figure 54: Semantic segmentation assigns one class to every pixel: building, road, sidewalk.

\[ \mathbf{z}=f_\theta(\mathbf{x})\in\mathbb{R}^{H\times W\times C}, \qquad \hat y_{ij}=\arg\max_{c}\,z_{ijc}, \]

where \(\mathbf{x}\) is the input image, \(f_\theta\) the network with weights \(\theta\), \(\mathbf{z}\) the per-pixel class scores, \(H,W\) the image height and width, \(C\) the number of classes, \(z_{ijc}\) the score of class \(c\) at pixel \((i,j)\), \(\hat y_{ij}\) the predicted label of pixel \((i,j)\), and \(\arg\max_c\) selects the highest-scoring class. The output stays aligned with the input; “stuff” (road, sky) and “things” (car, person) share one label map; and same-class objects are not separated into instances. Classification asks what; segmentation asks what at each location.

11.1 Naive patch classification

Two overlapping patches, each with a centre dot pointing to a centre label
Figure 55: Classify the centre pixel of a crop, for every pixel: neighbouring patches overlap almost completely.

Training a classifier on a crop around each pixel (Farabet et al. 2013) is correct but wasteful: neighbouring patches overlap almost completely and their features are recomputed again and again; small patches miss context while large ones multiply the cost; and a full image needs about \(H\times W\) classifier calls. The missing ingredient is shared computation.

11.2 Fully convolutional networks

Pipeline: image, shared features, class-score maps, the upsampled map, and the final label map
Figure 56: An FCN on the scene: shared convolutions turn a \(432\times768\times3\) image into a \(54\times96\times2048\) map, computed once (one vector per \(8\times8\) pixels); a \(1\times1\) convolution gives 21 class scores per cell; bilinear upsampling \(\times8\) returns to full resolution; the arg max gives the label map.

A fully convolutional network (Long et al. 2015) replaces the classifier’s dense layers by convolutions, so spatial score maps emerge in one forward pass. Here \(H,W\) are the image height and width, \(h,w\) the feature-map height and width (\(8\times\) smaller), and \(C=21\) the number of classes. The network accepts variable image sizes, shares features across locations, and trades resolution for receptive field. Dense prediction does not require dense repetition.

11.3 Encoder–decoder design

Encoder activation maps C2 to C5 shrinking, followed by decoder label maps growing back to full resolution
Figure 57: The encoder (ResNet-50 activations, stride 4 to 32) reduces \(432\times768\) to \(14\times24\); the decoder (an FCN’s prediction at each resolution) upsamples back through \(H/16\), \(H/8\), and \(H/4\) to the full mask.

Here \(H\times W\) is the input height × width, \(H/s\) a map \(s\) times smaller than the input, and \(C_2\)–\(C_5\) the ResNet stages. The encoder answers what?: downsampling enlarges the receptive field and builds invariance but discards precise location. The decoder answers where?: upsampling restores spatial resolution but must reconstruct boundaries from compressed features. Segmentation needs both global context and pixel-level localization.

11.4 Upsampling methods

An 8 by 8 score patch and four 16 by 16 upsampled versions
Figure 58: An \(8\times8\) patch of FCN “car” scores upsampled to \(16\times16\): nearest (copy each value \(2\times2\); blocky, no parameters), bilinear (weighted average of neighbours; smooth), transposed convolution (learned kernel, stride 2; with kernel 3, each output pixel receives 1, 2, or 4 inputs, which causes checkerboard artefacts), and resize followed by a \(3\times3\) convolution (a robust default).

Upsampling increases sampling density; it cannot recover detail that the encoder never preserved (Dumoulin and Visin 2016; Odena et al. 2016).

11.5 Skip connections recover detail

A fine and a coarse activation map above a detailed and a blobby segmentation result
Figure 59: An early map \(C_2\) (\(H/4\)) keeps edges and exact positions; a deep map \(C_5\) (\(H/32\)) encodes class and context. Decoding the same FCN’s scores with fine detail (stride 8) follows the legs, the wheel, and the dog; decoding from \(H/32\) only gives blobs.

Here \(H\) is the input height, and \(H/4\), \(H/32\) denote maps 4 and 32 times smaller. Early maps retain edges, corners, and accurate coordinates; deep maps encode class and broad context; concatenation or addition lets the decoder use both. Feature sizes must be aligned by padding, cropping, or resizing (Equation 2). Unlike ResNet’s residual links, which mainly ease optimization within one scale, these links bridge scales.

11.6 U-Net

A U-shaped diagram of feature maps with horizontal copy and concatenate arrows
Figure 60: U-Net: a contracting path and a symmetric expanding path, with encoder maps copied and concatenated (cyan) to the upsampled decoder maps of the same resolution (orange).

In the figure, \(112^2\times64\) denotes a \(112\times112\) map with 64 channels, and “+dec.” adds the decoder’s channels. U-Net (Ronneberger et al. 2015) has a symmetric encoder and decoder; its skip features are concatenated, not merely added; and it localizes well with limited annotated data, which made it the standard in biomedical imaging. Modern U-Nets add padding, normalization, and residual blocks. The enduring idea: pair semantics with same-scale detail.

11.7 DeepLab: context at multiple scales

The scene with dilated sampling points, five parallel branches, and the resulting label map
Figure 61: DeepLabV3 on the scene. Parallel branches — a \(1\times1\) convolution, three \(3\times3\) atrous convolutions with rates 12, 24, and 36 at stride 8 (taps 96, 192, and 288 pixels apart), and image pooling — are concatenated and projected into dense scores.

Atrous (dilated) convolution inserts gaps into the kernel:

\[ y[p]=\sum_{k}w[k]\,x[p+r k], \]

where \(x,y\) are the input and output feature maps, \(p\) an output position, \(k\) a kernel tap (\(-1,0,1\) for a size-3 kernel), \(w[k]\) a kernel weight, and \(r\) the rate, the gap between taps (\(r=1\) is an ordinary convolution). It enlarges the field of view without another pooling step. Running several rates in parallel (atrous spatial pyramid pooling) captures objects at different scales (Chen et al. 2017), and a light decoder can sharpen boundaries (Chen et al. 2018).

11.8 Segmentation metrics

A two by two grid labelled TP, FP, FN, and TN
Figure 62: For each class, over all pixels: true positives, extra pixels (FP), missed pixels (FN), and true negatives.

\[ \text{pixel accuracy}=\frac{\sum_c\mathrm{TP}_c}{|\Omega|}, \qquad \mathrm{IoU}_c=\frac{\mathrm{TP}_c}{\mathrm{TP}_c+\mathrm{FP}_c+\mathrm{FN}_c}, \qquad \mathrm{mIoU}=\frac1C\sum_{c=1}^{C}\mathrm{IoU}_c, \]

where \(c\) is a class, \(C\) the number of classes, \(\mathrm{TP}_c\) the class-\(c\) pixels predicted as \(c\), \(\mathrm{FP}_c\) the other pixels predicted as \(c\), \(\mathrm{FN}_c\) the class-\(c\) pixels missed, and \(\Omega\) the set of all pixels, with \(|\Omega|\) their count. Accuracy can look excellent when the background dominates; mIoU gives each class equal weight. A model that predicts only “road” on images that are 70% road reaches 70% pixel accuracy, but its IoU is \(0\) for every other class.

12 Instance segmentation

The scene with separate masks and labels for two people, a car, and a bus
Figure 63: Each countable object receives its own mask and identity: person 1, person 2, car 1, bus 1.

\[ \big\{(c_k,s_k,\mathbf{b}_k,\mathbf{M}_k)\big\}_{k=1}^{K}, \]

where \(k\) is the instance index, \(K\) the number of instances, \(c_k\) the class, \(s_k\) the confidence score, \(\mathbf{b}_k\) the box, and \(\mathbf{M}_k\) a binary mask of the object’s pixels (Hariharan et al. 2014). Each countable thing receives an identity, overlapping objects remain separate, masks capture shape while boxes help localize proposals, and “stuff” is usually left to a semantic branch. Instance segmentation predicts classes and individuals.

12.1 Mask R-CNN

Mask R-CNN pipeline: feature map, proposals, RoIAlign grid, class and box head, a 28 by 28 person mask, and the scene with masks
Figure 64: Mask R-CNN on the scene: backbone and FPN features, RPN proposals (top 40 of about 1000), RoIAlign (\(7\times7\) bins, bilinear samples, no rounding), the class and box head, and a parallel mask head — a small FCN — predicting a \(28\times28\) mask per RoI, pasted back into its box.

Mask R-CNN (He et al. 2017) adds one extra branch to Faster R-CNN: Faster R-CNN supplies proposals, classes, and boxes, and a parallel FCN predicts an \(m\times m\) mask for each RoI, where \(m\) is the mask side (28 here) and the box is given by its top-left and bottom-right corners \((x_1,y_1)\) and \((x_2,y_2)\). The mask uses a sigmoid per pixel and a pixel-wise binary cross-entropy loss, and detection and masks share the backbone features. RoIAlign replaces RoI pooling: it samples each bin by bilinear interpolation instead of rounding coordinates to the feature grid, which matters when the output is a boundary rather than a box.

Part VIPose estimation and tracking

13 Pose estimation

The scene with a skeleton of joints and limbs over the walking woman
Figure 65: 2D keypoints joined by anatomical links.

Pose estimation predicts a structured set of landmarks for a person or object:

\[ \mathcal{K}=\{(x_j,y_j,v_j)\}_{j=1}^{J}, \]

where \(\mathcal{K}\) holds the keypoints of one person, \((x_j,y_j)\) is the image position of joint \(j\), \(v_j\) records its visibility or confidence, and \(J\) is the number of joints (17 in COCO (Lin et al. 2014)). 2D pose gives keypoints in image coordinates; 3D pose gives joints in camera or world coordinates. A fixed skeleton graph connects related joints, and multiple people add a second problem: assigning joints to identities. DeepPose (Toshev and Szegedy 2014) regressed joint coordinates directly; modern methods predict one map per joint.

13.1 Keypoint R-CNN: one more head on Mask R-CNN

Mask R-CNN pipeline with a new keypoint head producing 17 joint maps, a left-knee map, and the decoded skeleton on the scene
Figure 66: Keypoint R-CNN on the scene. Steps 1–4 are Mask R-CNN unchanged (shared features, proposals, RoIAlign, box and mask heads). Step 5, the only new part, is a keypoint head: a small FCN on the same RoI features (8 convolutions \(3\times3\), a deconvolution, \(\times2\) upsampling) that outputs \(K=17\) maps of \(56\times56\), one per joint. Step 6 decodes each map: take the arg-max cell, then map it from the box back to the image.

The decoded joint position is

\[ \hat x=x_1+\big(\hat u+\tfrac12\big)\frac{w}{56}, \qquad \hat y=y_1+\big(\hat v+\tfrac12\big)\frac{h}{56}, \]

where \((x_1,y_1)\) is the top-left corner of the person box, \(w,h\) its width and height, \((\hat u,\hat v)\) the column and row of the arg-max cell of a \(56\times56\) map, and \((\hat x,\hat y)\) the decoded joint in image pixels. For the woman’s left knee, the box is \(x_1=1378\), \(y_1=435\), \(w=121\), \(h=258\) and the arg max is \((\hat u,\hat v)=(18,38)\), so \(\hat x=1378+18.5\cdot121/56=1418\) px and \(\hat y=435+38.5\cdot258/56=612\) px. Repeating this for all 17 maps gives one skeleton per box.

This is a top-down method: detect people first, then estimate each person’s pose inside its box (He et al. 2017). A missed person cannot be recovered, and the cost grows with the number of people. Bottom-up methods such as OpenPose (Cao et al. 2017) instead detect all joints in the image and group them into people.

14 Multi-object tracking

The scene with three boxes labelled ID 3, ID 7, and ID 9 and trails showing their past positions
Figure 67: The same identities — ID 3, ID 7, ID 9 — followed from the past to the present.

Given detections over a video, multi-object tracking estimates trajectories

\[ \mathcal{T}_i=\big\{(t,\mathbf{b}^{i}_t,c_i,\mathrm{ID}_i)\big\}_{t=t_s}^{t_e}, \]

where \(\mathcal{T}_i\) is the trajectory of object \(i\), \(t\) the frame index, \(\mathbf{b}^i_t\) its box at frame \(t\), \(c_i\) its class, \(\mathrm{ID}_i\) its identity label, and \(t_s,t_e\) the first and last frames of the track. A tracker must localize each object at each time, preserve a stable identity through motion and occlusion, start and terminate tracks as objects enter or leave, and be diagnosed for false or missed tracks, fragmentation, and identity switches (Milan et al. 2016).

14.1 Tracking by detection

Two copies of the scene with detections and predicted tracks, a 5 by 5 cost matrix with four circled matches, and the five steps
Figure 68: One step of tracking by detection. (1) Detections \(d_j\) at frame \(t\) (white boxes). (2) Tracks \(T_i\) predicted from \(t-1\) (dashed boxes \(\hat{\mathbf{b}}_i\); frame \(t-1\) is simulated). (3) Cost \(c_{ij}=1-\operatorname{IoU}(\hat{\mathbf{b}}_i,d_j)\), with pairs of IoU below 0.3 gated out (×). (4) Minimum-cost one-to-one matches: \(T_5\), behind the pole, and \(d_5\), the dog, stay unmatched. (5) Update: matched tracks are corrected by their detection; the unmatched detection starts a tentative new track; the unmatched track is kept briefly and deleted after repeated misses.

SORT (Bewley et al. 2016) runs a detector on every frame and links the detections over time:

  1. detect objects \(d_j\) at frame \(t\);
  2. predict each track \(T_i\) forward, giving a box \(\hat{\mathbf{b}}_i\) (SORT uses a constant-velocity Kalman filter);
  3. gate and build the cost matrix \(c_{ij}=1-\operatorname{IoU}(\hat{\mathbf{b}}_i,d_j)\), removing implausible pairs;
  4. find the minimum-cost one-to-one assignment with the Hungarian algorithm — the same tool as DETR’s matching;
  5. update each track’s state and lifecycle.

A simple online loop becomes a tracker when the association and lifecycle rules are explicit. Adding appearance features to the cost, as in Deep SORT (Wojke et al. 2017), helps recover identities after crossings and short occlusions.

15 Main takeaways

  1. Vision is an inverse problem. One image is compatible with many 3D worlds, so a model must combine data with prior assumptions.
  2. Learning is loss minimization; the goal is generalization. Fit on the training set, choose on the validation set, report once on the test set.
  3. Convolution is a local pattern detector with shared weights. Stacking layers grows the receptive field and builds a hierarchy: edges → parts → objects.
  4. ViTs turn an image into patch tokens. Self-attention lets every token use evidence from any other token in one layer, at a cost of \(O(N^2)\) for \(N\) tokens; position is supplied by embeddings.
  5. The backbone is reusable. A pretrained CNN or ViT, often with a feature pyramid, serves every task; mostly the head changes.
  6. The output defines the task: label → boxes → masks → keypoints → identities over time. Each needs its own head, loss, and metric.
  7. Detection scores many candidates and matches them to objects by IoU. R-CNN → Fast → Faster R-CNN: share the CNN, then learn the proposals. One-stage detectors predict densely and need the focal loss; NMS removes duplicates; DETR learns a one-to-one set prediction instead.
  8. Segmentation is classification at every pixel: an encoder–decoder, with skip connections or atrous convolutions to keep both detail and context. Mask R-CNN adds a mask head for each detected object.
  9. Pose is one more head on Mask R-CNN, with one map per joint inside each person box. Tracking links detections across frames by motion, geometry, and appearance.
  10. Evaluate with task metrics (mAP, mIoU, …) and inspect failures by scale, class, and occlusion before adding complexity.

16 Exercises

16.1 Exercise 1 — Shape arithmetic

A \(224\times224\times3\) image passes through a \(7\times7\) convolution with 64 filters, stride 2, padding 3, then a \(3\times3\) max pool with stride 2 and padding 1. Give the output shape after each layer and the number of parameters of the convolution.

16.2 Exercise 2 — ViT tokens

For ViT-B/16 at \(384\times384\), compute the number of patch tokens \(N\), the shape of \(\mathbf{z}_0\), and the size of the attention matrix \(\mathbf{A}\) of one head. By what factor did the attention matrix grow compared with \(224\times224\)?

16.3 Exercise 3 — IoU and anchors

Compute the IoU of the boxes \((0,0,4,4)\) and \((2,2,6,6)\), given as \((x_1,y_1,x_2,y_2)\). Then encode the box \((c_x,c_y,w,h)=(150,125,100,50)\) against the anchor \((140,130,128,64)\) and decode it back with Equation 5.

16.4 Exercise 4 — Focal loss

Compute the cross-entropy and the focal loss (\(\alpha_t=0.25\), \(\gamma=2\)) of a positive anchor with \(p_t=0.1\) and of a negative anchor with \(p_t=0.99\) (use \(\alpha_t=0.75\)). By how much does the focal loss reduce each, relative to cross-entropy?

16.5 Exercise 5 — Segmentation metrics

On images where road covers 70% of the pixels, cars 20%, and people 10%, compute the pixel accuracy and the mIoU of a model that predicts “road” everywhere.

References

This web note is adapted from the Lecture 1 slides of Deep Learning for Computer Vision by Jhony H. Giraldo. Recommended resources: Stanford CS231n; the TUM lecture videos; Goodfellow, Bengio, and Courville, Deep Learning (Goodfellow et al. 2016); and the libraries torchvision and Detectron2.

Bewley, Alex, Zongyuan Ge, Lionel Ott, Fabio Ramos, and Ben Upcroft. 2016. “Simple Online and Realtime Tracking.” IEEE International Conference on Image Processing (ICIP).
Cao, Zhe, Tomas Simon, Shih-En Wei, and Yaser Sheikh. 2017. “Realtime Multi-Person 2D Pose Estimation Using Part Affinity Fields.” IEEE Conference on Computer Vision and Pattern Recognition (CVPR).
Carion, Nicolas, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, and Sergey Zagoruyko. 2020. “End-to-End Object Detection with Transformers.” European Conference on Computer Vision (ECCV).
Chen, Liang-Chieh, George Papandreou, Florian Schroff, and Hartwig Adam. 2017. “Rethinking Atrous Convolution for Semantic Image Segmentation.” arXiv Preprint arXiv:1706.05587.
Chen, Liang-Chieh, Yukun Zhu, George Papandreou, Florian Schroff, and Hartwig Adam. 2018. “Encoder-Decoder with Atrous Separable Convolution for Semantic Image Segmentation.” European Conference on Computer Vision (ECCV).
Dalal, Navneet, and Bill Triggs. 2005. “Histograms of Oriented Gradients for Human Detection.” IEEE Conference on Computer Vision and Pattern Recognition (CVPR). https://doi.org/10.1109/CVPR.2005.177.
Deng, Jia, Wei Dong, Richard Socher, Li-Jia Li, Kai Li, and Li Fei-Fei. 2009. “ImageNet: A Large-Scale Hierarchical Image Database.” IEEE Conference on Computer Vision and Pattern Recognition (CVPR). https://doi.org/10.1109/CVPR.2009.5206848.
Dosovitskiy, Alexey, Lucas Beyer, Alexander Kolesnikov, et al. 2021. “An Image Is Worth 16x16 Words: Transformers for Image Recognition at Scale.” International Conference on Learning Representations (ICLR).
Dumoulin, Vincent, and Francesco Visin. 2016. “A Guide to Convolution Arithmetic for Deep Learning.” arXiv Preprint arXiv:1603.07285.
Everingham, Mark, Luc Van Gool, Christopher K. I. Williams, John Winn, and Andrew Zisserman. 2010. “The PASCAL Visual Object Classes (VOC) Challenge.” International Journal of Computer Vision 88 (2): 303–38. https://doi.org/10.1007/s11263-009-0275-4.
Farabet, Clément, Camille Couprie, Laurent Najman, and Yann LeCun. 2013. “Learning Hierarchical Features for Scene Labeling.” IEEE Transactions on Pattern Analysis and Machine Intelligence 35 (8): 1915–29. https://doi.org/10.1109/TPAMI.2012.231.
Geirhos, Robert, Patricia Rubisch, Claudio Michaelis, Matthias Bethge, Felix A. Wichmann, and Wieland Brendel. 2019. “ImageNet-Trained CNNs Are Biased Towards Texture; Increasing Shape Bias Improves Accuracy and Robustness.” International Conference on Learning Representations (ICLR).
Girshick, Ross. 2015. “Fast R-CNN.” IEEE International Conference on Computer Vision (ICCV).
Girshick, Ross, Jeff Donahue, Trevor Darrell, and Jitendra Malik. 2014. “Rich Feature Hierarchies for Accurate Object Detection and Semantic Segmentation.” IEEE Conference on Computer Vision and Pattern Recognition (CVPR).
Goodfellow, Ian, Yoshua Bengio, and Aaron Courville. 2016. Deep Learning. MIT Press.
Hariharan, Bharath, Pablo Arbeláez, Ross Girshick, and Jitendra Malik. 2014. “Simultaneous Detection and Segmentation.” European Conference on Computer Vision (ECCV).
He, Kaiming, Georgia Gkioxari, Piotr Dollár, and Ross Girshick. 2017. “Mask R-CNN.” IEEE International Conference on Computer Vision (ICCV).
He, Kaiming, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. 2016. “Deep Residual Learning for Image Recognition.” IEEE Conference on Computer Vision and Pattern Recognition (CVPR). https://doi.org/10.1109/CVPR.2016.90.
Hendrycks, Dan, and Kevin Gimpel. 2016. “Gaussian Error Linear Units (GELUs).” arXiv Preprint arXiv:1606.08415.
Hubel, David H., and Torsten N. Wiesel. 1962. “Receptive Fields, Binocular Interaction and Functional Architecture in the Cat’s Visual Cortex.” The Journal of Physiology 160 (1): 106–54. https://doi.org/10.1113/jphysiol.1962.sp006837.
Ioffe, Sergey, and Christian Szegedy. 2015. “Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift.” International Conference on Machine Learning (ICML).
Krizhevsky, Alex, Ilya Sutskever, and Geoffrey E. Hinton. 2012. “ImageNet Classification with Deep Convolutional Neural Networks.” Advances in Neural Information Processing Systems (NeurIPS).
Kuhn, Harold W. 1955. “The Hungarian Method for the Assignment Problem.” Naval Research Logistics Quarterly 2 (1–2): 83–97. https://doi.org/10.1002/nav.3800020109.
LeCun, Yann, Léon Bottou, Yoshua Bengio, and Patrick Haffner. 1998. “Gradient-Based Learning Applied to Document Recognition.” Proceedings of the IEEE 86 (11): 2278–324. https://doi.org/10.1109/5.726791.
Lin, Tsung-Yi, Piotr Dollár, Ross Girshick, Kaiming He, Bharath Hariharan, and Serge Belongie. 2017. “Feature Pyramid Networks for Object Detection.” IEEE Conference on Computer Vision and Pattern Recognition (CVPR).
Lin, Tsung-Yi, Priya Goyal, Ross Girshick, Kaiming He, and Piotr Dollár. 2017. “Focal Loss for Dense Object Detection.” IEEE International Conference on Computer Vision (ICCV).
Lin, Tsung-Yi, Michael Maire, Serge Belongie, et al. 2014. “Microsoft COCO: Common Objects in Context.” European Conference on Computer Vision (ECCV).
Liu, Wei, Dragomir Anguelov, Dumitru Erhan, et al. 2016. “SSD: Single Shot MultiBox Detector.” European Conference on Computer Vision (ECCV).
Liu, Ze, Yutong Lin, Yue Cao, et al. 2021. “Swin Transformer: Hierarchical Vision Transformer Using Shifted Windows.” IEEE/CVF International Conference on Computer Vision (ICCV).
Liu, Zhuang, Hanzi Mao, Chao-Yuan Wu, Christoph Feichtenhofer, Trevor Darrell, and Saining Xie. 2022. “A ConvNet for the 2020s.” IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR).
Long, Jonathan, Evan Shelhamer, and Trevor Darrell. 2015. “Fully Convolutional Networks for Semantic Segmentation.” IEEE Conference on Computer Vision and Pattern Recognition (CVPR).
Lowe, David G. 2004. “Distinctive Image Features from Scale-Invariant Keypoints.” International Journal of Computer Vision 60 (2): 91–110. https://doi.org/10.1023/B:VISI.0000029664.99615.94.
Milan, Anton, Laura Leal-Taixé, Ian Reid, Stefan Roth, and Konrad Schindler. 2016. “MOT16: A Benchmark for Multi-Object Tracking.” arXiv Preprint arXiv:1603.00831.
Neubeck, Alexander, and Luc Van Gool. 2006. “Efficient Non-Maximum Suppression.” International Conference on Pattern Recognition (ICPR).
Odena, Augustus, Vincent Dumoulin, and Chris Olah. 2016. “Deconvolution and Checkerboard Artifacts.” Distill, ahead of print. https://doi.org/10.23915/distill.00003.
Papert, Seymour A. 1966. The Summer Vision Project. Vision Memo No. 100. Massachusetts Institute of Technology, Artificial Intelligence Group.
Redmon, Joseph, Santosh Divvala, Ross Girshick, and Ali Farhadi. 2016. “You Only Look Once: Unified, Real-Time Object Detection.” IEEE Conference on Computer Vision and Pattern Recognition (CVPR).
Ren, Shaoqing, Kaiming He, Ross Girshick, and Jian Sun. 2015. “Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks.” Advances in Neural Information Processing Systems (NeurIPS).
Rezatofighi, Hamid, Nathan Tsoi, JunYoung Gwak, Amir Sadeghian, Ian Reid, and Silvio Savarese. 2019. “Generalized Intersection over Union: A Metric and a Loss for Bounding Box Regression.” IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR).
Ronneberger, Olaf, Philipp Fischer, and Thomas Brox. 2015. “U-Net: Convolutional Networks for Biomedical Image Segmentation.” Medical Image Computing and Computer-Assisted Intervention (MICCAI).
Simonyan, Karen, and Andrew Zisserman. 2015. “Very Deep Convolutional Networks for Large-Scale Image Recognition.” International Conference on Learning Representations (ICLR).
Toshev, Alexander, and Christian Szegedy. 2014. “DeepPose: Human Pose Estimation via Deep Neural Networks.” IEEE Conference on Computer Vision and Pattern Recognition (CVPR).
Uijlings, Jasper R. R., Koen E. A. van de Sande, Theo Gevers, and Arnold W. M. Smeulders. 2013. “Selective Search for Object Recognition.” International Journal of Computer Vision 104 (2): 154–71. https://doi.org/10.1007/s11263-013-0620-5.
Vaswani, Ashish, Noam Shazeer, Niki Parmar, et al. 2017. “Attention Is All You Need.” Advances in Neural Information Processing Systems (NeurIPS).
Wojke, Nicolai, Alex Bewley, and Dietrich Paulus. 2017. “Simple Online and Realtime Tracking with a Deep Association Metric.” IEEE International Conference on Image Processing (ICIP).
Zhou, Bolei, Aditya Khosla, Agata Lapedriza, Aude Oliva, and Antonio Torralba. 2016. “Learning Deep Features for Discriminative Localization.” IEEE Conference on Computer Vision and Pattern Recognition (CVPR). https://doi.org/10.1109/CVPR.2016.319.
Zhu, Xizhou, Weijie Su, Lewei Lu, Bin Li, Xiaogang Wang, and Jifeng Dai. 2021. “Deformable DETR: Deformable Transformers for End-to-End Object Detection.” International Conference on Learning Representations (ICLR).
Zitnick, C. Lawrence, and Piotr Dollár. 2014. “Edge Boxes: Locating Object Proposals from Edges.” European Conference on Computer Vision (ECCV).
Back to top