Sub topic 12
Evaluating instances with mask AP
This chapter assumes you know IoU on label maps, bounding-box detection with confidence scores, and precision and recall. It builds on the Mask R-CNN chapter, because mask AP is the standard score for models like it.
Why mean IoU is the wrong tool here
Mean IoU compares two label maps pixel by pixel. It has no idea which pixels belong to which object. A model that merges two touching people into one blob can score well on mean IoU, because every pixel still has the class "person". For instance segmentation that output is wrong, since the task is to separate objects.
An instance model also returns a variable-size list of masks, each with a class and a confidence score. The metric must therefore handle:
- detections that may be duplicates or false alarms
- ground-truth objects that may be missed
- confidence scores, so that a model is not rewarded or punished for where it happens to cut off its output
Average precision (AP), borrowed from object detection, handles all three. The only change is that overlap is measured between masks instead of boxes.
The evaluation procedure
The evaluation is built from the following steps. They run per class and per IoU threshold.
- Compute the mask IoU between every predicted mask and every ground-truth mask of that class in an image. Mask IoU is the intersection area divided by the union area, counted in pixels.
- Sort the predictions by score, highest first.
- Walk down the sorted list. Match each prediction to the unmatched ground-truth mask with the highest IoU. If that IoU is at least the threshold, the prediction is a true positive (TP) and the ground-truth mask is used up. Otherwise the prediction is a false positive (FP).
- Pool the TP/FP flags from all images, sort them again by score, and take running totals. This gives a precision and recall value after each prediction.
- Make precision monotonic by replacing each value with the highest precision at any equal or greater recall. Then sample it at fixed recall points and average. COCO uses 101 points, 0.00 to 1.00.
- Average over classes. Repeat for each IoU threshold and average again.
Because each ground-truth mask can be matched only once, duplicate predictions of the same object count as false positives. This is why instance models need non-maximum suppression or an equivalent step.
What the COCO numbers mean
The COCO benchmark reports several variants. Learn to read them, because papers and libraries use the same names.
| Name | Meaning |
|---|---|
| AP | Mean of AP over IoU thresholds 0.50, 0.55, ..., 0.95 (10 values), and over classes. This is the headline number. |
| AP50 | AP at IoU threshold 0.50 only. Lenient: a rough mask counts. |
| AP75 | AP at IoU threshold 0.75. Rewards accurate boundaries. |
| APs, APm, APl | AP restricted to small, medium, and large objects (by mask area, with cutoffs of 32² and 96² pixels). |
| AR@100 | Average recall when each image keeps at most 100 detections. |
Averaging over thresholds means a model with sloppy boundaries loses points at 0.75 to 0.95 even if it finds every object. A gap between AP50 and AP75 points to boundary quality problems, not detection problems.
A runnable implementation
The code below evaluates one class on one image at several thresholds. It shows the matching and the 101-point AP. For several images, compute ious and match_image per image, concatenate the scores and tp arrays, and call average_precision once with the total ground-truth count.
import numpy as np
def mask_iou_matrix(pred_masks, gt_masks):
# pred_masks: (N, H, W) bool, gt_masks: (M, H, W) bool -> (N, M) IoU
p = pred_masks.reshape(len(pred_masks), -1).astype(np.float64)
g = gt_masks.reshape(len(gt_masks), -1).astype(np.float64)
inter = p @ g.T
union = p.sum(axis=1)[:, None] + g.sum(axis=1)[None, :] - inter
return np.where(union > 0, inter / np.maximum(union, 1), 0.0)
def match_image(scores, ious, thr):
# Greedy matching in descending score order; returns a TP flag per prediction.
tp = np.zeros(len(scores), dtype=bool)
if ious.shape[1] == 0:
return tp
gt_taken = np.zeros(ious.shape[1], dtype=bool)
for i in np.argsort(-scores, kind="stable"):
candidates = np.where(gt_taken, -1.0, ious[i])
j = candidates.argmax()
if candidates[j] >= thr:
gt_taken[j] = True
tp[i] = True
return tp
def average_precision(scores, tp, num_gt):
if len(scores) == 0 or num_gt == 0:
return 0.0
order = np.argsort(-scores, kind="stable")
tp = tp[order]
ctp = np.cumsum(tp)
cfp = np.cumsum(~tp)
recall = ctp / num_gt
precision = ctp / (ctp + cfp)
precision = np.maximum.accumulate(precision[::-1])[::-1] # monotone envelope
points = np.linspace(0, 1, 101)
idx = np.searchsorted(recall, points, side="left")
sampled = np.zeros(101)
valid = idx < len(precision)
sampled[valid] = precision[idx[valid]]
return sampled.mean()
gt = np.zeros((2, 8, 8), dtype=bool)
gt[0, 0:4, 0:4] = True
gt[1, 4:8, 4:8] = True
pred = np.zeros((3, 8, 8), dtype=bool)
pred[0, 0:4, 0:4] = True # perfect match for object 0
pred[1, 4:8, 4:7] = True # 13 of 16 pixels of object 1 (IoU 0.8125)
pred[1, 4, 7] = True
pred[2, 0:4, 0:4] = True # duplicate of object 0
scores = np.array([0.9, 0.8, 0.6])
ious = mask_iou_matrix(pred, gt)
aps = []
for thr in np.linspace(0.5, 0.95, 10):
tp = match_image(scores, ious, thr)
aps.append(average_precision(scores, tp, num_gt=len(gt)))
print("AP50:", round(aps[0], 4))
print("AP:", round(float(np.mean(aps)), 4))It prints AP50: 1.0 and AP: 0.8515. The second prediction has IoU 0.8125, so it counts as a true positive for the seven thresholds up to 0.80 and as a false positive for the last three. The duplicate prediction is a false positive at every threshold, but it ranks below both true positives. It therefore does not lower AP50.
Gotchas and edge cases
- Do not threshold scores before evaluation. AP needs the full ranked list, including low-confidence detections. Cutting at 0.5 first discards the right-hand part of the precision-recall curve and lowers recall. COCO keeps up to 100 detections per image.
- Mask AP is not box AP. Libraries such as pycocotools take an IoU type (
segmorbbox). Usingbboxon a mask model scores the boxes, not the masks, and gives a higher and misleading number. - Crowd regions. COCO marks groups of objects, such as a dense crowd, as a single "iscrowd" region. Predictions that fall inside it are ignored, not counted as false positives. A hand-written evaluator like the one above has no such rule.
- Mask resolution. Predicted masks must be pasted back to the original image size before scoring. Scoring at a downsampled size changes IoU, especially for small objects.
- Results are stored as run-length encoding (RLE). COCO files store masks in this compressed form. Convert correctly, or every IoU will be wrong.
- Overlapping masks are allowed. Unlike panoptic output, instance predictions may overlap. AP does not penalize this directly, which is one reason panoptic quality exists.
Exercise
A model detects every object in a validation set and ranks all true positives above all false positives, but its masks only reach IoU 0.6 with the ground truth. Roughly what happens to AP50, AP75, and the headline AP, and why?
Show answer
AP50 is close to 1.0, because every mask clears the 0.50 threshold and the ranking is perfect. AP75 is close to 0, because no mask reaches IoU 0.75, so every prediction is a false positive at that threshold. The headline AP averages over 0.50 to 0.95, and only the thresholds 0.50, 0.55, and 0.60 can pass. That is 3 of 10 thresholds, so AP is about 0.3 at best. The model detects well but segments the boundaries poorly.
Exercise
Why does mean IoU not tell you whether two touching objects of the same class were separated correctly, and which metric does?
Show answer
Mean IoU works on a label map with one class per pixel, so two touching objects of the same class merge into one region with the same label, and the metric cannot see the merge. Mask AP matches each predicted mask to a single ground-truth instance. A merged mask has low IoU with each of the two objects and counts as a miss.