I am wondering how can I calculate the dice coefficient for multi-class segmentation.
Here is the script that would calculate the dice coefficient for the binary segmentation task. How can I loop over each class and calculate the dice for each class?
Thank you in advance
import numpy
def dice_coeff(im1, im2, empty_score=1.0):
im1 = numpy.asarray(im1).astype(numpy.bool)
im2 = numpy.asarray(im2).astype(numpy.bool)
if im1.shape != im2.shape:
raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")
im_sum = im1.sum() + im2.sum()
if im_sum == 0:
return empty_score
# Compute Dice coefficient
intersection = numpy.logical_and(im1, im2)
return (2. * intersection.sum() / im_sum)