TExcelTAD
Home › Computer Vision: Images to Detection, Segmentation & Tracking › Semantic Segmentation: from Thresholds to FCN

Semantic Segmentation: from Thresholds to FCN

A detector says "there is a circle in this box". For many questions a box is far too coarse: how much of a field is flooded, where exactly the road ends, how large a tumour is, which pixels a self-driving car may drive on. Semantic segmentation answers them by giving every pixel a class. Its output is a label map of the same height and width as the image, with one class id per pixel.

"Semantic" means the classes are kinds of stuff, not individual objects: two circles that touch get the same label and become one blob. Separating them is instance segmentation, the next lesson but one. This lesson starts with methods that need no training (thresholds, clustering, superpixels), shows why they cannot name classes, then builds the idea behind every modern segmentation network, the fully convolutional network (FCN), and its loss functions. The U-Net lesson then trains one.

The task

For an image of size H×WH \times W and KK classes (background included), the target is a map y∈{0,…,K−1}H×Wy \in \{0, \ldots, K-1\}^{H \times W}. A network outputs KK scores per pixel, an array of shape K×H×WK \times H \times W (in PyTorch N×K×H×WN \times K \times H \times W for a batch); a softmax over the KK channels turns them into class probabilities pikp_{ik} for pixel ii, and the prediction is the arg max per pixel.

The data in this lesson are the course's generated scenes (make_scene): 64 x 64 RGB images on a noisy grey background with one to three squares, circles and triangles, each painted in a random colour, with exact masks. The semantic target uses class 0 for background and 1, 2, 3 for square, circle and triangle. The random colours are deliberate: the colour of a shape says nothing about its class, only its shape does. That is the situation in real scenes too, where a car can be any colour.

Segmentation is evaluated with per-class IoU, its mean over classes (mIoU) and Dice, computed from a pixel confusion matrix. These are taught in segmentation metrics; here they are just used. The one thing to remember: pixel accuracy is dominated by the background and flatters every model.

Classical segmentation: no training

Three classic tools, each still useful as a baseline or as a preprocessing step:

  • Thresholding. One number decides foreground versus background. Otsu's method picks the threshold that best separates the histogram into two groups (histograms and thresholding). The shapes here have random colours, some darker and some brighter than the background, so the threshold is applied to the colour distance from the background (the median colour of the image), not to the grey level.
  • k-means colour clustering. Every pixel is a point in RGB space; k-means groups them into kk colour clusters. It finds regions of similar colour, but the clusters have no names.
  • Superpixels. SLIC (simple linear iterative clustering) runs k-means on colour plus position, so clusters are compact patches that follow colour edges. They are not a segmentation by themselves but a way to reduce 4,096 pixels to a few dozen regions that a later classifier labels.
python · try it yourself
import numpy as np, cv2
from skimage.filters import threshold_otsu
from skimage.segmentation import slic
cv2.setLogLevel(0)

CLASSES = ["square", "circle", "triangle"]

def make_scene(rng, size=64, max_objects=3):
    """Noisy grey background with 1..max_objects shapes that do not touch.
    Returns RGB uint8 image, boxes (n, 4) as [x1, y1, x2, y2] with x2, y2 exclusive,
    labels (n,) indices into CLASSES, masks (n, size, size) bool."""
    img = rng.normal(110, 12, (size, size, 3)).clip(0, 255).astype(np.uint8)
    n = int(rng.integers(1, max_objects + 1))
    boxes, labels, masks = [], [], []
    for _ in range(100):
        if len(boxes) == n:
            break
        s = int(rng.integers(12, 25)); x = int(rng.integers(0, size - s)); y = int(rng.integers(0, size - s))
        if any(x < b[2] + 2 and b[0] < x + s + 2 and y < b[3] + 2 and b[1] < y + s + 2 for b in boxes):
            continue
        c = int(rng.integers(0, 3)); m = np.zeros((size, size), np.uint8)
        if c == 0:
            cv2.rectangle(m, (x, y), (x + s - 1, y + s - 1), 1, -1)
        elif c == 1:
            cv2.circle(m, (x + s // 2, y + s // 2), s // 2, 1, -1)
        else:
            cv2.fillPoly(m, [np.array([[x + s // 2, y], [x, y + s - 1], [x + s - 1, y + s - 1]], np.int32)], 1)
        img[m > 0] = rng.integers(0, 256, 3)
        ys, xs = np.nonzero(m)
        boxes.append([int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1])
        labels.append(c); masks.append(m > 0)
    return img, np.array(boxes).reshape(-1, 4), np.array(labels), np.array(masks)

def label_map(labels, masks, size=64):
    """Semantic target: 0 = background, 1 + class index on each shape."""
    y = np.zeros((size, size), np.int64)
    for c, m in zip(labels, masks):
        y[m] = c + 1
    return y

rng = np.random.default_rng(0)
img, boxes, labels, masks = make_scene(rng)
img, boxes, labels, masks = make_scene(rng)          # the second scene: a circle and a square
y = label_map(labels, masks)
print("classes:", [CLASSES[c] for c in labels], "| pixels per class id 0..3:", np.bincount(y.ravel(), minlength=4).tolist())

# 1. Otsu on the distance from the background colour (median of the image)
f = img.astype(float)
dist = np.linalg.norm(f - np.median(f.reshape(-1, 3), axis=0), axis=2)
fg = dist > threshold_otsu(dist)
print(f"Otsu foreground IoU: {(fg & (y > 0)).sum() / (fg | (y > 0)).sum():.3f}")

# 2. k-means on colour: k = 3 clusters (background + 2 shapes)
Z = img.reshape(-1, 3).astype(np.float32)
crit = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 0.5)
_, km, centres = cv2.kmeans(Z, 3, None, crit, 3, cv2.KMEANS_PP_CENTERS)
km = km.reshape(64, 64)
for k in range(3):
    ids, counts = np.unique(y[km == k], return_counts=True)
    print(f"cluster {k}: colour {centres[k].round().astype(int).tolist()}, true class ids {dict(zip(ids.tolist(), counts.tolist()))}")

# 3. SLIC superpixels: how well do they respect the true boundaries?
for n in [10, 30, 100]:
    sp = slic(img, n_segments=n, compactness=30, start_label=0)
    pure = sum(np.bincount(y[sp == s]).max() for s in np.unique(sp))
    print(f"SLIC n_segments={n:3d}: {len(np.unique(sp)):3d} superpixels, {pure / y.size:.3f} of pixels share their superpixel's majority class")
classes: ['circle', 'square'] | pixels per class id 0..3: [3787, 196, 113, 0]
Otsu foreground IoU: 1.000
cluster 0: colour [110, 109, 110], true class ids {0: 3787}
cluster 1: colour [236, 97, 44], true class ids {1: 196}
cluster 2: colour [222, 92, 119], true class ids {2: 113}
SLIC n_segments= 10:   8 superpixels, 0.925 of pixels share their superpixel's majority class
SLIC n_segments= 30:  25 superpixels, 1.000 of pixels share their superpixel's majority class
SLIC n_segments=100: 106 superpixels, 0.997 of pixels share their superpixel's majority class

On this scene the colour-distance threshold separates the shapes from the background perfectly (foreground IoU 1.000), and k-means finds three clusters that coincide exactly with the background, the circle and the square. But look at what k-means returns: "cluster 1 is orange, cluster 2 is pink". Nothing says which cluster is the circle. Both methods solve foreground versus background, the easiest part, and neither can name a class, because the class is in the shape and these methods look only at colour, one pixel at a time.

SLIC shows its trade-off in the purity column. With too few superpixels (the first row asks for 10 and gets 8) whole shapes merge with the background, so about 7.5 % of the pixels sit in a superpixel dominated by another class; with 25 superpixels every superpixel is pure (purity 1.000), and 106 superpixels are almost as good (0.997) at four times the cost. Superpixels never fix a boundary that a later step got wrong, but they can make a classifier's job 100 times smaller.

Fully convolutional networks

A CNN classifier (CNN architectures) shrinks the image through convolutions and pooling to a small feature map, then flattens it into a dense layer that outputs one vector of class scores. Long, Shelhamer and Darrell's fully convolutional network (2015) made two changes that turned classifiers into segmenters:

  1. Replace the dense layer by a 1×11 \times 1 convolution. A 1×11 \times 1 convolution with KK output channels applies the same linear classifier, a K×CK \times C weight matrix, to the CC features at every position of the feature map. The network then outputs a coarse grid of class scores instead of one vector, and it accepts any input size.
  2. Upsample the coarse scores back to the input size, by bilinear interpolation (no parameters) or by a learned transposed convolution.

The encoder's output stride is the factor by which it shrinks the image: 8 for the toy map below, 32 for a plain ResNet (vision backbones). After stride 32, a 512 x 512 image is a 16 x 16 grid and every grid cell must speak for a 32 x 32 block of pixels, so thin structures and exact boundaries are lost. The fixes are the subject of the next lesson: skip connections that bring back fine features from early layers (FCN-8s, U-Net) and dilated convolutions that keep the map larger (DeepLab).

image3 x 64 x 64 32 x 32 16 8 4 scores4 x 64 x 64 label map64 x 64 encoder: conv + pooloutput stride 8 1 x 1conv upsample x 8bilinear or transposed arg maxper pixel dashed: skip connections (U-Net, FCN-8s) every layer is a convolution: the same weights at every position, any input size

A transposed convolution with kernel kk, stride ss and padding pp maps an HinH_{\text{in}}-pixel side to

Hout=(Hin−1) s−2p+kH_{\text{out}} = (H_{\text{in}} - 1)\, s - 2p + k

pixels; with k=s=2k = s = 2, p=0p = 0 it exactly doubles the size. Its name says what it is: an ordinary strided convolution is a linear map z↦Azz \mapsto Az that shrinks the image, and the transposed convolution is the map x↦A⊤xx \mapsto A^{\top} x with the same kernel, which has the shape of the inverse but is not the inverse. Each input value "stamps" a copy of the kernel, scaled by itself, onto the larger output. The padding and stride lesson has the size arithmetic for ordinary convolutions.

python · try it yourself
import numpy as np
import cv2
cv2.setLogLevel(0)
rng = np.random.default_rng(0)

# An encoder has turned a 64 x 64 image into a coarse 8 x 8 map with C = 16 channels (stride 8).
C, K = 16, 4
feat = rng.normal(size=(C, 8, 8)).astype(np.float32)

# 1 x 1 convolution = the same linear classifier applied at every position
W, b = rng.normal(size=(K, C)).astype(np.float32) * 0.3, np.zeros(K, np.float32)
logits = np.einsum("kc,chw->khw", W, feat) + b[:, None, None]
print("coarse logits:", logits.shape)
print("same as a dense layer at (3, 5):", np.allclose(logits[:, 3, 5], W @ feat[:, 3, 5] + b))

# Upsample back to 64 x 64: bilinear interpolation (no parameters)
up = np.stack([cv2.resize(l, (64, 64), interpolation=cv2.INTER_LINEAR) for l in logits])
print("upsampled logits:", up.shape, "-> label map", up.argmax(axis=0).shape)

def conv_transpose(x, w, s):
    """Transposed convolution of a 2-D map x with kernel w, stride s, no padding:
    every input value adds a scaled copy of the kernel to the output."""
    k = w.shape[0]
    out = np.zeros(((x.shape[0] - 1) * s + k, (x.shape[1] - 1) * s + k))
    for i in range(x.shape[0]):
        for j in range(x.shape[1]):
            out[s * i:s * i + k, s * j:s * j + k] += x[i, j] * w
    return out

def conv_strided(z, w, s):
    """The ordinary strided convolution (cross-correlation) with the same kernel."""
    k = w.shape[0]
    return np.array([[np.sum(z[s * i:s * i + k, s * j:s * j + k] * w) for j in range((z.shape[1] - k) // s + 1)]
                     for i in range((z.shape[0] - k) // s + 1)])

x = np.array([[1., 2.], [3., 4.]]); w = np.array([[1., 0.5], [0.25, 0.]])
print(conv_transpose(x, w, 2))
z = rng.normal(size=(4, 4))                          # transpose test: <conv(z), x> = <z, conv_transpose(x)>
print(f"<A z, x> = {np.sum(conv_strided(z, w, 2) * x):.6f}   <z, A^T x> = {np.sum(z * conv_transpose(x, w, 2)):.6f}")

# Kernel 3, stride 2: the stamps overlap unevenly -> how many stamps land on each pixel of the first output row
print("overlap count, k=3 s=2:", conv_transpose(np.ones((4, 4)), np.ones((3, 3)), 2)[0].astype(int).tolist())
coarse logits: (4, 8, 8)
same as a dense layer at (3, 5): True
upsampled logits: (4, 64, 64) -> label map (64, 64)
[[1.   0.5  2.   1.  ]
 [0.25 0.   0.5  0.  ]
 [3.   1.5  4.   2.  ]
 [0.75 0.   1.   0.  ]]
<A z, x> = 9.476673   <z, A^T x> = 9.476673
overlap count, k=3 s=2: [1, 1, 2, 1, 2, 1, 2, 1, 1]

The 1×11 \times 1 convolution at position (3, 5) gives exactly what a dense layer gives for that position's 16 features: an FCN is a classifier slid over the feature map. The 2×22 \times 2 stride-2 transposed convolution turns the 2×22 \times 2 input into a 4×44 \times 4 output made of four scaled copies of the kernel, and the two inner products agree to six decimals, which is the definition of a transpose. The last line is the origin of the checkerboard artefacts of transposed convolutions: with kernel 3 and stride 2, every other pixel inside the output receives two stamps and its neighbours only one (1, 2, 1, 2 along the row), so the output has a built-in 2-pixel period unless training cancels it. Kernels divisible by the stride (k=sk = s, or k=4,s=2k = 4, s = 2), or bilinear upsampling followed by an ordinary convolution, avoid it.

The loss: per-pixel cross-entropy and Dice

Training a segmenter is classification at every pixel. With one-hot targets yiky_{ik} and softmax probabilities pikp_{ik} over NN pixels, the loss is the mean per-pixel cross-entropy (cross-entropy losses):

LCE=−1N∑i=1N∑k=1Kwk yiklog⁡pikL_{\text{CE}} = -\frac{1}{N} \sum_{i=1}^{N} \sum_{k=1}^{K} w_k \, y_{ik} \log p_{ik}

with all class weights wk=1w_k = 1 by default. In PyTorch this is F.cross_entropy(logits, target) with logits of shape N×K×H×WN \times K \times H \times W and an integer target of shape N×H×WN \times H \times W; nothing about it is specific to images.

The trouble is class imbalance. When the object covers 1 % of the image, 99 % of the loss comes from background pixels, and a model can reach a low loss by being very sure about the background and ignoring the object. Two standard fixes:

  • Class weights wkw_k, for example inversely proportional to each class's pixel frequency (or the square root of it, to be gentler).
  • The soft Dice loss, one minus the Dice coefficient computed on probabilities instead of a thresholded mask, so it is differentiable:
LDice=1−2∑ipigi+ϵ∑ipi+∑igi+ϵL_{\text{Dice}} = 1 - \frac{2 \sum_i p_i g_i + \epsilon}{\sum_i p_i + \sum_i g_i + \epsilon}

Here pip_i is the predicted probability of the object at pixel ii, gi∈{0,1}g_i \in \{0, 1\} the target and ϵ\epsilon a small constant (often 1) that keeps an empty prediction on an empty mask from dividing by zero. True negatives do not appear in it at all, so the background cannot dominate. For several classes, the Dice loss is averaged over the classes. Many practical models use LCE+LDiceL_{\text{CE}} + L_{\text{Dice}} together.

python · try it yourself
import numpy as np

# Binary task on a 64 x 64 image: a 6 x 6 object (36 of 4096 pixels, 0.9 %)
g = np.zeros((64, 64)); g[20:26, 30:36] = 1

# Two predicted probability maps for "object"
lazy = np.full((64, 64), 0.01)                    # confident background everywhere: finds nothing
finder = np.full((64, 64), 0.05); finder[20:26, 30:36] = 0.7   # finds the object, less sure about background

def bce(p, g, w_pos=1.0):
    """Mean per-pixel binary cross-entropy; w_pos weights the object pixels."""
    w = np.where(g == 1, w_pos, 1.0)
    return float(np.sum(-w * (g * np.log(p) + (1 - g) * np.log(1 - p))) / np.sum(w))

def soft_dice_loss(p, g, eps=1.0):
    return float(1 - (2 * np.sum(p * g) + eps) / (np.sum(p) + np.sum(g) + eps))

w_pos = (g == 0).sum() / (g == 1).sum()           # inverse frequency
print(f"object weight for weighted CE: {w_pos:.1f}")
for name, p in [("lazy", lazy), ("finder", finder)]:
    pred = p > 0.5
    iou = (pred & (g == 1)).sum() / max((pred | (g == 1)).sum(), 1)
    print(f"{name:7s} CE {bce(p, g):.4f}  weighted CE {bce(p, g, w_pos):.4f}  Dice loss {soft_dice_loss(p, g):.3f}  "
          f"pixel acc {np.mean(pred == (g == 1)):.4f}  IoU {iou:.3f}")
object weight for weighted CE: 112.8
lazy    CE 0.0504  weighted CE 2.3076  Dice loss 0.978  pixel acc 0.9912  IoU 0.000
finder  CE 0.0540  weighted CE 0.2040  Dice loss 0.806  pixel acc 1.0000  IoU 1.000

Plain cross-entropy prefers the lazy model (0.0504 against 0.0540) although it finds nothing (IoU 0) and the finder is perfect after thresholding (IoU 1). The lazy model's pixel accuracy, 0.9912, also looks excellent. Weighting the object pixels by the inverse frequency (112.8) reverses the ranking by a wide margin (2.3076 against 0.2040), and so does the Dice loss (0.978 against 0.806). The Dice loss of the finder is still far from 0 because its 0.05 background probability, summed over 4,060 pixels, is a large "predicted area"; that is the Dice loss pushing the model to be sure about the background too.

A learned baseline: a classifier per pixel

Before a deep network, the honest question is how far a classical learned model gets. Give each pixel a small feature vector, train any classifier on labelled pixels, and predict every pixel of a new image independently. The features below are the pixel's colour, its distance from the background colour, and the local mean of that distance over three window sizes plus a local standard deviation, so each pixel sees a little of its neighbourhood (up to 17 x 17 pixels). A random forest learns from 30,000 pixels sampled from 60 training scenes; the test set is 100 scenes from a different seed, the same test set the U-Net lesson uses.

python · try it yourself
import numpy as np, cv2
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix
cv2.setLogLevel(0)

CLASSES = ["square", "circle", "triangle"]

def make_scene(rng, size=64, max_objects=3):
    """Noisy grey background with 1..max_objects shapes that do not touch.
    Returns RGB uint8 image, boxes (n, 4) as [x1, y1, x2, y2] with x2, y2 exclusive,
    labels (n,) indices into CLASSES, masks (n, size, size) bool."""
    img = rng.normal(110, 12, (size, size, 3)).clip(0, 255).astype(np.uint8)
    n = int(rng.integers(1, max_objects + 1))
    boxes, labels, masks = [], [], []
    for _ in range(100):
        if len(boxes) == n:
            break
        s = int(rng.integers(12, 25)); x = int(rng.integers(0, size - s)); y = int(rng.integers(0, size - s))
        if any(x < b[2] + 2 and b[0] < x + s + 2 and y < b[3] + 2 and b[1] < y + s + 2 for b in boxes):
            continue
        c = int(rng.integers(0, 3)); m = np.zeros((size, size), np.uint8)
        if c == 0:
            cv2.rectangle(m, (x, y), (x + s - 1, y + s - 1), 1, -1)
        elif c == 1:
            cv2.circle(m, (x + s // 2, y + s // 2), s // 2, 1, -1)
        else:
            cv2.fillPoly(m, [np.array([[x + s // 2, y], [x, y + s - 1], [x + s - 1, y + s - 1]], np.int32)], 1)
        img[m > 0] = rng.integers(0, 256, 3)
        ys, xs = np.nonzero(m)
        boxes.append([int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1])
        labels.append(c); masks.append(m > 0)
    return img, np.array(boxes).reshape(-1, 4), np.array(labels), np.array(masks)

def label_map(labels, masks, size=64):
    y = np.zeros((size, size), np.int64)
    for c, m in zip(labels, masks):
        y[m] = c + 1
    return y

def scenes(seed, n):
    rng = np.random.default_rng(seed)
    out = []
    for _ in range(n):
        img, boxes, labels, masks = make_scene(rng)
        out.append((img, label_map(labels, masks)))
    return out

def pixel_features(img):
    """8 numbers per pixel: R, G, B, distance from the background colour, its local mean
    over 3 x 3, 9 x 9 and 17 x 17 windows, and its local standard deviation over 9 x 9."""
    f = img.astype(np.float32)
    dist = np.linalg.norm(f - np.median(f.reshape(-1, 3), axis=0), axis=2)
    feats = [f[..., 0], f[..., 1], f[..., 2], dist]
    for k in (3, 9, 17):
        feats.append(cv2.blur(dist, (k, k)))
    m = cv2.blur(dist, (9, 9))
    feats.append(np.sqrt(np.maximum(cv2.blur(dist * dist, (9, 9)) - m * m, 0)))
    return np.stack(feats, -1).reshape(-1, len(feats))

train, test = scenes(0, 60), scenes(1, 100)          # different seeds: no test scene is seen in training
X = np.concatenate([pixel_features(img) for img, _ in train])
Y = np.concatenate([y.ravel() for _, y in train])
idx = np.random.default_rng(0).choice(len(X), 30000, replace=False)   # 30,000 of 245,760 training pixels
clf = RandomForestClassifier(n_estimators=30, max_depth=12, random_state=0).fit(X[idx], Y[idx])

P = np.concatenate([clf.predict(pixel_features(img)) for img, _ in test])
G = np.concatenate([y.ravel() for _, y in test])
M = confusion_matrix(G, P, labels=[0, 1, 2, 3])
iou = np.diag(M) / (M.sum(axis=0) + M.sum(axis=1) - np.diag(M))
print("share of test pixels per class:", (M.sum(axis=1) / M.sum()).round(3).tolist())
print(M)
for name, v in zip(["background"] + CLASSES, iou):
    print(f"IoU {name:10s} {v:.3f}")
print(f"mIoU {iou.mean():.3f}   pixel accuracy {np.trace(M) / M.sum():.3f}   (100 test scenes, 409,600 pixels)")

img, y = test[0]
fig, ax = plt.subplots(1, 3, figsize=(6, 2.2))
for a, im, t in zip(ax, [img, y, clf.predict(pixel_features(img)).reshape(64, 64)], ["image", "truth", "per-pixel forest"]):
    a.imshow(im, vmin=0, vmax=3, cmap="viridis" if im.ndim == 2 else None); a.set_title(t, fontsize=9); a.axis("off")
fig.tight_layout()
share of test pixels per class: [0.872, 0.055, 0.038, 0.035]
[[357153     10      2     10]
 [     2   8858   8212   5610]
 [   646   7312   3957   3676]
 [   231   6224   3000   4697]]
IoU background 0.997
IoU square     0.245
IoU circle     0.148
IoU triangle   0.200
mIoU 0.397   pixel accuracy 0.915   (100 test scenes, 409,600 pixels)

The confusion matrix tells the whole story. Background is almost perfect (IoU 0.997): only 22 of 357,175 background pixels are called a shape, and 879 shape pixels (mostly at shape borders) are called background. Inside the shapes the forest is close to guessing: the 22,682 square pixels are split 8,858 / 8,212 / 5,610 between square, circle and triangle. The shape IoUs are 0.245, 0.148 and 0.200, the mIoU is 0.397, and the pixel accuracy of 0.915 would hide all of that, because 87.2 % of the pixels are background.

The reason is the receptive field. A 17 x 17 window around a pixel in the middle of a 24-pixel square sees a uniform patch, exactly what it would see inside a large circle. To tell a square from a circle the model needs features that describe the outline of the whole shape: corners, curvature, the pointed top of a triangle. A hand-made feature set could add them (that is what the classical vision pipelines did, at great effort); a CNN encoder learns them, and its deep layers see the whole shape. The U-Net in the next lesson reaches an mIoU above 0.97 on the same test set.

Pitfalls

  • Reporting pixel accuracy. 0.915 above for a model that cannot tell the shapes apart. Report per-class IoU and mIoU, and say whether they are pooled over the test set (as here) or averaged per image (segmentation metrics).
  • Resizing label maps with interpolation. Bilinear interpolation of class ids invents classes (halfway between class 1 and class 3 is class 2). Resize label maps with nearest neighbour, images with bilinear or area interpolation, and apply the same crop and flip to both (image augmentation).
  • Ignore labels. Real data sets mark unsure pixels (object borders, unlabelled regions) with a special value, 255 in Pascal VOC and Cityscapes. Pass it to the loss (ignore_index=255 in PyTorch) and leave it out of the metrics; otherwise the model is trained to predict "border" as a class.
  • Colour as a shortcut. If every car in the training set is red, a pixel classifier learns "red = car". The random colours of the generated scenes remove this shortcut on purpose; with real data, check what the model actually uses (error analysis).
  • Leakage between crops. Large images (satellite, microscopy) are cut into tiles for training. Tiles of the same image in train and test overlap or share context; split by image or by region (split strategies).
  • Checkerboard artefacts from transposed convolutions whose kernel is not divisible by the stride (the overlap count 1, 2, 1, 2 above).

Practice

  1. An encoder has output stride 16. What is the size of its score map for a 512 x 384 image, and how many pixels does each score cell stand for?
Answer

512/16=32512 / 16 = 32 by 384/16=24384 / 16 = 24, so a 32 x 24 grid, each cell standing for a 16×16=25616 \times 16 = 256-pixel block. Any boundary inside that block is decided by interpolation, which is why skip connections or dilated convolutions are needed for sharp masks.

  1. A transposed convolution has kernel 4, stride 2 and padding 1. What size does it produce from a 16 x 16 input? Does it have the checkerboard problem?
Answer

Hout=(16−1)⋅2−2⋅1+4=32H_{\text{out}} = (16 - 1) \cdot 2 - 2 \cdot 1 + 4 = 32: it doubles the size. The kernel 4 is divisible by the stride 2, so every output pixel receives the same number of stamps (two in each direction) and there is no built-in checkerboard pattern. That is why many DCGAN-style decoders (PyTorch's DCGAN example among them) use k=4k = 4, s=2s = 2, p=1p = 1.

  1. In the loss example, change the finder's background probability from 0.05 to 0.01 (as sure as the lazy model). Which model does plain cross-entropy prefer now, and why does the change matter so little for the object pixels?
Answer

Now both models pay the same background cost, −log⁡0.99-\log 0.99 per background pixel, and the finder pays −log⁡0.7=0.357-\log 0.7 = 0.357 per object pixel instead of −log⁡0.01=4.6-\log 0.01 = 4.6, so the finder wins. The object pixels are only 0.9 % of the total, so they move the mean little; it was the background term that decided the earlier ranking. Run the example with finder = np.full((64, 64), 0.01) to check.

  1. Why does k-means colour clustering give each shape its own cluster but no class name, and what would you have to add to get class names?
Answer

k-means only groups pixels of similar colour; cluster numbers are arbitrary and change from image to image. To name the classes you need a model that maps regions to classes from labelled examples: for instance shape features of each cluster's region (area, perimeter, circularity, corner count, as in contours) fed to a classifier, or a CNN that learns such features itself.

Test yourself

What does a 1×11 \times 1 convolution with KK output channels do in a fully convolutional network?

  1. It doubles the resolution
  2. It applies the same linear classifier to the feature vector at every position, giving KK class scores per cell
  3. It blurs the feature map
  4. It removes the background

An object covers 0.9 % of the pixels. A model outputs 0.01 for 'object' everywhere. Which statement is true?

  1. Its cross-entropy is high, so training fixes it at once
  2. Its plain cross-entropy is low and its pixel accuracy above 0.99, although its IoU is 0; class weights or the Dice loss expose it
  3. Its Dice loss is 0
  4. Its IoU is 0.99

The per-pixel random forest reached background IoU 0.997 but shape IoUs of only 0.15 to 0.25. What is the main reason?

  1. Too few trees
  2. Its features see at most a 17 x 17 window, which inside a shape looks the same for squares, circles and triangles; the class is in the outline of the whole shape
  3. The test set is too small
  4. Random forests cannot predict four classes

How should you resize a ground-truth label map from 512 x 512 to 256 x 256?

  1. Bilinear interpolation
  2. Bicubic interpolation
  3. Nearest-neighbour interpolation, so every pixel keeps a real class id
  4. Averaging the class ids