Per-class IoU, Dice, sensitivity, and specificity, plus mIoU, computed from scratch.
def compute_segmentation_metrics(pred, gt, num_classes):
results = {}
ious = []
dices = []
for c in range(num_classes):
pred_c = (pred == c).astype(float)
gt_c = (gt == c).astype(float)
tp = (pred_c * gt_c).sum()
fp = (pred_c * (1 - gt_c)).sum()
fn = ((1 - pred_c) * gt_c).sum()
tn = ((1 - pred_c) * (1 - gt_c)).sum()
iou = tp / (tp + fp + fn + 1e-10)
dice = 2*tp / (2*tp + fp + fn + 1e-10)
sens = tp / (tp + fn + 1e-10)
spec = tn / (tn + fp + 1e-10)
results[f'class_{c}'] = {
'IoU': round(float(iou), 4),
'Dice': round(float(dice), 4),
'Sensitivity': round(float(sens), 4),
'Specificity': round(float(spec), 4),
}
ious.append(iou)
dices.append(dice)
results['mIoU'] = round(float(np.mean(ious)), 4)
results['mean_Dice'] = round(float(np.mean(dices)), 4)
return results
pred and gt are integer class-index arrays of shape (H, W). Returns per-class metrics plus mIoU and mean Dice across all classes.