Instance Segmentation: Watershed and Mask R-CNN
Semantic segmentation gives every pixel a class, so seven coins lying on a table become one "coin" region. To count them, measure each one or pick one up with a robot, you need instance segmentation: a separate mask, class and score for every object. This lesson first separates touching objects without any learning, with connected components, the distance transform and the watershed, then looks at how the standard learned model, Mask R-CNN, adds a mask to every box of a detector, and how instance results are scored.
Three kinds of segmentation
| Task | Output | Two touching coins | Things vs stuff |
|---|---|---|---|
| Semantic | one class id per pixel | one "coin" region | no distinction |
| Instance | a mask + class + score per object; masks may overlap, background is not labelled | two masks | only countable things (cars, people, coins) |
| Panoptic | every pixel gets a class and, for things, an instance id; no overlaps | two ids, plus "table" as stuff | things and amorphous stuff (road, sky, grass) |
Panoptic segmentation (Kirillov et al., 2019) unifies the two: stuff classes are segmented semantically, thing classes per instance. Annotations for both are polygons or masks per object (masks, polygons and RLE).
Touching objects: why connected components are not enough
The classical route is: threshold the image into foreground and background, then call every connected blob of foreground one object (morphology and contours). It works as long as objects do not touch. The data here are lesson-specific: 96 x 96 grey images with seven bright discs ("coins", radius 7 to 11 pixels) that may touch and overlap a little, with an exact instance map as ground truth.
The fix is a classic of mathematical morphology. The distance transform gives every foreground pixel its distance to the nearest background pixel. Inside a disc it rises to a peak at the centre; where two discs touch it dips to a saddle at the neck. One local maximum per object is a marker. The watershed then treats the negated distance as a landscape and floods it from the markers; where floods from two markers meet, it draws a boundary. The result splits touching blobs along their necks.
import numpy as np, cv2
from scipy import ndimage as ndi
from skimage.feature import peak_local_max
from skimage.segmentation import watershed
cv2.setLogLevel(0)
def make_touching(rng, n=7, size=96):
"""Lesson-specific generator: n bright discs (radius 7..11) on a dark noisy background, allowed to
touch and overlap a little, like coins on a table. Returns grey uint8 image and an instance map
(0 = background, 1..n = disc id; where discs overlap the later disc wins)."""
inst = np.zeros((size, size), np.int32); discs = []
while len(discs) < n:
r = int(rng.integers(7, 12)); cx, cy = rng.integers(r, size - r, 2)
if all(np.hypot(cx - x, cy - y) >= 0.7 * (r + q) for x, y, q in discs):
discs.append((int(cx), int(cy), r))
for k, (cx, cy, r) in enumerate(discs):
cv2.circle(inst, (cx, cy), r, k + 1, -1)
img = np.where(inst > 0, 170.0, 60.0) + rng.normal(0, 10, inst.shape)
return img.clip(0, 255).astype(np.uint8), inst
def watershed_instances(fg, min_distance=5):
"""Markers = local maxima of the distance transform, then flood -distance from them inside fg."""
dist = ndi.distance_transform_edt(fg)
peaks = peak_local_max(dist, min_distance=min_distance, labels=ndi.label(fg)[0])
markers = np.zeros(fg.shape, np.int32)
markers[tuple(peaks.T)] = np.arange(1, len(peaks) + 1)
return watershed(-dist, markers, mask=fg), dist
rng = np.random.default_rng(0)
img, inst = make_touching(rng)
_, fg = cv2.threshold(img, 0, 1, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # Otsu: foreground = 1
fg = cv2.morphologyEx(fg, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8)) # remove noise specks
n_cc, cc, stats, _ = cv2.connectedComponentsWithStats(fg)
ws, dist = watershed_instances(fg > 0)
print("true discs:", inst.max(), "| connected components:", n_cc - 1, "| watershed regions:", ws.max())
print("component areas:", sorted(stats[1:, cv2.CC_STAT_AREA].tolist()))
print("watershed areas:", sorted(np.bincount(ws.ravel())[1:].tolist()))
print("true areas: ", sorted(np.bincount(inst.ravel())[1:].tolist()))
print(f"distance transform: max {dist.max():.1f} px (the largest radius)")
# Five images more: counts only
for i in range(5):
img, inst = make_touching(rng)
_, fg = cv2.threshold(img, 0, 1, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
fg = cv2.morphologyEx(fg, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
print(f"image {i + 1}: true {inst.max()}, components {cv2.connectedComponents(fg)[0] - 1}, watershed {watershed_instances(fg > 0)[0].max()}")true discs: 7 | connected components: 6 | watershed regions: 7
component areas: [145, 193, 249, 373, 373, 567]
watershed areas: [145, 193, 194, 249, 373, 373, 373]
true areas: [149, 197, 197, 253, 376, 377, 377]
distance transform: max 11.0 px (the largest radius)
image 1: true 7, components 5, watershed 7
image 2: true 7, components 5, watershed 7
image 3: true 7, components 6, watershed 7
image 4: true 7, components 6, watershed 7
image 5: true 7, components 4, watershed 7
In the first image the connected components count 6 coins instead of 7, and the areas show why: the component of 567 pixels is two coins (194 + 373 in the watershed) merged into one blob. In the five further images the components miss one to three coins each. The watershed recovers the separate coins because each has its own peak in the distance transform. Its areas are close to, but a few pixels below, the true ones: the Otsu threshold and the opening shave a little off every outline, and where two discs overlap the watershed cuts along the neck, while the ground truth gives the whole overlap to the disc drawn last.
The method has one important knob, the minimum distance between markers (min_distance=5). Too small, and the noisy edge of a big coin produces two peaks and the coin is split (over-segmentation); too large, and two small touching coins share one marker (under-segmentation). With real images the markers often come from somewhere else: a blurred image's maxima, a threshold on the distance transform, or a detector's boxes. The watershed is still used today, for example to split touching cells in microscopy, often on a network's predicted distance map instead of a hand-made one.
Scoring instances: matching masks
Evaluating instances needs a matching step, exactly as for detection boxes, with mask IoU in place of box IoU: the IoU of two pixel sets. A predicted instance is a true positive when its mask IoU with an unmatched ground-truth instance is at least the threshold. Two scores are standard:
- Mask AP, the COCO detection metric computed with mask IoU: per class, rank the instances by score, match, build the precision-recall curve, average over IoU 0.5 to 0.95 (detection metrics builds it; nothing changes except the IoU). It needs scores, which a watershed does not produce.
- Panoptic quality (PQ), which needs no scores. Match with IoU greater than 0.5: then no two predictions can match the same object (two masks that each cover more than half of the union of themselves with an object cannot both exist without overlapping), so the matching is unique and needs no ranking. With TP, FP, FN the matched, unmatched predicted and unmatched true instances:
SQ says how good the matched masks are, RQ is an score of finding the objects. Both methods on 20 generated images (140 coins):
import numpy as np, cv2
from scipy import ndimage as ndi
from skimage.feature import peak_local_max
from skimage.segmentation import watershed
cv2.setLogLevel(0)
def make_touching(rng, n=7, size=96):
"""Lesson-specific generator: n bright discs (radius 7..11) on a dark noisy background, allowed to
touch and overlap a little, like coins on a table. Returns grey uint8 image and an instance map
(0 = background, 1..n = disc id; where discs overlap the later disc wins)."""
inst = np.zeros((size, size), np.int32); discs = []
while len(discs) < n:
r = int(rng.integers(7, 12)); cx, cy = rng.integers(r, size - r, 2)
if all(np.hypot(cx - x, cy - y) >= 0.7 * (r + q) for x, y, q in discs):
discs.append((int(cx), int(cy), r))
for k, (cx, cy, r) in enumerate(discs):
cv2.circle(inst, (cx, cy), r, k + 1, -1)
img = np.where(inst > 0, 170.0, 60.0) + rng.normal(0, 10, inst.shape)
return img.clip(0, 255).astype(np.uint8), inst
def watershed_instances(fg, min_distance=5):
dist = ndi.distance_transform_edt(fg)
peaks = peak_local_max(dist, min_distance=min_distance, labels=ndi.label(fg)[0])
markers = np.zeros(fg.shape, np.int32)
markers[tuple(peaks.T)] = np.arange(1, len(peaks) + 1)
return watershed(-dist, markers, mask=fg)
def mask_iou_matrix(a, b):
"""IoU of every instance in label map a (ids 1..A) with every instance in label map b (ids 1..B)."""
A, B = a.max(), b.max()
inter = np.bincount(a.ravel() * (B + 1) + b.ravel(), minlength=(A + 1) * (B + 1)).reshape(A + 1, B + 1)[1:, 1:]
area_a, area_b = np.bincount(a.ravel(), minlength=A + 1)[1:], np.bincount(b.ravel(), minlength=B + 1)[1:]
return inter / (area_a[:, None] + area_b[None, :] - inter)
def match_counts(gt, pred):
iou = mask_iou_matrix(gt, pred)
matched = iou > 0.5 # IoU > 0.5 makes the matching unique: no ranking needed
tp = int(matched.sum())
return tp, int(pred.max()) - tp, int(gt.max()) - tp, float(iou[matched].sum())
for name in ["components", "watershed"]:
TP = FP = FN = 0; iou_sum = 0.0
rng = np.random.default_rng(0) # the same 20 images for both methods
for i in range(20):
img, inst = make_touching(rng)
_, fg = cv2.threshold(img, 0, 1, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
fg = cv2.morphologyEx(fg, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
pred = cv2.connectedComponents(fg)[1] if name == "components" else watershed_instances(fg > 0)
tp, fp, fn, s = match_counts(inst, pred)
TP += tp; FP += fp; FN += fn; iou_sum += s
sq = iou_sum / max(TP, 1); rq = TP / (TP + 0.5 * FP + 0.5 * FN)
print(f"{name:10s} TP {TP:3d} FP {FP:3d} FN {FN:3d} SQ {sq:.3f} RQ {rq:.3f} PQ {sq * rq:.3f}")components TP 91 FP 12 FN 49 SQ 0.942 RQ 0.749 PQ 0.705
watershed TP 138 FP 0 FN 2 SQ 0.960 RQ 0.993 PQ 0.953
Connected components find 91 of the 140 coins. Each merged blob costs twice: it matches at most one of its coins (often none, if no coin covers more than half of the blob), and the remaining coins are false negatives; a merged blob that matches nothing is also a false positive. The watershed finds 138 coins with no false positive, and its masks are better too (SQ 0.960 against 0.942), giving PQ 0.953 against 0.705. The two coins it still misses are most likely in pairs that overlap so much that the distance transform has a single peak (the generator allows centres as close as 0.7 times the sum of the radii); print the per-image counts to find them.
Mask R-CNN: a mask for every box
Hand-made markers do not generalise to cars, people and cats. Mask R-CNN (He, Gkioxari, Dollar and Girshick, 2017) takes the two-stage detector of the Faster R-CNN lesson and adds a third head beside the box classifier and box regressor:
- A backbone with a feature pyramid (FPN) computes feature maps at strides 4 to 64; the region proposal network proposes boxes.
- For each proposal, RoI Align samples a fixed-size feature grid from the right pyramid level with bilinear interpolation, without rounding coordinates (rounding, as RoI pooling did, shifts masks by up to a feature cell; that half-pixel care is what made the masks precise). The box head uses grids, the mask head .
- The mask head, four convolutions and a transposed convolution, outputs a mask per class for each RoI. Only the mask of the predicted class is used, and it is trained with a per-pixel binary cross-entropy, so classes do not compete for pixels; classification is left to the box head.
- At inference each mask is resized to its box, pasted into the image and thresholded at 0.5.
Step 4 sets a resolution limit: however large the object, its mask has only cells. What that costs is easy to measure from scratch, by sending exact masks through a grid and back:
import numpy as np, cv2
cv2.setLogLevel(0)
def shape_mask(kind, s):
"""An s x s canvas with a filled shape touching its borders (the box is the canvas)."""
m = np.zeros((s, s), np.uint8)
if kind == "circle":
cv2.circle(m, (s // 2, s // 2), s // 2, 1, -1)
elif kind == "triangle":
cv2.fillPoly(m, [np.array([[s // 2, 0], [0, s - 1], [s - 1, s - 1]], np.int32)], 1)
else: # a thin ring, like a bicycle wheel: the hardest case
cv2.circle(m, (s // 2, s // 2), s // 2 - 1, 1, max(1, s // 40))
return m
def through_mask_head(m, res=28):
"""The best a res x res mask head can do: the exact mask averaged into res x res cells,
resized back to the box and thresholded at 0.5."""
small = cv2.resize(m.astype(np.float32), (res, res), interpolation=cv2.INTER_AREA)
back = cv2.resize(small, (m.shape[1], m.shape[0]), interpolation=cv2.INTER_LINEAR)
return back >= 0.5
print("mask IoU after a 28 x 28 round trip, by box size")
for kind in ["circle", "triangle", "ring"]:
row = []
for s in [16, 64, 256, 512]:
m = shape_mask(kind, s) > 0
p = through_mask_head(m)
row.append(f"{s:3d} px {np.sum(m & p) / np.sum(m | p):.3f}")
print(f"{kind:8s} " + " ".join(row))mask IoU after a 28 x 28 round trip, by box size
circle 16 px 1.000 64 px 0.988 256 px 0.988 512 px 0.988
triangle 16 px 1.000 64 px 0.998 256 px 0.991 512 px 0.991
ring 16 px 1.000 64 px 0.000 256 px 0.526 512 px 0.416
For compact shapes the limit is mild: a perfect mask head still reaches mask IoU 0.988 on a circle and about 0.99 on a triangle, whatever the box size, and boxes smaller than 28 pixels lose nothing. Thin structures are another matter: a 1-pixel ring in a 64-pixel box disappears completely (IoU 0.000, every cell is mostly empty), and a 12-pixel ring in a 512-pixel box keeps an IoU of only 0.416. That is why Mask R-CNN's masks look soft at the outline of large objects and miss bicycle spokes and chair legs, and why later models (PointRend, Mask2Former) predict masks at higher resolution or refine boundary points.
torchvision builds the full model. The COCO weights are not cached in this course's image, so the model below has random weights: the output format and the shapes are real, the boxes and masks are noise.
import torch
from torchvision.models.detection import maskrcnn_resnet50_fpn
from skimage import data
torch.manual_seed(0)
# Random weights (no download): structure and output format only, the detections are meaningless.
model = maskrcnn_resnet50_fpn(weights=None, weights_backbone=None, num_classes=4, min_size=256, max_size=320).eval()
print(f"parameters: {sum(p.numel() for p in model.parameters()) / 1e6:.1f} M")
print("RoI Align grid: box head", model.roi_heads.box_roi_pool.output_size, "| mask head", model.roi_heads.mask_roi_pool.output_size)
roi_feats = torch.rand(3, 256, 14, 14) # 3 RoIs after RoI Align, 256 FPN channels
with torch.no_grad():
mask_logits = model.roi_heads.mask_predictor(model.roi_heads.mask_head(roi_feats))
print("mask head output for 3 RoIs:", tuple(mask_logits.shape), "= one 28 x 28 mask per class (background included)")
img = torch.tensor(data.coffee()).permute(2, 0, 1).float() / 255 # (3, 400, 600), RGB in 0..1
with torch.no_grad():
batch = model.transform([img])[0]
feats = model.backbone(batch.tensors)
out = model([img])[0]
print("resized and padded input:", tuple(batch.tensors.shape[-2:]))
print("FPN levels:", {k: tuple(v.shape[-2:]) for k, v in feats.items()})
for k, v in out.items():
print(f"output {k:6s} {tuple(v.shape)} {v.dtype}")parameters: 44.0 M
RoI Align grid: box head (7, 7) | mask head (14, 14)
mask head output for 3 RoIs: (3, 4, 28, 28) = one 28 x 28 mask per class (background included)
resized and padded input: (224, 320)
FPN levels: {'0': (56, 80), '1': (28, 40), '2': (14, 20), '3': (7, 10), 'pool': (4, 5)}
output boxes (100, 4) torch.float32
output labels (100,) torch.int64
output scores (100,) torch.float32
output masks (100, 1, 400, 600) torch.float32
The interface is the detection interface plus masks: a list with one dictionary per image, boxes in the original image's pixel coordinates [x1, y1, x2, y2], labels, scores, and masks of shape already pasted into the full image as probabilities (threshold at 0.5 for binary masks). The model resizes the 600 x 400 coffee image so that its short side is 256 unless the long side would then exceed max_size=320, which is the case here: it becomes 213 x 320, padded to 224 x 320 (a multiple of 32). It then runs the five FPN levels from stride 4 (56 x 80) to stride 64, and maps everything back. The mask head returns one mask per class for every RoI. With trained weights, the usage on your own machine is:
# Not run here: needs the COCO weights (a download of about 170 MB)
import torch
from torchvision.models.detection import maskrcnn_resnet50_fpn_v2, MaskRCNN_ResNet50_FPN_V2_Weights
weights = MaskRCNN_ResNet50_FPN_V2_Weights.COCO_V1
model = maskrcnn_resnet50_fpn_v2(weights=weights).eval()
with torch.no_grad():
out = model([weights.transforms()(image_tensor)])[0]
keep = out["scores"] > 0.5
masks = out["masks"][keep, 0] > 0.5 # (n, H, W) boolean, one per object
names = [weights.meta["categories"][i] for i in out["labels"][keep]]Two other model families are worth knowing, also shown without running (their weights are not cached here):
# Not run here: YOLO segmentation weights and SAM weights are downloads
from ultralytics import YOLO
seg = YOLO("yolo11n-seg.pt") # one-stage: boxes + mask coefficients x 32 prototype masks
r = seg.predict(image_bgr, conf=0.25, verbose=False)[0]
polygons = r.masks.xy # one polygon per instance, in image pixels
# Segment Anything (SAM): class-agnostic masks from a prompt (a point, a box, or "everything")
from ultralytics import SAM
sam = SAM("sam2.1_b.pt")
r = sam.predict(image_bgr, bboxes=[[100, 50, 300, 260]], verbose=False)[0] # mask for the object in this box| Model | Idea | Strength | Weakness |
|---|---|---|---|
| Watershed + markers | flood the distance map from one marker per object | no training, exact boundaries on clean images | needs good markers; one object type at a time |
| Mask R-CNN (2017) | detector + per-RoI mask head | strong, well understood, many pretrained versions | soft outlines on large objects, two-stage speed |
| YOLO-seg (YOLACT idea, 2019) | per image prototype masks, per box coefficients | real time | less precise masks |
| Mask2Former (2022) | transformer queries, one mask per query, panoptic too | top accuracy, one model for all three tasks | heavy, needs pretraining |
| SAM (2023) | promptable, class-agnostic masks | masks for anything you point at; great for annotation | no classes: pair it with a detector or a human |
SAM changed annotation more than deployment: a click or a rough box gives a precise mask, so polygon labelling became much cheaper (annotation tasks). For fine-tuning any of these on your own classes, start from the pretrained weights (transfer learning).
Pitfalls
- Merged blobs counted as one. Connected components are an instance method only when objects never touch. Check counts against a labelled sample before trusting them.
- Over- and under-segmentation with the watershed. Tune the marker rule on labelled images and report both FP (splits) and FN (merges), not only the count, since a split and a merge can cancel in a count.
- Overlapping masks. Instance masks may overlap (an occluded person behind another), panoptic labels may not. Converting instance output to a panoptic or semantic map needs a rule (highest score wins); converting ground truth needs the same rule as the annotation tool.
- Mask AP vs box AP. They are different numbers on the same detections; a model can have good boxes and poor masks. Say which one you report, and at which IoU thresholds.
- Mask resolution. masks cannot represent thin structures in large boxes (the ring above); if your objects are wires, vessels or cracks, use a semantic segmenter at full resolution.
- Small objects. A few pixels of mask error ruin the IoU of a small object; COCO reports AP separately for small, medium and large objects (detection metrics).
Practice
- Two coins of radius 10 touch at one point (centres 20 apart). What is the maximum of the distance transform, and what is its value at the point where they touch?
Answer
The maximum is about 10 at each centre (distance to the nearest edge). At the touching point the foreground is only a pixel or two wide, so the distance there is about 1. The profile along the line between the centres goes 10, down to about 1, up to 10: two clear peaks, and the watershed splits the blob there. Coins that overlap deeply have a shallow saddle, and when the saddle is close to the peaks a single marker is found (the watershed's two misses above).
- A method finds 8 of 10 objects with matched mask IoUs that average 0.80, and makes 2 false detections. Compute SQ, RQ and PQ.
Answer
SQ = 0.80. RQ . PQ .
- Why does Mask R-CNN predict one mask per class with a sigmoid, instead of one mask with a softmax over classes?
Answer
The box head already decides the class. Separate binary masks mean the mask head only has to answer "which pixels of this box belong to the object", without classes competing for pixels. The Mask R-CNN paper reported clearly better mask AP with per-class sigmoid masks than with a softmax over classes. At inference only the predicted class's mask is used.
- In the watershed example, what happens to the count if you change
min_distancefrom 5 to 15? Predict, then run it.
Answer
Peaks closer than 15 pixels are merged into one, and the centres of touching coins of radius 7 to 11 are often closer than that, so some touching pairs get a single marker: the count drops towards the connected-components count. Very small values (1 or 2) can do the opposite on noisy edges and split a coin. The example's numbers change accordingly; the right value comes from the object size (here about half the smallest diameter).
Test yourself
Seven coins, three of them touching in a chain. How many objects does thresholding plus connected components report?
- 7
- 5: the chain of three becomes one blob
- 3
- 1
What are the markers of the watershed in this lesson?
- The edges found by Canny
- The local maxima of the distance transform of the foreground, one per object
- Random seed points
- The corners of the bounding boxes
Why does matching with IoU greater than 0.5 not need a greedy or Hungarian step in panoptic quality?
- Because there are no scores
- Because two non-overlapping predicted masks cannot both have IoU above 0.5 with the same object, so each object matches at most one prediction
- Because PQ ignores false positives
- Because masks are binary
A Mask R-CNN segments large buildings with soft, rounded outlines. What is the most likely reason?
- The backbone is too deep
- Each mask is predicted on a grid and resized to the box, so detail finer than one grid cell of a large box is lost
- The NMS threshold is too high
- RoI Align rounds coordinates