Sub topic 5
Instance segmentation: separating individual objects
This chapter assumes you know basic Python and NumPy, how convolutional networks classify images, and how object detectors produce boxes and confidence scores. It also assumes you have read the earlier chapters on label maps and mask stacks, and on things versus stuff.
What instance segmentation adds
Semantic segmentation gives every pixel a class, so two touching cars become one "car" region. Instance segmentation gives every detected object its own mask, so each car is separate and can be counted, tracked, or measured on its own.
Three properties set it apart:
- It covers things only. Instance segmentation labels countable objects such as people, cars, and cups. Amorphous regions such as sky, road, and grass (stuff) are usually left out.
- Pixels may stay unlabeled. Background pixels belong to no instance.
- Masks can overlap. Each instance is predicted independently, so two masks can claim the same pixel. This is the main difference from panoptic output, which must be non-overlapping.
Output format
A typical model returns, for each detected object:
- a class label
- a confidence score
- a box
- a mask
Masks are usually stored as a stack of binary arrays with shape (N, H, W), one per instance. This is the "mask stack" representation from earlier in the tutorial. Because the stack allows overlap, the number of instances N changes from image to image.
Some pipelines flatten the stack into one integer map, with 0 for background and 1, 2, 3, and so on for instances. That map has to resolve every overlap first, so it loses information.
Three ways to produce instances
| Strategy | Idea | Example | Main weakness |
|---|---|---|---|
| Top-down (detect, then segment) | Find boxes first, then predict a mask inside each box | Mask R-CNN | Mask quality depends on the box. Crowded scenes give many overlapping candidates. |
| Bottom-up (group pixels) | Predict per-pixel features or offsets, then cluster pixels into objects | Embedding or center-offset methods | Needs a grouping step that is sensitive to its parameters. |
| Query-based | A fixed set of learned queries each predict one mask and one class | Mask2Former, covered in a later chapter | Needs more training data and compute to converge. |
Top-down methods are the most common starting point, and the next chapter covers Mask R-CNN in detail. Here the focus is on using what such a model returns.
Running a pretrained model
This example uses torchvision's Mask R-CNN. It needs torch and torchvision, and the weights download on first use.
import torch
from torchvision.models.detection import maskrcnn_resnet50_fpn
model = maskrcnn_resnet50_fpn(weights="DEFAULT")
model.eval()
image = torch.rand(3, 480, 640) # replace with a real image: float tensor in [0, 1], shape (3, H, W)
with torch.no_grad():
output = model([image])[0]
keep = output["scores"] > 0.5
masks = output["masks"][keep, 0] > 0.5 # (N, H, W) boolean mask per detected instance
labels = output["labels"][keep]
boxes = output["boxes"][keep]
print(masks.shape, labels.tolist())The model has two thresholds, and they do different jobs.
- The score threshold (0.5 above) decides which detections you keep. It trades missed objects against false ones.
- The mask threshold (0.5 above) turns each soft mask, with per-pixel values between 0 and 1, into a binary mask. Lowering it grows the masks, and raising it shrinks them.
A random-noise image will usually give zero detections, so the printed shape may be torch.Size([0, 480, 640]). Use a real photo to see results.
The labels are integer IDs from the COCO category list, where 0 is background. The IDs are not contiguous (some are unused), so map them to names with the dataset's category table. Do not index into a list of 80 names.
Resolving overlaps
Many downstream uses need one ID per pixel: coloring a visualization, counting pixels per object, or feeding a panoptic merge. When masks overlap, you must pick a winner. A simple rule is that the higher score wins.
import numpy as np
def masks_to_id_map(masks, scores):
# masks: (N, H, W) bool; scores: length-N array. Returns (H, W) int32, 0 = background.
id_map = np.zeros(masks.shape[1:], dtype=np.int32)
for i in np.argsort(scores): # lowest score first, so the highest score is written last
id_map[masks[i]] = i + 1
return id_map
masks = np.zeros((2, 3, 4), dtype=bool)
masks[0, :, :3] = True # instance 1 covers columns 0-2
masks[1, :, 2:] = True # instance 2 covers columns 2-3, overlapping column 2
scores = np.array([0.9, 0.6])
print(masks_to_id_map(masks, scores))Column 2 is claimed by both instances. Instance 1 has the higher score, so it keeps that column. Mask area, depth ordering, or a learned rule could also decide, and the choice affects results. The panoptic chapter returns to this problem.
Failure modes and common errors
- Duplicate detections. Detectors suppress near-duplicate boxes with non-maximum suppression (NMS). If the IoU threshold is too high, one object gets two masks. If it is too low, two nearby objects collapse into one. Tune it on your own data, especially for crowds.
- Low-resolution masks. Top-down models predict a small mask per box (28×28 in Mask R-CNN) and resize it into the box. Thin structures and sharp edges come out smooth and blobby.
- Box errors become mask errors. If the box cuts off part of an object, the mask cannot recover it, because the mask head only sees the cropped region.
- Occlusion. When an object is split by another in front of it, the model may output one fragmented mask or two separate masks. Annotation guidelines decide which is correct.
- Missing stuff. Asking an instance model about "road" or "sky" gives nothing useful. Use a semantic or panoptic model for those classes.
- Mismatched image format. torchvision expects floats in [0, 1] with channels first. Passing uint8 values in 0–255 or an
(H, W, 3)array produces poor or failing results. - Memory growth. A mask stack costs
N × H × Wvalues. With hundreds of instances on large images, store masks as run-length encodings or polygons instead of dense arrays.
Choosing a method
- Use a top-down model when you need a strong baseline, good pretrained weights, and a clear box-plus-mask output.
- Use a bottom-up approach when objects are crowded, irregular, or not well described by boxes, such as cells in a microscope image.
- Use a query-based model when you want a single architecture that also handles semantic and panoptic tasks.
Exercise
A model returns three instance masks for an image. Masks A and B overlap on 200 pixels, and A has score 0.8 while B has score 0.7. You build an ID map with the rule from this chapter, where the higher score wins. Which instance owns the 200 shared pixels, and what do you lose in the resulting map?
Show answer
Instance A owns the shared pixels, because its score is higher and it is written last. The map loses B's full extent. B's 200 overlapping pixels are no longer recorded as part of B, so B's area and shape in the map are smaller than its original mask, and you can no longer tell from the map that the two objects overlapped.