Sub topic 13
Merging semantic and instance predictions into panoptic output
This chapter assumes you can read basic NumPy, know what a label map and a stack of binary instance masks are, and have seen output from a semantic model and a detect-then-segment model such as Mask R-CNN. Here you will combine the two outputs into one panoptic result. In that result every pixel has exactly one class and at most one instance ID.
Why the two outputs conflict
A semantic network and an instance network are trained separately or with separate heads. Each is internally consistent, but together they disagree in three ways.
- Overlapping instances. Instance masks are predicted independently, so two masks can claim the same pixel. This happens most often when two objects touch or one occludes the other.
- Semantic and instance disagreement. The semantic map may say "road" where an instance mask says "car". It may also say "car" where no instance mask exists.
- Duplicate or spurious instances. Detectors emit low-confidence or near-duplicate masks that you do not want in the final output.
Panoptic segmentation forbids overlap, so the merge step has to resolve each of these. It is a post-processing rule, not a trained component. This is the approach used by early panoptic systems such as Panoptic FPN. Later transformer models (see the mask classification chapter) produce non-overlapping segments directly, but they still apply a similar pixel-ownership rule at the end.
The merge rules
A simple and widely used set of rules works as follows.
- Filter by confidence. Discard instances below a score threshold, for example 0.5. Without this, false positives will overwrite correct stuff pixels.
- Sort by score. Process instances from highest to lowest confidence. Whoever is more certain wins contested pixels.
- Claim only free pixels. Each instance may take only pixels that no earlier instance took. Skip an instance that has no free pixels.
- Take stuff from the semantic map. Regions of stuff classes such as road and sky come from the semantic prediction, because instance models do not predict them.
- Void leftover thing pixels. If the semantic map says a pixel is a thing class but no instance claimed it, mark it void. The alternative is to guess an instance, which is usually worse.
The function below implements rules 2 to 5. It takes the filtered instances as input, so rule 1 happens in the caller.
import numpy as np
def merge_to_panoptic(semantic, inst_masks, inst_classes, inst_scores, thing_classes):
# semantic: (H, W) signed integer class map; inst_masks: (N, H, W) bool
# inst_classes, inst_scores: length-N arrays; thing_classes: list of class ids
out_class = semantic.copy()
out_inst = np.zeros(semantic.shape, dtype=np.int32) # 0 = no instance (stuff or void)
taken = np.zeros(semantic.shape, dtype=bool)
next_id = 1
for i in np.argsort(-np.asarray(inst_scores)): # highest score claims pixels first
free = inst_masks[i] & ~taken
if not free.any():
continue
out_class[free] = inst_classes[i]
out_inst[free] = next_id
taken |= free
next_id += 1
# Thing pixels in the semantic map that no instance claimed become void (-1).
is_thing = np.isin(semantic, thing_classes)
out_class[is_thing & ~taken] = -1
return out_class, out_inst
# Classes: 0 = road (stuff), 1 = car (thing), 2 = sky (stuff)
semantic = np.array([
[2, 2, 2, 2, 2, 2],
[0, 0, 1, 1, 1, 0],
[0, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 1],
])
def box_mask(r0, r1, c0, c1):
m = np.zeros(semantic.shape, dtype=bool)
m[r0:r1, c0:c1] = True
return m
masks = np.stack([
box_mask(1, 3, 2, 4), # car A, columns 2-3
box_mask(1, 3, 3, 5), # car B, columns 3-4, overlaps A at column 3
box_mask(3, 4, 0, 2), # spurious detection on the road
])
classes = np.array([1, 1, 1])
scores = np.array([0.9, 0.6, 0.3])
keep = scores >= 0.5 # rule 1: drop low-confidence instances
out_class, out_inst = merge_to_panoptic(
semantic, masks[keep], classes[keep], scores[keep], thing_classes=[1]
)
print(out_class)
print(out_inst)
# One common storage format: a single integer per pixel, class * 1000 + instance ID.
panoptic_id = np.where(out_class < 0, -1, out_class * 1000 + out_inst)
print(panoptic_id)Running this gives these results.
- Car A takes columns 2 and 3 and gets ID 1. Car B gets only column 4 and gets ID 2, because A won the contested column.
- The 0.3-score detection is dropped, so the road pixels beneath it stay road.
- The car pixel at the bottom right of the semantic map has no instance, so it becomes void (-1).
Design choices and failure modes
The rules above are a baseline. Each one is a trade-off you may need to change.
| Choice | Default | Alternative | Effect |
|---|---|---|---|
| Conflict order | Score, highest first | Mask area, or a learned ranking | Score favors confident detections. Area can stop a large, uncertain mask from swallowing small objects. |
| Instance vs semantic | Instance wins on things | Semantic wins | Instance masks usually have sharper boundaries. Semantic maps can be more reliable for the class label. |
| Leftover thing pixels | Void | Reassign to the nearest instance | Void keeps errors visible to the metric. Reassigning can hide missed detections. |
| Tiny segments | Keep | Drop below a minimum area | Dropping removes speckle, but it also removes real small objects. |
Two additional rules from the original panoptic heuristic are worth knowing.
- Overlap rejection. After pixel claiming, discard an instance if too little of its mask survived. A common threshold is that less than half of the original mask remains. This removes duplicates that were almost entirely covered by a better detection.
- Stuff area filter. Drop stuff regions smaller than a minimum area, and mark those pixels void.
Typical failure modes follow from the rules.
- Thin or fragmented masks. A high-scoring but sloppy mask can steal pixels from a better mask. Check boundaries visually on touching objects.
- Thresholds that differ between models. A score cutoff of 0.5 is not equally strict for every detector. Tune it on a validation set using panoptic quality, not by eye.
- Soft mask threshold. Mask R-CNN returns per-pixel probabilities. The 0.5 binarization step happens before merging, and it changes which pixels overlap.
- Class mismatch. If a thing instance sits on pixels that the semantic model calls stuff, the instance overwrites them. A noisy detector can therefore cut holes in large stuff regions.
Checklist before you trust a merged result
- Confirm that
thing_classesmatches your label space. A wrong list silently turns real things into stuff or void. - Confirm that void uses a value that cannot collide with a real class ID.
- Check that no pixel has two owners. By construction the
takenmap guarantees this, but any custom variant needs a test. - Verify that the number of unique
(class, instance)pairs equals the number of segments you expect. - Score the output with panoptic quality (next chapter) rather than judging from visualizations.
Exercise
In the demo above, suppose car B had a score of 0.95 instead of 0.6. Which car owns column 3, what IDs do the cars get, and how many pixels does car A keep?
Show answer
Car B is now processed first, so it gets ID 1 and claims columns 3 and 4 in rows 1 and 2 (4 pixels). Car A gets ID 2 and can claim only column 2 in rows 1 and 2 (2 pixels), because column 3 is already taken. Car B owns column 3. Car A keeps 2 pixels, down from 4. If you applied an overlap rejection rule that discards instances with under half of their mask remaining, car A would still survive, since 2 of its 4 pixels remain, which is exactly half.