Dice score calculation of 3D binary masks using Segment Comparison module

Hi All,

Could you please point out where can I find the source code for Segment Comparison module (Slicer version 5.2.2). I’m getting different values of dice score for 3D binary nifti masks when using 3D Slicer and the Monai framework. This is the monai function I’m using:

def calculate_dice_score(predicted, ground_truth):
      dice_metric = monai.metrics.DiceMetric(include_background=False, reduction="mean")
      # Convert the predicted and ground truth masks to PyTorch tensors
      predicted_tensor = torch.from_numpy(predicted)
      ground_truth_tensor = torch.from_numpy(ground_truth)
      # Reshape tensors to have batch size and number of channels
      predicted_tensor = predicted_tensor.unsqueeze(0).unsqueeze(0)
      ground_truth_tensor = ground_truth_tensor.unsqueeze(0).unsqueeze(0)
      # Calculate the Dice score
      dice_score = dice_metric(y_pred =predicted_tensor, y = ground_truth_tensor)
      return dice_score.item()

Please note that I have tried both mean and sum for reduction method and still getting different values from Slicer and Monai .

Thank you!

This is the source code of the module:

The difference may be due to the resizing that a MONAI transform does, that’s where I’d look first.

Thank you for sharing the code. I’m getting same dice score value as monai for below python code as well:

# Calculate dice score of masks
def calculate_dice_score(predicted, ground_truth):
    area_sum = np.sum(predicted == 1) + np.sum(ground_truth == 1)
    if area_sum > 0:
        return np.sum(predicted[ground_truth == 1]) * 2.0 / area_sum
        return 1.0 # Will return 1.0 if both predicted and ground truth masks are empty

Will check the slicer code. Thanks again.

I’m getting the same value with Segment Comaprison module as with manual calculation. Sorry for the trouble. Thank you!