├── Active-Contour-Loss.py ├── README.md └── notebooks └── demo.ipynb /Active-Contour-Loss.py: -------------------------------------------------------------------------------- 1 | 2 | import torch 3 | 4 | def active_contour_loss(y_true, y_pred, weight=10): 5 | ''' 6 | y_true, y_pred: tensor of shape (B, C, H, W), where y_true[:,:,region_in_contour] == 1, y_true[:,:,region_out_contour] == 0. 7 | weight: scalar, length term weight. 8 | ''' 9 | # length term 10 | delta_r = y_pred[:,:,1:,:] - y_pred[:,:,:-1,:] # horizontal gradient (B, C, H-1, W) 11 | delta_c = y_pred[:,:,:,1:] - y_pred[:,:,:,:-1] # vertical gradient (B, C, H, W-1) 12 | 13 | delta_r = delta_r[:,:,1:,:-2]**2 # (B, C, H-2, W-2) 14 | delta_c = delta_c[:,:,:-2,1:]**2 # (B, C, H-2, W-2) 15 | delta_pred = torch.abs(delta_r + delta_c) 16 | 17 | epsilon = 1e-8 # where is a parameter to avoid square root is zero in practice. 18 | lenth = torch.mean(torch.sqrt(delta_pred + epsilon)) # eq.(11) in the paper, mean is used instead of sum. 19 | 20 | # region term 21 | c_in = torch.ones_like(y_pred) 22 | c_out = torch.zeros_like(y_pred) 23 | 24 | region_in = torch.mean( y_pred * (y_true - C_in )**2 ) # equ.(12) in the paper, mean is used instead of sum. 25 | region_out = torch.mean( (1-y_pred) * (y_true - C_out)**2 ) 26 | region = region_in + region_out 27 | 28 | loss = weight*lenth + region 29 | 30 | return loss 31 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Active-Contour-Loss-pytorch 2 | An unofficial pytorch implementation for cvpr2019 paper "Learning Active Contour Models for Medical Image Segmentation" by Chen, Xu, et al. 3 | 4 | The offcial tensorflow implementation can be found at https://github.com/xuuuuuuchen/Active-Contour-Loss 5 | --------------------------------------------------------------------------------