Segmentation Metrics: IoU, Dice and Pixel Accuracy
A segmentation model labels every pixel: tumour or healthy tissue, road or pavement or car. Its output is a mask the size of the image, and evaluating it means comparing two masks. The obvious metric, the share of pixels labelled correctly, is almost always misleading, because most pixels in most images are background. The overlap metrics IoU (Jaccard index) and Dice (the score of pixels) look only at the object and are the standard. Here you compute all three in NumPy on masks small enough to print.
The definitions
Treat the predicted mask and the ground-truth mask as sets of pixels that belong to the object. Counting pixels as in a confusion matrix:
IoU is the same quantity as for detection boxes, now on pixel sets. Dice is exactly over pixels. Neither counts true negatives, so a huge background does not inflate them. The two are monotone functions of each other:
so they always rank two predictions on the same image the same way; Dice is never smaller than IoU. Medical imaging tends to report Dice, scene segmentation IoU.
A binary mask by hand
An 8 by 8 image with a 4 by 4 object and a prediction that is shifted by one pixel and misses a corner:
import numpy as np
from sklearn.metrics import jaccard_score, f1_score, accuracy_score
G = np.zeros((8, 8), int); G[2:6, 2:6] = 1 # ground truth: 16 pixels
P = np.zeros((8, 8), int); P[2:6, 3:7] = 1 # prediction: shifted right by one
P[5, 6] = 0 # ...and missing a corner
print("ground truth prediction")
for g_row, p_row in zip(G, P):
print(" ".join(map(str, g_row)), " ", " ".join(map(str, p_row)))
tp = int(np.sum((P == 1) & (G == 1))); fp = int(np.sum((P == 1) & (G == 0)))
fn = int(np.sum((P == 0) & (G == 1))); tn = int(np.sum((P == 0) & (G == 0)))
pix_acc = (tp + tn) / G.size
iou = tp / (tp + fp + fn)
dice = 2 * tp / (2 * tp + fp + fn)
print(f"TP {tp} FP {fp} FN {fn} TN {tn}")
print(f"pixel accuracy {pix_acc:.3f} sklearn {accuracy_score(G.ravel(), P.ravel()):.3f}")
print(f"IoU {iou:.3f} sklearn {jaccard_score(G.ravel(), P.ravel()):.3f}")
print(f"Dice {dice:.3f} sklearn F1 {f1_score(G.ravel(), P.ravel()):.3f} from IoU {2 * iou / (1 + iou):.3f}")ground truth prediction
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 1 1 1 0 0 0 0 0 1 1 1 1 0
0 0 1 1 1 1 0 0 0 0 0 1 1 1 1 0
0 0 1 1 1 1 0 0 0 0 0 1 1 1 1 0
0 0 1 1 1 1 0 0 0 0 0 1 1 1 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
TP 12 FP 3 FN 4 TN 45
pixel accuracy 0.891 sklearn 0.891
IoU 0.632 sklearn 0.632
Dice 0.774 sklearn F1 0.774 from IoU 0.774
The prediction overlaps 12 of the 16 object pixels, adds 3 wrong ones and misses 4. Pixel accuracy says 0.891, which sounds good; IoU says , Dice , and confirms the conversion. scikit-learn has no segmentation module, but on flattened masks jaccard_score is IoU and f1_score is Dice.
Pixel accuracy and small objects
Most of a street scene is road, sky and buildings; a pedestrian may cover a fraction of a percent of the pixels. A model that never predicts the small class still scores a high pixel accuracy:
import numpy as np
def scores(G, P):
tp = np.sum(P & G); fp = np.sum(P & ~G); fn = np.sum(~P & G)
acc = np.mean(P == G)
iou = tp / (tp + fp + fn) if tp + fp + fn else 1.0
dice = 2 * tp / (2 * tp + fp + fn) if tp + fp + fn else 1.0
return acc, iou, dice
G = np.zeros((64, 64), bool); G[30:36, 40:44] = True # a 6 x 4 object: 24 of 4096 pixels
empty = np.zeros_like(G) # predicts nothing at all
blob = np.zeros_like(G); blob[28:38, 38:46] = True # a generous blob around it
good = G.copy(); good[30, 40] = False; good[36, 41] = True # one pixel missed, one extra
print(f"object covers {G.mean():.2%} of the image")
for name, P in [("predicts nothing", empty), ("blob 10x8", blob), ("nearly exact", good)]:
acc, iou, dice = scores(G, P)
print(f"{name:16s} pixel accuracy {acc:.4f} IoU {iou:.3f} Dice {dice:.3f}")object covers 0.59% of the image
predicts nothing pixel accuracy 0.9941 IoU 0.000 Dice 0.000
blob 10x8 pixel accuracy 0.9863 IoU 0.300 Dice 0.462
nearly exact pixel accuracy 0.9995 IoU 0.920 Dice 0.958
The object is 24 of 4096 pixels (0.59 %). Predicting nothing gives a pixel accuracy of 0.9941 and an IoU of 0. A loose 10 by 8 blob around the object scores lower pixel accuracy (0.9863) than predicting nothing, though it found the whole object; its IoU of 0.300 says what is true: it found the object, but most of the blob is wrong. Only the overlap metrics order the three predictions sensibly.
Several classes: mean IoU
For classes, build the pixel confusion matrix (rows = true class, columns = predicted). The IoU of class is
(its row sum plus its column sum counts the union, the diagonal entry once too often). Mean IoU (mIoU) averages over classes, so every class counts the same however few pixels it has. It is the headline number of scene-segmentation benchmarks.
import numpy as np
from sklearn.metrics import confusion_matrix, jaccard_score
# 0 = background, 1 = road, 2 = car
G = np.array([[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 2, 2, 1, 1, 1, 1],
[1, 1, 2, 2, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1]])
P = G.copy()
P[3, :3] = 0 # top of the road called background
P[4, 3] = 1; P[5, 3] = 1 # right half of the car called road
P[2, 2] = 1 # a stray road pixel in the sky
M = confusion_matrix(G.ravel(), P.ravel(), labels=[0, 1, 2])
print(M)
iou = np.diag(M) / (M.sum(axis=1) + M.sum(axis=0) - np.diag(M))
for name, v in zip(["background", "road", "car"], iou):
print(f"IoU {name:10s} {v:.3f}")
print(f"mean IoU ours {iou.mean():.3f} sklearn {jaccard_score(G.ravel(), P.ravel(), average='macro'):.3f}")
print(f"pixel accuracy {np.trace(M) / M.sum():.3f}")[[23 1 0]
[ 3 33 0]
[ 0 2 2]]
IoU background 0.852
IoU road 0.846
IoU car 0.500
mean IoU ours 0.733 sklearn 0.733
pixel accuracy 0.906
Background and road are mostly right (IoU 0.852 and 0.846); the car lost half its pixels to the road class (IoU 0.500). The mean IoU of 0.733 shows that problem, the pixel accuracy of 0.906 hides it, because the car is only 4 of 64 pixels. Each error also hurts two classes: the car pixels called road are false negatives for car and false positives for road.
Per image or over the data set?
There are two ways to average over a test set. Per image: compute IoU or Dice on each image, then take the mean; every image counts the same, and an image where a tiny lesion is missed scores 0. Pooled: add up TP, FP and FN over all images, then compute once; large objects dominate. Medical papers usually report the mean per-image Dice, scene benchmarks the pooled per-class IoU. Decide what a missed small object should cost, and say which one you report. Images with no object at all need a rule too: an empty prediction on an empty mask is , usually counted as 1.
Pitfalls
- Pixel accuracy as the main metric. It is dominated by the background; report per-class IoU or Dice.
- Thresholding. Models output a probability per pixel; the metrics need a mask, so the threshold (often 0.5) is part of the result.
- Resizing the masks. Compute metrics at the resolution of the ground truth, and resize labels with nearest-neighbour interpolation only; bilinear resizing invents new label values.
- Boundaries. Annotators disagree by a pixel or two along edges; for thin structures that alone can cost a lot of IoU. Boundary-tolerant metrics (boundary IoU, Hausdorff distance) exist for that case.
Practice
- A predicted mask has 30 pixels, the ground truth 20, and they share 15. Compute IoU and Dice, and check the conversion formula.
Answer
Union , IoU . Dice . Check: .
- Why can the Dice score be used directly as a training loss for segmentation, while pixel accuracy cannot?
Answer
Replacing the hard mask by the predicted probabilities gives a "soft Dice", , which is differentiable, and focuses on the object regardless of how large the background is. Pixel accuracy needs hard decisions (a step function with zero gradient) and is dominated by the background.
Test yourself
Dice is the same as which classification metric computed over pixels?
- accuracy
- precision
- specificity
IoU is 0.5. What is the Dice score?
- 0.5
- 0.667
- 0.25
- 0.75
A model predicts only background on images where the object covers 1 % of the pixels. What are its pixel accuracy and object IoU?
- about 0.99 and 0
- about 0.5 and 0.5
- 0 and 0
- about 0.99 and 0.99
Why is mean IoU averaged over classes rather than over pixels?
- It is faster to compute
- So that small classes count as much as large ones
- Because pixels are not independent
- To make it equal to pixel accuracy