DEV Community

Cover image for How to Measure Inter-Annotator Agreement for Medical Image Segmentation in Python
Pariedolia System
Pariedolia System

Posted on

How to Measure Inter-Annotator Agreement for Medical Image Segmentation in Python

Your segmentation model is only as consistent as the labels it learned from. If three annotators outline the same tumor three different ways, the model learns a blurry average, and your validation score inherits the same noise.

The fix is to measure disagreement before training. In this post we'll build a small, dependency-light toolkit for inter-annotator agreement (IAA) that you can run on any labeled dataset:

pairwise Dice between annotators for segmentation masks
Cohen's kappa and Fleiss' kappa for classification labels
a function that flags low-agreement cases for review
a majority-vote consensus mask

Everything uses only numpy.

Setup
python
import itertools
import numpy as np
Step 1: Dice between two annotators

Dice measures overlap: 2|A ∩ B| / (|A| + |B|).

python
def dice(a, b):
a, b = a.astype(bool), b.astype(bool)
denom = a.sum() + b.sum()
if denom == 0:
return 1.0 # both empty: treat as agreement
return 2.0 * np.logical_and(a, b).sum() / denom
Step 2: Agreement across more than two annotators

With three or more annotators, build a pairwise matrix and average the off-diagonal values.

python
def pairwise_dice(masks):
n = len(masks)
m = np.eye(n)
for i, j in itertools.combinations(range(n), 2):
m[i, j] = m[j, i] = dice(masks[i], masks[j])
return m

def mean_pairwise_dice(masks):
m = pairwise_dice(masks)
return m[np.triu_indices(len(masks), k=1)].mean()

The matrix is useful on its own. If one annotator has consistently lower agreement with everyone else, that is a training problem for that person, not a problem with the protocol.

Step 3: Flag cases that need review

Compute agreement per case, then list those below a threshold.

python
def flag_low_agreement(case_masks, threshold=0.8):
"""case_masks: {case_id: [mask_from_annotator_1, mask_from_annotator_2, ...]}"""
scores = {cid: mean_pairwise_dice(m) for cid, m in case_masks.items()}
return scores, [cid for cid, s in scores.items() if s < threshold]
Step 4: A majority-vote consensus mask

When annotators disagree, a simple consensus is a voxel-wise majority vote.

python
def majority_vote(masks):
return np.mean(np.stack(masks).astype(float), axis=0) >= 0.5

With an even number of annotators, a tie counts as foreground here. Pick a rule for ties and write it down. For production work you may prefer a probabilistic method such as STAPLE, which weights annotators by estimated reliability.

Step 5: Kappa for classification labels

For labels like benign / malignant / indeterminate, raw percent agreement is misleading because some agreement happens by chance. Kappa corrects for that.

python
def cohen_kappa(a, b):
a, b = np.asarray(a), np.asarray(b)
po = (a == b).mean()
pe = sum((a == l).mean() * (b == l).mean() for l in np.union1d(a, b))
return 1.0 if pe == 1 else (po - pe) / (1 - pe)

def fleiss_kappa(counts):
"""counts: (n_items, n_categories); each row sums to the number of raters."""
counts = np.asarray(counts, dtype=float)
n_items, _ = counts.shape
n_raters = counts.sum(axis=1)[0]
p_j = counts.sum(axis=0) / (n_items * n_raters)
p_i = (np.square(counts).sum(axis=1) - n_raters) / (n_raters * (n_raters - 1))
p_bar, p_e = p_i.mean(), np.square(p_j).sum()
return 1.0 if p_e == 1 else (p_bar - p_e) / (1 - p_e)

Use Cohen's kappa for two raters and Fleiss' kappa for three or more.

Try it on synthetic data

We'll simulate three annotators outlining a sphere, with different amounts of "hand jitter" per case.

python
def sphere(shape, center, radius):
z, y, x = np.ogrid[:shape[0], :shape[1], :shape[2]]
d2 = (z - center[0]) ** 2 + (y - center[1]) ** 2 + (x - center[2]) ** 2
return d2 <= radius ** 2

rng = np.random.default_rng(0)
shape = (48, 48, 48)

def simulate_annotators(radius, jitter, n=3):
masks = []
for _ in range(n):
c = 24 + rng.normal(0, jitter, size=3)
r = radius + rng.normal(0, jitter)
masks.append(sphere(shape, c, r))
return masks

cases = {
"case_clear_edges": simulate_annotators(radius=14, jitter=0.4),
"case_fuzzy_edges": simulate_annotators(radius=14, jitter=1.5),
"case_tiny_lesion": simulate_annotators(radius=3, jitter=0.8),
}

scores, flagged = flag_low_agreement(cases, threshold=0.8)
for cid, s in scores.items():
print(f"{cid:18s} mean pairwise Dice = {s:.3f}")
print("flagged for review:", flagged)

Output:

case_clear_edges mean pairwise Dice = 0.954
case_fuzzy_edges mean pairwise Dice = 0.762
case_tiny_lesion mean pairwise Dice = 0.608
flagged for review: ['case_fuzzy_edges', 'case_tiny_lesion']

Two things to notice:

The fuzzy case is flagged because of boundary noise. Larger jitter means less overlap.
The tiny lesion scores lowest even with modest jitter. Dice is very sensitive to size: a one-voxel disagreement matters far more on a 3-voxel-radius object than on a 14-voxel one. A low Dice on a small structure doesn't always mean poor annotation, so consider a boundary metric as well for small targets.

Now the pairwise matrix for the fuzzy case:

python
print(np.round(pairwise_dice(cases["case_fuzzy_edges"]), 3))
[[1. 0.713 0.742]
[0.713 1. 0.832]
[0.742 0.832 1. ]]

Annotator 1 agrees least with the others. And here is each annotator measured against the majority-vote consensus:

python
consensus = majority_vote(cases["case_fuzzy_edges"])
print([round(float(dice(m, consensus)), 3) for m in cases["case_fuzzy_edges"]])
[0.817, 0.889, 0.935]

Same story: annotator 1 is furthest from the group. That's a useful signal for retraining or protocol clarification.

Classification example
python

0 = benign, 1 = malignant, 2 = indeterminate

a1 = [0, 1, 1, 2, 0, 1, 0, 2, 1, 0]
a2 = [0, 1, 0, 2, 0, 1, 0, 1, 1, 0]
a3 = [0, 1, 1, 2, 1, 1, 0, 2, 0, 0]

print("Cohen's kappa (a1 vs a2):", round(cohen_kappa(a1, a2), 3))

ratings = np.array([a1, a2, a3]).T
counts = np.stack([(ratings == k).sum(axis=1) for k in range(3)], axis=1)
print("Fleiss' kappa (3 raters):", round(fleiss_kappa(counts), 3))
Cohen's kappa (a1 vs a2): 0.677
Fleiss' kappa (3 raters): 0.573
Practical tips
Run IAA throughout the project, not only at the end. Drift is much cheaper to fix early.
Don't treat 0.8 as a law. Acceptable Dice depends on the structure and the clinical task. Use the threshold that your reviewers agree makes sense, and write it down.
Fix the protocol, not just the people. Persistent disagreement on one structure usually means the labeling guideline is ambiguous.
Report agreement with the dataset. Anyone training on your labels, including regulators, will want to know how consistent they are.
Keep an adjudication step. When annotators disagree, a senior reviewer should resolve it and update the guideline.
Kappa has quirks. It can look low when one category dominates, even with high raw agreement. Report both kappa and the raw agreement rate.
Wrapping up

Agreement metrics are cheap to compute and catch problems that no model metric will reveal. With about 50 lines of NumPy you can score every case, find the annotators or structures that need attention, and put numbers behind your claim that a dataset is ready to train on.

I work with Pareidolia Systems LLP, a medical image annotation, segmentation and QC company. If you have questions about agreement metrics or annotation workflows, drop a comment.

Top comments (0)