Instance segmentation: which pixels belong to which object?
实例分割
Separate object identity from foreground labels, trace mask matching and AP, and run a component baseline that fails after one extra pixel.
instance-segmentationOne extra pixel can turn two objects into one
Consider a small synthetic image containing two bright rectangles, each covering 12 pixels. Thresholding the image and grouping connected foreground pixels finds both objects. Now brighten a single pixel in the gap. The foreground prediction changes by only one pixel, but the two components become one.
The foreground intersection-over-union is still 24/25, or 0.96. Against either individual object, the merged prediction has intersection 12 and union 25: its instance IoU is only 0.48. At a matching threshold of 0.5, neither object is successfully detected. The program below produces these numbers from actual masks.
Semantic segmentation asks for the category at each pixel. Instance segmentation also asks which particular object those pixels belong to. Two people share a category, but must have different instance identities. Mask R-CNN combines object detection with a mask for each detected region; it is one approach to this task, not its definition. Mask R-CNN, §3
Represent identities before choosing a score
A mask is not a box, and a category is not an identity
For an image of height H and width W, represent predictions as a set of binary masks, category labels and confidence scores. The number N is part of the prediction:
The score ranks predictions; it is not automatically a calibrated probability of a correct instance. Instance index i only identifies an entry in this image. Tracking the same object across video frames is another task.
An integer label image stores one instance ID per pixel, with 0 often reserved for background. It is convenient for disjoint visible regions. A stack of separate masks can also represent overlap; collapsing it to one integer map requires a conflict rule and can discard information. Whether annotations cover visible parts or also infer hidden parts must be specified by the dataset. Our example covers only the provided binary pixels.
A box contains less geometric information than a mask. On a 2×2 grid, the main diagonal and the other diagonal have the same full-image bounding box but no foreground pixels in common. Their box IoU is 1 and mask IoU is 0. Evaluating masks with box overlap therefore measures the wrong object geometry.
Ordinary overlap and crowd overlap answer different questions
For ordinary binary masks P and G, count their foreground intersection and union:
The code defines zero for an empty union and rejects empty ground-truth instances in evaluation. That is an explicit teaching contract, not a meaningful annotation of an object with no pixels. Different spatial dimensions are rejected.
COCO treats a marked crowd region differently. A detection can describe part of a crowd, so the overlap used for that marked GT is intersection divided by the detection’s area:
A one-pixel detection contained inside a nine-pixel crowd region has ordinary IoU 1/9 but crowd overlap 1. This does not mean the detection becomes an ordinary true positive in every summary: crowd matching and ignoring are coordinated by the evaluator. Read the mask utility and matching logic together. Fixed mask API, C overlap implementation
A duplicate mask must not detect the same object twice
Within one image and category, sort predictions by descending confidence and apply the detection limit. Process them in that order. For each prediction, select the best available GT overlap meeting the threshold. An ordinary GT can be used once. A second prediction of that same object becomes a false positive unless it matches a different still-available GT.
This greedy matching is not the global cost assignment used during DETR training. The evaluation order gives confidence a concrete role. Equal-confidence predictions retain their input order in our program; equal candidate IoUs update to the later GT. These choices make ties reproducible. The fixed COCO implementation also handles reusable crowd GT, preferred ordinary matches and area/ignore rules, which our deliberately narrower evaluator omits. Its preparation code does not simply preserve an arbitrary supplied ignore field: for these tasks it replaces that value using iscrowd. Fixed evaluator, preparation and per-image matching
Precision, recall and a specified AP
After the first k ranked detections, let T(k) and F(k) be cumulative true and false positives, and let G be the number of applicable GT instances:
Interpolated precision at a recall threshold takes the best precision achieved at that threshold or higher. If no detection reaches it, use zero. Our single-threshold, single-category, single-image AP is:
The maximum over an empty set is defined as zero here. If there is no applicable GT, AP is undefined and the program returns None; it is not a perfect score or a zero. With GT but no predictions, AP is zero. The 101-point interpolation follows the fixed evaluator’s accumulation procedure, but this local result is not full COCO AP: it uses one chosen IoU threshold and omits dataset-wide aggregation, multiple thresholds, area ranges and crowd/ignore handling. Fixed evaluator, accumulation
For two GT objects and the ranked sequence TP, duplicate FP, TP, recall is 0.5, 0.5, 1 and precision is 1, 1/2, 2/3. There are 51 recall thresholds from 0 through 0.5 and 50 above 0.5. Consequently:
Encoding and computational cost
Run-length encoding stores lengths of successive background/foreground runs. COCO expects column-major binary mask layout, and a run list begins with the zero run, possibly of length zero. For [[1,0,1],[0,1,0]], column-major runs are [0,1,2,2,1]; row-major traversal gives a different list. A compressed COCO counts string is another representation, not the literal Python list printed here. RLE contract and wrappers
Simple shapes often compress well. Alternating pixels can require a number of runs proportional to the pixel count, so do not turn a favorable shape assumption into a universal square-root bound.
With P=HW pixels and fixed 4/8-neighbor connectivity, breadth-first component labeling uses O(P) time and O(P) space. Materializing N full masks costs O(NP) space. A straightforward comparison of N predictions with G GT masks costs O(NGP) time and stores O(NG) overlaps; sorting costs O(N log N), and greedy matching O(NG). These costs describe this code, not an optimized encoded-mask backend.
Run a baseline that makes the failure visible
The following complete program needs Python 3.12 and NumPy 1.26.4. It thresholds a finite grayscale image, labels connected components and ranks them by mean region intensity. This works as a baseline when objects are separated bright regions. Mean intensity is a convenient synthetic ranking rule, not a learned confidence estimator.
The evaluator accepts binary mask stacks so that overlap is retained. It requires nonempty GT masks, finite scores, integer category labels and one common image size. The profile covers ordinary instances only. Change connectivity from 4 to 8 to see diagonally touching pixels merge; neither setting can reliably split two objects joined by foreground pixels.
"""Original threshold/component baseline and one-image, one-class mask AP.
Ordinary, nonignored instances only. No crowd/area filters, multiple-image
aggregation or full COCO evaluator. AP uses 101-point interpolated precision
at one specified IoU threshold. Binary mask stacks can preserve overlap.
"""
import json
from collections import deque
import numpy as np
def binary(value, dimensions):
a = np.asarray(value)
if a.ndim != dimensions or min(a.shape[-2:]) < 1 or a.dtype.kind not in 'buif' or not np.isin(a, [0, 1]).all():
raise ValueError('binary arrays with nonempty height and width required')
return a.astype(bool)
def components(mask, connectivity=4):
mask = binary(mask, 2)
if connectivity not in (4, 8):
raise ValueError('connectivity must be 4 or 8')
directions = [(dy, dx) for dy in (-1, 0, 1) for dx in (-1, 0, 1)
if (dy or dx) and (connectivity == 8 or abs(dy)+abs(dx) == 1)]
labels = np.zeros(mask.shape, int)
height, width = mask.shape
label = 0
for y, x in np.argwhere(mask):
if labels[y, x]:
continue
label += 1
labels[y, x] = label
queue = deque([(y, x)])
while queue:
yy, xx = queue.popleft()
for dy, dx in directions:
ny, nx = yy+dy, xx+dx
if 0 <= ny < height and 0 <= nx < width and mask[ny, nx] and not labels[ny, nx]:
labels[ny, nx] = label
queue.append((ny, nx))
return labels
def baseline(image, threshold=.5, connectivity=4):
image = np.asarray(image, float)
if image.ndim != 2 or min(image.shape) < 1 or not np.isfinite(image).all() or not np.isfinite(threshold):
raise ValueError('finite nonempty grayscale image and threshold required')
labels = components(image >= threshold, connectivity)
masks = np.array([labels == i for i in range(1, int(labels.max())+1)], bool).reshape(-1, *image.shape)
# Region mean intensity ranks this toy baseline; it is not a calibrated
# probability that the region is a correctly separated object.
scores = np.array([image[mask].mean() for mask in masks])
return masks, scores, labels
def mask_iou(predicted, truth):
p, g = binary(predicted, 3), binary(truth, 3)
if p.shape[1:] != g.shape[1:]:
raise ValueError('matching image dimensions required')
result = np.zeros((len(p), len(g)))
for i, pm in enumerate(p):
for j, gm in enumerate(g):
union = np.count_nonzero(pm | gm)
result[i, j] = np.count_nonzero(pm & gm)/union if union else 0.
return result
def category_array(labels, count):
a = np.asarray(labels)
if a.shape != (count,) or a.dtype.kind not in 'iu' or np.any(a < 0):
raise ValueError('nonnegative integer categories of the correct length required')
return a
def evaluate(truth, truth_classes, predicted, predicted_classes, scores,
category=1, threshold=.5, max_detections=100):
g, p = binary(truth, 3), binary(predicted, 3)
gc, pc = category_array(truth_classes, len(g)), category_array(predicted_classes, len(p))
scores = np.asarray(scores, float)
if g.shape[1:] != p.shape[1:] or scores.shape != (len(p),) or not np.isfinite(scores).all():
raise ValueError('same image size and finite score per prediction required')
if np.any(g.sum(axis=(1, 2)) == 0):
raise ValueError('ground-truth instance masks must be nonempty')
if type(category) is not int or category < 0 or not np.isfinite(threshold) or not 0 < threshold <= 1:
raise ValueError('nonnegative category and IoU threshold in (0,1] required')
if type(max_detections) is not int or max_detections < 1:
raise ValueError('positive integer detection limit required')
gt = np.flatnonzero(gc == category)
dt = np.flatnonzero(pc == category)
dt = dt[np.argsort(-scores[dt], kind='stable')[:max_detections]]
overlaps = mask_iou(p[dt], g[gt])
used = np.zeros(len(gt), bool)
matches = np.full(len(dt), -1, int)
for i in range(len(dt)):
best, chosen = threshold, -1
for j in range(len(gt)):
if not used[j] and overlaps[i, j] >= best:
best, chosen = overlaps[i, j], j
if chosen >= 0:
used[chosen] = True
matches[i] = int(gt[chosen])
tp = np.cumsum(matches >= 0)
precision = tp/np.arange(1, len(dt)+1)
# No applicable GT: AP is undefined, not a perfect score or a zero.
recall = tp/len(gt) if len(gt) else np.full(len(dt), np.nan)
ap = None
if len(gt):
envelope = np.maximum.accumulate(precision[::-1])[::-1]
positions = np.searchsorted(recall, np.linspace(0, 1, 101), side='left')
samples = np.zeros(101)
valid = positions < len(dt)
samples[valid] = envelope[positions[valid]]
ap = float(samples.mean())
return {'ap101': ap, 'detectionIndices': dt.tolist(), 'matchedTruthIndices': matches.tolist(),
'truePositive': (matches >= 0).tolist(), 'precision': precision.tolist(),
'recall': recall.tolist() if len(gt) else None, 'groundTruthCount': len(gt)}
def demo():
truth = np.zeros((2, 10, 12), bool)
truth[0, 2:6, 2:5] = True
truth[1, 2:6, 6:9] = True
image = np.where(truth.any(axis=0), .9, .1)
separate, scores, _ = baseline(image)
first = evaluate(truth, [1, 1], separate, np.ones(len(separate), int), scores)
image[3, 5] = .9 # One extra foreground pixel joins the two objects.
merged, scores, _ = baseline(image)
second = evaluate(truth, [1, 1], merged, np.ones(len(merged), int), scores)
semantic = np.count_nonzero(truth.any(axis=0) & merged.any(axis=0))/np.count_nonzero(truth.any(axis=0) | merged.any(axis=0))
assert first['ap101'] == 1 and second['ap101'] == 0
return {'separatePredictions': len(separate), 'separateAP50_101': first['ap101'],
'bridgedPredictions': len(merged), 'bridgedAP50_101': second['ap101'],
'bridgedForegroundIoU': float(semantic), 'bridgedPairwiseIoU': mask_iou(merged, truth).tolist(),
'scope': 'single image/category/IoU threshold; ordinary instances; not COCO AP'}
if __name__ == '__main__':
print(json.dumps(demo(), indent=2))
The actual output is:
{
"separatePredictions": 2,
"separateAP50_101": 1.0,
"bridgedPredictions": 1,
"bridgedAP50_101": 0.0,
"bridgedForegroundIoU": 0.96,
"bridgedPairwiseIoU": [
[
0.48,
0.48
]
],
"scope": "single image/category/IoU threshold; ordinary instances; not COCO AP"
}
Thirteen numerical checks cover component membership, connectivity, overlapping masks, diagonal-mask geometry, duplicate predictions, precision interpolation, inclusive thresholds, category filtering, stable ties, detection caps, empty cases and invalid inputs. The numbers measure the explicitly constructed image; they do not estimate performance on natural scenes.
What the baseline cannot infer
Connected components infer identity solely from connected foreground. Touching objects merge; an occluded or dim object can fragment into several components. A minimum-area filter may remove noise but also remove small real objects. Before changing a metric, inspect which of these errors is actually occurring.
Learned methods can use appearance and context beyond connectivity. Region-based methods predict a mask per detected object; Mask R-CNN explains one such design. Semantic predictions from U-Net can help produce foreground, but class logits alone do not establish instance membership. If a system has no good object proposals, a precise mask head cannot recover an object it was never asked to segment.
Evaluate against the intended annotation policy. Visible-mask quality, inferred hidden extent, object counts, boundary accuracy and stable video identity are related but different questions. Report the mask definition, IoU thresholds, class averaging, score order, detection cap and handling of absent classes. A high foreground IoU by itself cannot answer how many objects were separated correctly.
Predict the result before running it
1. Same category, different object
Two adjacent people are both labeled “person.” What extra information must instance segmentation retain?
Answer: A separate membership mask or identity for each person. The category label alone says which kind of object occupies a pixel; it does not identify which person. The identity is local to the image unless a separate tracking rule links frames.
2. One bridge pixel
Two disjoint GT masks each contain 12 pixels. A single predicted mask contains both and one extra connecting pixel. Compute foreground IoU, each instance IoU and AP50 under the example’s matching contract.
Answer: Foreground IoU is 24/25=0.96. Each instance IoU is 12/25=0.48. There is one detection, but it meets neither 0.5 threshold, so there are no true positives and AP50 is zero. Good union coverage has not preserved identity.
3. A duplicate in the middle
For two GT objects, confidence order gives TP, duplicate FP, TP. Why is 101-point AP about 0.83498 rather than the final precision 2/3?
Answer: AP uses the precision envelope across recall thresholds. At recall thresholds through 0.5, the first prediction already provides precision 1. Above 0.5, the best available precision is 2/3. Average 51 copies of 1 and 50 copies of 2/3 over 101 thresholds; final precision is only one point on that curve.
4. Bright objects that touch
A production image contains touching same-class objects. Would switching from 4- to 8-neighbor connectivity solve their separation? What should the next experiment compare?
Answer: No. Eight-neighbor connectivity adds links and may merge more components. Compare the component baseline with a method using separation cues or object-conditioned masks, keeping annotations and evaluation settings fixed. Inspect merges, splits and missed small objects separately; do not select a method solely by foreground IoU.
Read the representation and evaluator together
The source scope for this article is Mask R-CNN’s task/method discussion; fixed COCO mask API documentation, rleIou, and the specified preparation, matching and accumulation ranges. Official code was read, not executed. The original NumPy example has its own tested contract, and no benchmark claim is borrowed from the upstream projects.
The companion Mask R-CNN article moves from “what counts as one detected object?” to the region features, mask loss and gradients used to predict it. Later topics can change the mask predictor while retaining these questions about identity and evaluation.
Make a prediction, then check
Two 12-pixel GT objects become one 25-pixel prediction. What is its IoU against either object?
Learning objectives
- Distinguish category, object identity, mask overlap and bounding-box overlap.
- Trace confidence-ordered matching, duplicate errors and specified 101-point AP.
- Run a connected-component baseline and explain the one-pixel bridge failure.
Prerequisites & connections
Explore related knowledge →References
- Mask R-CNN — v3 region masks and alignment
Kaiming He; Georgia Gkioxari; Piotr Dollár; Ross Girshick · 2017 - COCO mask API — layout, encoding and overlap contract
COCO API contributors · 2019 - COCO rleIou — fixed binary mask overlap
COCO API contributors · 2019 - COCO evaluation — fixed instance matching and precision accumulation
COCO API contributors · 2019
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-07 · Codex single-AI-author technical check: scoped primary/source reading, explicit identity and coordinate counterexamples, independent arithmetic/gradient tests and complete bilingual comparison. Not independent human review or official benchmark reproduction.
- Compared both complete languages, displayed equations, executable code/stdout, four explained exercises and scoped references; separate toy profiles from official APIs and complete benchmark claims.
- Thirteen numerical checks plus bilingual/figure binding: components, overlap, duplicate matching, 101-point AP arithmetic, inclusive thresholds, class/tie/cap/empty rules and bridge-pixel counterexample. Formal code generates the illustrated masks and metrics.
Source locations checked:
- Mask R-CNN — v3 region masks and alignment · Read physical pages 2-4; visually inspected pages 3 and 4. Page 5 targeted inference closing and experimental-setup opening only; full results/ablations/appendices not read or adopted. v1 submission 2017-03-20; read revision v3 2018-01-24.
- COCO mask API — layout, encoding and overlap contract · Read lines 1-108: run-length representation, column-major input, ordinary/crowd IoU and wrappers. Compressed wire codec not executed.
- COCO rleIou — fixed binary mask overlap · Read rleIou lines 77-96: intersections/unions, crowd detection-area denominator, dimension mismatch handling. Full C backend and codecs not audited.
- COCO evaluation — fixed instance matching and precision accumulation · New reading 84-125,145-191,228-310: preparation, IoU dispatch, per-image/category matching, crowd/area ignore. Reused unchanged existing Source cocoapi-eval-20191225. No official execution. Additional read of accumulation lines 360-410: precision envelope and 101 recall sample lookup; no upstream execution.
Related topics