Sub topic 10
Measuring consistency with IoU and annotator agreement
This chapter assumes you can read basic Python and NumPy, know the (x_min, y_min, x_max, y_max) box convention from the earlier chapters on coordinates and bounding boxes, and know what a binary mask is. By the end you will be able to quantify how much two annotators agree, and decide whether a disagreement is noise or a sign that your guidelines are unclear.
Why measure agreement
A labelled dataset is a set of human decisions. Two careful people will still draw slightly different boxes, pick different classes for ambiguous objects, or skip small objects. If you never measure that variation, you cannot tell whether a model scoring 0.70 is weak or is already at the limit of what the labels allow.
Agreement measurement answers three questions:
- Are the guidelines clear enough that different people produce similar labels?
- Which classes or situations cause disagreement?
- What is a realistic upper bound for model accuracy on this data?
Agreement is not correctness. Two annotators can agree and both be wrong, for example if the guideline itself says to label something incorrectly. Agreement tells you about consistency, which is a necessary condition for quality, not a sufficient one.
Intersection over union for boxes
Intersection over union (IoU) is the area where two regions overlap divided by the area they cover together. It ranges from 0 (no overlap) to 1 (identical regions).
def box_iou(a, b):
"""Boxes in (x_min, y_min, x_max, y_max) format."""
ix1, iy1 = max(a[0], b[0]), max(a[1], b[1])
ix2, iy2 = min(a[2], b[2]), min(a[3], b[3])
inter = max(0, ix2 - ix1) * max(0, iy2 - iy1)
area_a = (a[2] - a[0]) * (a[3] - a[1])
area_b = (b[2] - b[0]) * (b[3] - b[1])
union = area_a + area_b - inter
return inter / union if union > 0 else 0.0
print(box_iou((50, 40, 150, 90), (60, 45, 160, 95)))The two boxes are each 100 by 50 pixels and are shifted by 10 pixels in x and 5 in y. The intersection is 90 by 45 = 4050 pixels, the union is 5000 + 5000 − 4050 = 5950, and the IoU is about 0.681.
The max(0, ...) terms matter. Without them, two boxes that do not overlap give a negative width, and the product of two negatives would produce a false positive overlap.
What IoU values mean in practice
| IoU between two annotators | Typical interpretation |
|---|---|
| 0.90 or higher | Near-identical; often only seen on large, sharp-edged objects |
| 0.75 to 0.90 | Good agreement; normal for well-defined classes |
| 0.50 to 0.75 | Acceptable for loose boxes; check small or occluded objects |
| Below 0.50 | Likely different interpretations of the object's extent, or different objects |
These are rules of thumb, not standards. Set your own target from a pilot batch.
IoU is harsher on small objects
A one-pixel shift costs very little on a large box but a lot on a small one. Take a 10 by 10 box and shift a copy by one pixel in x: the intersection is 9 by 10 = 90, the union is 110, and the IoU is 0.818. Do the same with a 100 by 100 box: the intersection is 9900, the union is 10100, and the IoU is 0.980.
So a single IoU threshold treats classes unequally. If you have a class of tiny objects such as distant pedestrians or bolts, report agreement per size band or per class, and expect lower numbers there.
IoU for masks
For segmentation, the same idea applies to binary masks. Count pixels instead of computing rectangle areas.
import numpy as np
def mask_iou(m1, m2):
"""m1, m2: arrays of shape (height, width) with values 0 or 1."""
a = m1.astype(bool)
b = m2.astype(bool)
union = np.logical_or(a, b).sum()
if union == 0:
return 1.0 # both empty: treat as perfect agreement
return float(np.logical_and(a, b).sum() / union)
m1 = np.zeros((480, 640), dtype=np.uint8)
m2 = np.zeros((480, 640), dtype=np.uint8)
m1[40:90, 50:150] = 1
m2[45:95, 60:160] = 1
print(mask_iou(m1, m2))This prints about 0.6807, the same as the box example, because the masks are the same rectangles.
Two details need a decision:
- Both masks empty. The code above returns 1.0, because both annotators agreed there was nothing. Returning 0.0 would punish agreement on empty images. Whichever you pick, apply it consistently.
- Rasterisation convention. If you create masks from polygons with a library such as Pillow, whether boundary pixels are included changes the pixel counts by a thin outline. On large objects this is negligible. On thin objects such as poles or cables it can change IoU noticeably, so use one rasterisation routine for everything you compare.
Matching objects before comparing them
IoU compares two regions, but two annotators produce two lists of objects. You must first decide which object in list A corresponds to which object in list B. Without that step you cannot say whether a box was missed or just drawn differently.
A common approach is greedy matching:
- Compute IoU for every pair of boxes that share a class label.
- Discard pairs below a threshold, often 0.5.
- Take pairs from highest IoU downward, and accept a pair only if neither box has been used.
def box_iou(a, b):
ix1, iy1 = max(a[0], b[0]), max(a[1], b[1])
ix2, iy2 = min(a[2], b[2]), min(a[3], b[3])
inter = max(0, ix2 - ix1) * max(0, iy2 - iy1)
area_a = (a[2] - a[0]) * (a[3] - a[1])
area_b = (b[2] - b[0]) * (b[3] - b[1])
union = area_a + area_b - inter
return inter / union if union > 0 else 0.0
def match_boxes(objs_a, objs_b, threshold=0.5):
"""Each object is a dict with 'label' and 'box'. Returns (i, j, iou) tuples."""
candidates = []
for i, a in enumerate(objs_a):
for j, b in enumerate(objs_b):
if a["label"] != b["label"]:
continue
score = box_iou(a["box"], b["box"])
if score >= threshold:
candidates.append((score, i, j))
candidates.sort(reverse=True)
used_a, used_b, matches = set(), set(), []
for score, i, j in candidates:
if i in used_a or j in used_b:
continue
used_a.add(i)
used_b.add(j)
matches.append((i, j, score))
return matches
def agreement_summary(objs_a, objs_b, threshold=0.5):
matches = match_boxes(objs_a, objs_b, threshold)
total = len(objs_a) + len(objs_b)
f1 = 2 * len(matches) / total if total else 1.0
mean_iou = sum(m[2] for m in matches) / len(matches) if matches else 0.0
return {"matched": len(matches), "f1": round(f1, 3), "mean_iou": round(mean_iou, 3)}
ann_a = [
{"label": "car", "box": (50, 40, 150, 90)},
{" (300, 200, 380, 260)},
{"label": "person", "box": (10, 10, 40, 90)},
]
ann_b = [
{"label": "car", "box": (60, 45, 160, 95)},
{"label": "person", "box": (12, 8, 42, 88)},
{"label": "bus", "box": (300, 200, 380, 260)},
]
print(agreement_summary(ann_a, ann_b))The output is {'matched': 2, 'f1': 0.667, 'mean_iou': 0.758}. The F1 value, 2 × matches ÷ (objects in A + objects in B), works as a symmetric agreement score: neither annotator is treated as the ground truth. Here the second car and the bus occupy the same box, so they fail to match because of the label mismatch, not the geometry.
Matching only same-class pairs hides class confusion. A more diagnostic approach is to match on IoU alone, then report matched pairs with different labels separately. That shows you which pairs of classes get confused.
Agreement on class labels
When the question is "which class?" and not "where?", use a chance-corrected statistic. Raw percent agreement is misleading when one class dominates: if 95% of objects are cars, two annotators who label everything "car" agree 95% of the time while showing no skill.
Cohen's kappa corrects for this. It compares observed agreement with the agreement expected if each annotator picked labels at random with their own class frequencies:
kappa = (observed − expected) / (1 − expected)
from collections import Counter
def cohens_kappa(labels_a, labels_b):
n = len(labels_a)
observed = sum(x == y for x, y in zip(labels_a, labels_b)) / n
count_a, count_b = Counter(labels_a), Counter(labels_b)
expected = sum(count_a[c] * count_b[c] for c in count_a) / (n * n)
return (observed - expected) / (1 - expected)
a = ["car", "car", "bus", "car", "bus", "car", "car", "bus", "car", "car"]
b = ["car", "car", "bus", "bus", "bus", "car", "car", "car", "car", "car"]
print(round(cohens_kappa(a, b), 3))Observed agreement is 0.8 and expected agreement is 0.7 × 0.7 + 0.3 × 0.3 = 0.58, so kappa is 0.22 / 0.42 ≈ 0.524. That is moderate agreement, much lower than the raw 80% suggests.
The function divides by zero if both annotators use a single identical class for every item, because the expected agreement is then 1. Guard against that when you run it on small batches.
Cohen's kappa applies to two annotators and one label per item. For more annotators or missing labels, Krippendorff's alpha is the usual alternative. Kappa is also not a threshold you can apply blindly: it depends on class balance, so compare it across batches of the same task and not across unrelated projects.
Running an agreement study
- Pick an overlap batch. Use 50 to 200 images that every annotator labels independently, drawn to include the hard cases, not only easy ones.
- Label blind. Annotators must not see each other's work or discuss the batch before submitting.
- Compute per-class numbers. An overall score can look fine while one class fails.
- Read the disagreements. Open the worst-scoring images and sort the causes: guideline gap, tool problem, annotator error, or truly ambiguous image.
- Fix the cause, then repeat. Update the guideline with a worked example, then measure again on a fresh batch.
Repeat the study periodically, because annotator behaviour drifts and new annotators join.
Common errors
- Mixing box formats.
box_iouexpects(x_min, y_min, x_max, y_max). Feeding it COCO[x, y, w, h]boxes gives wrong values with no error message. Convert first. - Comparing across different image sizes. If one annotator's tool exported normalised coordinates and the other pixels, IoU will be meaningless. Convert both to the same system.
- Using one global threshold. An IoU of 0.5 is lenient for large objects and strict for tiny ones. Check per-class and per-size results.
- Counting unmatched objects as zero-IoU pairs. Missed objects and badly drawn objects are different problems. Report them separately.
- Treating an annotator as ground truth. For a two-annotator comparison, use symmetric measures such as the F1 above, or designate a reviewer-corrected set as the reference.
- Tiny overlap batches. With 10 images, one odd image moves the score a lot. Report the number of objects as well as the score.
Exercise
Box A is (0, 0, 10, 10) and box B is (5, 0, 15, 10). What is their IoU, and what is the IoU if B is moved to (0, 5, 10, 15) instead?
Show answer
For the first pair, the intersection is 5 by 10 = 50 and the union is 100 + 100 − 50 = 150, so IoU = 50/150 ≈ 0.333. For the second pair the intersection is 10 by 5 = 50 and the union is again 150, so IoU is also ≈ 0.333. Shifting by half the box size in either direction gives the same result for same-sized boxes.
Exercise
Two annotators label 100 objects as "car" or "truck". Both label 90 objects as "car" and 10 as "truck", and they agree on 82 of the 100 objects (80 cars and 2 trucks). Compute raw agreement and Cohen's kappa, and explain why they differ so much.
Show answer
Raw agreement is 0.82. Expected agreement is 0.9 × 0.9 + 0.1 × 0.1 = 0.82. Kappa is (0.82 − 0.82) / (1 − 0.82) = 0. Because "car" is so common, agreement of 82% is exactly what random labelling with these frequencies would produce, so the annotators show no agreement beyond chance. Raw agreement hides this.