You want to compute one scalar metric (Dice/F1) from two binary masks by counting how many pixels match in the foreground and how many do not.
1. Background Knowledge (concepts & theory)
In semantic segmentation, each pixel is assigned a class label (e.g., background vs tumor). For binary segmentation, we can treat each pixel as either 0 (background) or 1 (foreground). To evaluate how good a predicted mask is compared to a ground-truth mask, we use overlap-based metrics. One of the most popular for medical and other segmentation tasks is the Dice coefficient (also called F1 score at the pixel level).
Dice measures the overlap between two sets of foreground pixels: prediction A and ground truth B. Formally:
Dice=∣A∣+∣B∣2∣A∩B∣
Here ∣A∩B∣ is the number of pixels that are 1 in both masks (true positives), ∣A∣ is the number of predicted foreground pixels, and ∣B∣ is the number of ground-truth foreground pixels. In classification terms, this can also be written as:
Dice=2TP+FP+FN2TP
where TP, FP, and FN are computed over pixels.
Dice ranges from 0 (no overlap) to 1 (perfect overlap). It is especially useful when the foreground is small and imbalanced (e.g., tumors, small organs), because it directly measures the relative overlap instead of being dominated by the large background.
2. Algorithm / Approach
General pattern to compute Dice between two binary masks:
Ensure binary masks: Both prediction and ground truth should be boolean/int masks with values in {0,1}.
Flatten or broadcast: Treat them as 1D arrays of the same length (or operate elementwise on the full 2D/3D arrays).
Compute confusion counts per pixel:
TP: pixels where prediction == 1 and ground truth == 1
FP: pixels where prediction == 1 and ground truth == 0
FN: pixels where prediction == 0 and ground truth == 1