Tyler Durden
Tyler Durden

Reputation: 31

Dice coefficient for image segmentation evaluation

I'm trying to implement dice coefficient, so I could compare segmented image to ground truth image. However, the output of the dice coefficient seems to be incorrect as segmented image is around 80% similar to the ground truth image. The output of dice coefficient is 0.13. Should be around 0.8.

def my_dice(img1,img2):
 intersection = np.logical_and(img1, img2)
 union = np.logical_or(img1, img2)
 dice = (2*np.sum(intersection))/(np.sum(union)+np.sum(intersection))
 return dice

I thought the results are odd because of non-binary array (range 0-255). So I divided images by 255, which gave me some floats. This didn't help. So I used python astype(np.bool) but that didn't help as well. To be clear, I performed semantic segmentation on image where is one cell, nothing more and I want to compare with its ground truth using dice coefficient. I have used plenty of methods I've found online but none is give me correct number. Like this one before.

    """Soft dice loss calculation for arbitrary batch size, number of classes, and number of spatial dimensions.
    Assumes the `channels_last` format.
  
    # Arguments
        y_true: b x X x Y( x Z...) x c One hot encoding of ground truth
        y_pred: b x X x Y( x Z...) x c Network output, must sum to 1 over c channel (such as after softmax) 
        epsilon: Used for numerical stability to avoid divide by zero errors
    """
   
    # skip the batch and class axis for calculating Dice score
    axes = tuple(range(1, len(y_pred.shape)-1)) 
    print(axes)
    numerator = 2. * np.sum(y_pred * y_true, axes)
    print(numerator)
    denominator = np.sum(np.square(y_pred) + np.square(y_true), axes)
    print(denominator)
    
    return np.mean(numerator / (denominator + epsilon)) # average over classes and batch

The results looks more sensible when I use dice loss which in case of second method the return looks like this:

return 1-np.mean(numerator / (denominator + epsilon)) # average over classes and batch

However, this is not what I apparently need to have. Both of the images are of shape: (224,224,1)

Upvotes: 1

Views: 3551

Answers (1)

Tyler Durden
Tyler Durden

Reputation: 31

Solved. The problem was caused by having one binary image (true, false) and segmented image in range (0-255). I had to binarized the segmented image and then calculate dice coefficient.

Upvotes: 1

Related Questions