from scipy.ndimage.morphology import distance_transform_edt
from skimage import segmentation as skimage_seg
from torch.nn import functional as F
import torch.nn as nn
import torch
def dice_loss(pred, target, smooth=1.):
pred = pred.contiguous()
target = target.contiguous()
intersection = (pred * target).sum(dim=2).sum(dim=2)
loss = (1 - ((2. * intersection + smooth) / (pred.sum(dim=2).sum(dim=2) + target.sum(dim=2).sum(dim=2) + smooth)))
return loss.mean()
class BDLoss(nn.Module):
def __init__(self):
# ref: https://github.com/LIVIAETS/surface-loss/blob/108bd9892adca476e6cdf424124bc6268707498e/losses.py#L74
super().__init__()
def forward(self, pred, target):
"""
pred: (batch_size, class, x,y)
target: ground truth, shape: (batch_size, class, x,y)
bound: precomputed distance map, shape (batch_size, class, x,y)
"""
img_gt_p = target.to(torch.bool)[:, 0, :, :].cpu()
img_gt_n = ~img_gt_p
posdis = distance_transform_edt(img_gt_p)
negdis = distance_transform_edt(img_gt_n)
boundary = skimage_seg.find_boundaries(img_gt_p.numpy(), mode='inner')
sdf = negdis - posdis
sdf[boundary == 1.0] = 0
# pred = pred[:, 0, :, :].cpu().detach().numpy()
# pred[pred[:, :, :] < 0.5] = 0.0
# pred[pred[:, :, :] >= 0.5] = 1.0
# plt.imshow(pred[0])
# plt.show()
# plt.imshow(sdf[0])
# plt.show()
pc = pred[:, 0, :, :]
dc = torch.tensor(sdf).to(device)
multipled = torch.einsum("bxy,bxy->bxy", pc, dc)
bd_loss = multipled.mean()
return bd_loss
def dice_loss(pred, target, smooth=1.):
pred = pred.contiguous()
target = target.contiguous()
intersection = (pred * target).sum(dim=2).sum(dim=2)
loss = (1 - ((2. * intersection + smooth) / (pred.sum(dim=2).sum(dim=2) + target.sum(dim=2).sum(dim=2) + smooth)))
return loss.mean()
class MyBDLoss(nn.Module):
def __init__(self):
# ref: https://github.com/LIVIAETS/surface-loss/blob/108bd9892adca476e6cdf424124bc6268707498e/losses.py#L74
super().__init__()
def forward(self, pred, target):
"""
pred: (batch_size, class, x,y)
target: ground truth, shape: (batch_size, class, x,y)
bound: precomputed distance map, shape (batch_size, class, x,y)
"""
img_gt_p = target.to(torch.bool)[:, 0, :, :].cpu()
img_gt_n = ~img_gt_p
posdis = distance_transform_edt(img_gt_p)
negdis = distance_transform_edt(img_gt_n)
boundary = skimage_seg.find_boundaries(img_gt_p.numpy(), mode='inner').astype(np.uint8)
sdf = negdis + posdis
sdf[boundary == 1] = 0
sdf = sdf * sdf
pred = pred[:, 0, :, :].cpu().detach().numpy()
pred[pred[:, :, :] < 0.5] = 0.0
pred[pred[:, :, :] >= 0.5] = 1.0
boundary_pc = skimage_seg.find_boundaries(pred, mode='inner') * 255.0
pc = torch.tensor(boundary_pc).to(device)
dc = torch.tensor(sdf).to(device)
multipled = torch.einsum("bxy,bxy->bxy", pc, dc)
bd_loss = multipled.mean()
return bd_loss
class DiceCE(nn.Module):
def __init__(self, bce_weight=0.5):
super().__init__()
self.bce_weight = bce_weight
# self.bd = DC_and_HD_loss({'batch_dice': False, 'smooth': 1e-5, 'do_bg': False, 'square': False},{})
def forward(self, pred, target):
pred = torch.sigmoid(pred)
bce = F.binary_cross_entropy_with_logits(pred, target, reduction='mean')
dice = dice_loss(pred, target)
loss = (bce * self.bce_weight) + ((1.0 - self.bce_weight) * dice)
return loss
class DiceBD(nn.Module):
def __init__(self, BD_weight=0.5):
super().__init__()
self.BD_weight = BD_weight
self.bd = BDLoss()
def forward(self, pred, target):
pred = torch.sigmoid(pred)
dice = dice_loss(pred, target)
bd = self.bd(pred, target)
loss = (bd * self.BD_weight) + ((1.0 - self.BD_weight) * dice)
return loss
class MyDiceBD(nn.Module):
def __init__(self, BD_weight=0.5):
super().__init__()
self.BD_weight = BD_weight
self.bd = MyBDLoss()
def forward(self, pred, target):
pred = torch.sigmoid(pred)
dice = dice_loss(pred, target)
bd = self.bd(pred, target)
loss = (bd * self.BD_weight) + ((1.0 - self.BD_weight) * dice)
return loss
class MyCEBD(nn.Module):
def __init__(self, BD_weight=0.5):
super().__init__()
self.BD_weight = BD_weight
self.bd = MyBDLoss()
def forward(self, pred, target):
pred = torch.sigmoid(pred)
bce = F.binary_cross_entropy_with_logits(pred, target, reduction='mean')
bd = self.bd(pred, target)
loss = (bd * self.BD_weight) + ((1.0 - self.BD_weight) * bce)
return loss