Semantic Segmentation for Drones
Semantic segmentation labels every pixel in an image with a class, turning one aerial frame into a dense map of roads, rooftops, water, fields, and tree cover. Detection answers how many and roughly where by drawing boxes; segmentation answers exactly which pixels belong to which class, down to the curve of a shoreline or the notch of a parking lot. That per-pixel answer is what makes automated land-use accounting, coverage checks, and change monitoring practical from airborne imagery.
What Pixel Labels Deliver That Boxes Cannot
Boxes are the wrong shape for area questions. A vehicle detection box also covers the asphalt beneath it, a building rectangle spills onto adjacent yards, and a polygon drawn around a lake ignores every inlet. Pixel masks resolve these cases because each label occupies only the surface it describes, so area integrates directly from the class map multiplied by the capture's ground sampling distance.
The difference shows up in evaluation as well: detection is scored with box overlap on a handful of objects, while segmentation is scored per pixel across millions of decisions. Small systematic errors â thin roads erased, roof shadows labeled as water â therefore accumulate into large area biases that box metrics never reveal.
| Question | Object detection | Semantic segmentation |
|---|---|---|
| How many vehicles? | One box per object | Connected components on the mask |
| Where exactly is the road edge? | Approximate rectangle | Pixel-precise boundary |
| What fraction of the scene is water? | Poor estimate | Direct pixel ratio times ground sampling distance |
| Instance separation | Built in | Needs an extra head, as in Mask R-CNN |
| Output size | A handful of boxes | One label per pixel |
The Encoder-Decoder Pipeline
A segmentation network compresses the image through a series of pooling stages while widening channels, then expands it back to input resolution while narrowing channels again. The contracting path, called the encoder, learns what things are; the expanding path, the decoder, recovers where each thing sits spatially. At the lowest resolution sits the bottleneck, which holds the most abstract and most context-rich representation of the scene.
Two details make the design work. First, upsampling recovers resolution through interpolation or learned transposition, and doing it carelessly produces checkerboard artifacts that show up as repeating label noise. Second, a final 1Ã1 convolution projects the feature stack onto the class dimension, after which a per-pixel softmax converts those logits into probabilities that sum to one at every pixel. The result is a tensor shaped by batch, classes, height, and width â one probability stack per pixel, ready for argmax or thresholded extraction.
Anatomy of U-Net and Its Skip Connections
U-Net was designed for biomedical datasets with very few labeled images, and that data efficiency makes it a default for drone imagery where annotated flights are expensive. Its encoder and decoder are mirrored, and each decoder stage receives a skip connection concatenated from the matching encoder stage. Because encoder features still carry the fine spatial detail that pooling destroys, feeding them back gives the decoder the edges it needs to place boundaries precisely instead of approximately.
The simulator below traces channel counts through such a network, showing how concatenation widens the decoder at every scale before the head collapses the features to the class count.
import numpy as np
class SkipNet:
"""Minimal U-Net shape simulator with skip connections."""
def __init__(self, in_ch=3, num_classes=6, base=16, depth=3):
self.encoder = []
ch = in_ch
for level in range(depth):
out_ch = base * 2 ** level
self.encoder.append((ch, out_ch))
ch = out_ch
self.bottleneck = (ch, ch * 2)
ch = self.bottleneck[1]
self.decoder = []
for _, enc_ch in reversed(self.encoder):
self.decoder.append((ch + enc_ch, enc_ch))
ch = enc_ch
self.head = (ch, num_classes)
def summary(self, hw=256):
print(f"input: {self.encoder[0][0]} ch at {hw}x{hw}")
h = hw
for index, (c_in, c_out) in enumerate(self.encoder, 1):
print(f"enc{index}: {c_in:4d} -> {c_out:4d} ch at {h}x{h}")
h //= 2
print(f"bottleneck: {self.bottleneck[1]} ch at {h}x{h}")
for index, (c_in, c_out) in enumerate(self.decoder, 1):
h *= 2
print(f"dec{index}: concat {c_in:4d} -> {c_out:4d} ch at {h}x{h}")
print(f"head: {self.head[0]} -> {self.head[1]} classes at {hw}x{hw}")
SkipNet().summary()
Choosing Between FCN, DeepLab, and Mask R-CNN
Which architecture you pick depends on what the deliverable must support. Land-cover statistics tolerate soft boundaries and reward the speed of simpler heads, while obstacle avoidance and asset inspection need crisp edges close to real geometry, and vehicle surveys need individual instances rather than merged blobs. A sensible progression is to baseline with the simplest encoder that trains, then add the component your error analysis actually points at.
| Architecture | Core idea | Strength | Typical drone task |
|---|---|---|---|
| FCN | Fully convolutional classifier with stride-based upsampling | Simple, fast baseline | Coarse land cover |
| U-Net | Symmetric encoder-decoder with skip connections | Sharp boundaries, data efficiency | Small labeled sets, precise masks |
| DeepLab v3+ | Atrous spatial pyramid pooling | Multi-scale context | Roads and rivers at varying widths |
| Mask R-CNN | Detection branch plus per-instance mask head | Instance-level separation | Vehicle and vessel counting |
Loss Functions for Imbalanced Classes
Aerial scenes are dominated by a few large classes â vegetation and rooftops â while vehicles, road centerlines, and shadows occupy a tiny fraction of pixels. Plain cross-entropy therefore rewards a model that predicts background well and fails exactly on the classes you care about. Two remedies dominate practice.
Dice loss optimizes overlap directly: it maximizes the ratio between predicted and true masks, so a class's contribution no longer shrinks with its pixel count. Focal loss instead reweights per-pixel cross-entropy so easy, confident pixels contribute almost nothing and hard pixels dominate the gradient. Most production pipelines combine cross-entropy with Dice for stability, adding focal weighting when rare classes still disappear after training.
import numpy as np
def dice_loss(probs, targets, smooth=1.0):
"""Soft Dice loss over a batch of per-pixel class probabilities."""
scores = []
for c in range(probs.shape[1]):
pred = probs[:, c].ravel()
true = (targets == c).astype(float).ravel()
intersection = np.sum(pred * true)
scores.append((2 * intersection + smooth) /
(np.sum(pred) + np.sum(true) + smooth))
return 1.0 - float(np.mean(scores))
def focal_loss(probs, targets, alpha=0.25, gamma=2.0):
"""Focal loss that down-weights already-correct pixels."""
eps = 1e-7
probs = np.clip(probs, eps, 1 - eps)
one_hot = np.stack([(targets == c) for c in range(probs.shape[1])],
axis=1)
p_t = one_hot * probs + (1 - one_hot) * (1 - probs)
weight = alpha * (1 - p_t) ** gamma
return float(-np.mean(weight * one_hot * np.log(probs)))
def cross_entropy(probs, targets):
"""Per-pixel categorical cross-entropy on the true-class channel."""
eps = 1e-7
picked = np.take_along_axis(
probs, targets[:, None, :, :].astype(np.int64), axis=1)
return float(-np.mean(np.log(np.clip(picked, eps, 1 - eps))))
np.random.seed(42)
probs = np.random.rand(2, 6, 64, 64)
probs /= probs.sum(axis=1, keepdims=True)
targets = np.random.randint(0, 6, (2, 64, 64))
print(f"cross-entropy: {cross_entropy(probs, targets):.4f}")
print(f"dice loss: {dice_loss(probs, targets):.4f}")
print(f"focal loss: {focal_loss(probs, targets):.4f}")
Measuring Success with mIoU
Overall accuracy is a misleading metric here: a model that predicts only vegetation can look strong on a green-dominated scene while being useless. The standard metric is mean intersection over union, computed per class as true positives divided by the union of predicted and actual pixels, then averaged so every class counts equally regardless of size. Frequency-weighted intersection over union and per-class Dice complete the picture, with Dice behaving better on boundary-heavy targets.
Always report per-class numbers next to the mean. A respectable mIoU can hide a water class stuck near zero, and water is usually the class a stakeholder asks about first.
import numpy as np
class Confusion:
"""Confusion matrix with per-class IoU and mean IoU."""
def __init__(self, num_classes):
self.num_classes = num_classes
self.matrix = np.zeros((num_classes, num_classes), dtype=np.int64)
def update(self, predicted, target):
index = predicted.ravel() * self.num_classes + target.ravel()
self.matrix += np.bincount(
index, minlength=self.num_classes ** 2
).reshape(self.num_classes, self.num_classes)
def per_class_iou(self):
tp = np.diag(self.matrix).astype(float)
union = self.matrix.sum(1) + self.matrix.sum(0) - tp
with np.errstate(divide="ignore", invalid="ignore"):
return np.where(union > 0, tp / union, np.nan)
def report(self, names):
iou = self.per_class_iou()
for name, score in zip(names, iou):
print(f" {name:11s} IoU {score:.3f}")
print(f"mIoU: {np.nanmean(iou):.3f}")
class_names = ["building", "road", "vegetation", "water", "vehicle", "person"]
np.random.seed(42)
conf = Confusion(len(class_names))
for _ in range(12):
target = np.random.randint(0, len(class_names), (64, 64))
keep = np.random.rand(64, 64) > 0.15
predicted = np.where(keep, target,
np.random.randint(0, len(class_names), (64, 64)))
conf.update(predicted, target)
conf.report(class_names)
Turning Predictions into Land-Use Maps
Moving from probabilities to a deliverable requires more than argmax. Extract the class map at full resolution or by tiling, then attach physical meaning: multiply pixel counts by the square of the ground sampling distance to obtain area in square meters and hectares. Once two flights are georegistered to the same grid, differencing their label maps yields a transition matrix showing which class became which â the raw material for urban growth reports and deforestation alerts.
import numpy as np
class LandUseReport:
"""Area accounting and change detection from label maps."""
CLASSES = ["residential", "commercial", "agricultural",
"forest", "water", "road"]
def __init__(self, pixel_size_m=0.05):
self.pixel_size_m = pixel_size_m
def area_table(self, label_map):
pixel_area = self.pixel_size_m ** 2
rows = []
for index, name in enumerate(self.CLASSES):
count = int(np.sum(label_map == index))
rows.append((name, count, count * pixel_area,
100.0 * count / label_map.size))
rows.sort(key=lambda row: row[2], reverse=True)
return rows, label_map.size * pixel_area
def change_matrix(self, before, after):
transitions = {}
for old in range(len(self.CLASSES)):
for new in range(len(self.CLASSES)):
if old == new:
continue
mask = (before == old) & (after == new)
if mask.any():
key = f"{self.CLASSES[old]} -> {self.CLASSES[new]}"
transitions[key] = int(mask.sum())
return dict(sorted(transitions.items(),
key=lambda item: item[1], reverse=True))
np.random.seed(42)
labels = np.random.choice(6, size=(512, 512),
p=[0.30, 0.10, 0.20, 0.25, 0.05, 0.10])
report = LandUseReport(pixel_size_m=0.05)
rows, total = report.area_table(labels)
print(f"scene area: {total:.0f} m2")
for name, count, area, pct in rows:
print(f" {name:12s} {area:8.0f} m2 {pct:5.1f}%")
changed = labels.copy()
changed[100:160, 200:280] = 0
print(report.change_matrix(labels, changed))
Deploying for Inference on the Drone
Accuracy that cannot run onboard is not operationally useful. A small aircraft offers a few tens of watts for compute, a camera that delivers frames faster than you can process them, and no time for a cloud round trip when the model feeds obstacle avoidance. The standard toolkit addresses each limit: reduce input resolution while preserving small-object recall through tiling with overlapping windows; export to ONNX and execute with TensorRT or OpenVINO; apply INT8 quantization validated against a held-out flight; and stitch tile predictions with overlap so borders never produce discontinuous labels.
Post-processing deserves its own budget line. Morphological cleanup of speckled regions, polygon simplification before GIS export, and the georeferencing transforms that place labels in a coordinate system often cost more wall-clock time than inference itself at these resolutions, so profile the full path from shutter to shapefile rather than the network alone.
Common Mistakes
Reporting overall accuracy instead of mIoU
Fix: Dominant classes inflate accuracy; report per-class IoU and mIoU so failures on rare classes stay visible.
Training on tiles that leak across the split
Fix: Split by flight or geographic area, never by tile from the same frame, or validation scores will be fiction.
Ignoring class imbalance with plain cross-entropy
Fix: Combine cross-entropy with Dice loss and check per-class recall after every training run.
Skipping georeferencing before area calculations
Fix: Convert pixel counts through ground sampling distance in a projected coordinate system before quoting hectares.
Evaluating only at training resolution
Fix: Validate on untouched flights at deployment altitude â altitude and lighting shift break models that only saw one setting.
Best Practices
- Collect labels across seasons, altitudes, and lighting so the model sees the variance it will face in the field.
- Annotate with a consistent class taxonomy and a written guideline; inter-annotator disagreement is often the accuracy ceiling.
- Start with a strong baseline such as U-Net on a moderate backbone, then tune data and losses before searching for exotic architectures.
- Keep a geographically held-out flight as the final test set and never train against it.
- Version datasets, label maps, and model exports together so any published area figure can be reproduced later.
Key Takeaways
- Segmentation produces one label per pixel, enabling direct area, boundary, and coverage measurements that boxes cannot provide.
- Encoder-decoder networks with skip connections, led by U-Net, recover spatial precision while staying data efficient for small drone datasets.
- Dice and focal losses counter the heavy class imbalance of aerial scenes where background dominates the pixel count.
- mIoU with per-class reporting is the honest metric; overall accuracy hides failures on the rare classes that matter most.
- Production systems must budget tiling, quantization, georeferencing, and post-processing alongside raw model accuracy.