-
Notifications
You must be signed in to change notification settings - Fork 14
/
hausdorff_loss.py
170 lines (128 loc) · 4.93 KB
/
hausdorff_loss.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import cv2 as cv
import numpy as np
import torch
from torch import nn
from scipy.ndimage.morphology import distance_transform_edt as edt
from scipy.ndimage import convolve
"""
Hausdorff loss implementation based on paper:
https://arxiv.org/pdf/1904.10030.pdf
"""
class HausdorffDTLoss(nn.Module):
"""Binary Hausdorff loss based on distance transform"""
def __init__(self, alpha=2.0, **kwargs):
super(HausdorffDTLoss, self).__init__()
self.alpha = alpha
@torch.no_grad()
def distance_field(self, img: np.ndarray) -> np.ndarray:
field = np.zeros_like(img)
for batch in range(len(img)):
fg_mask = img[batch] > 0.5
if fg_mask.any():
bg_mask = ~fg_mask
fg_dist = edt(fg_mask)
bg_dist = edt(bg_mask)
field[batch] = fg_dist + bg_dist
return field
def forward(
self, pred: torch.Tensor, target: torch.Tensor, debug=False
) -> torch.Tensor:
"""
Uses one binary channel: 1 - fg, 0 - bg
pred: (b, 1, x, y, z) or (b, 1, x, y)
target: (b, 1, x, y, z) or (b, 1, x, y)
"""
assert pred.dim() == 4 or pred.dim() == 5, "Only 2D and 3D supported"
assert (
pred.dim() == target.dim()
), "Prediction and target need to be of same dimension"
# pred = torch.sigmoid(pred)
pred_dt = torch.from_numpy(self.distance_field(pred.cpu().numpy())).float()
target_dt = torch.from_numpy(self.distance_field(target.cpu().numpy())).float()
pred_error = (pred - target) ** 2
distance = pred_dt ** self.alpha + target_dt ** self.alpha
dt_field = pred_error * distance
loss = dt_field.mean()
if debug:
return (
loss.cpu().numpy(),
(
dt_field.cpu().numpy()[0, 0],
pred_error.cpu().numpy()[0, 0],
distance.cpu().numpy()[0, 0],
pred_dt.cpu().numpy()[0, 0],
target_dt.cpu().numpy()[0, 0],
),
)
else:
return loss
class HausdorffERLoss(nn.Module):
"""Binary Hausdorff loss based on morphological erosion"""
def __init__(self, alpha=2.0, erosions=10, **kwargs):
super(HausdorffERLoss, self).__init__()
self.alpha = alpha
self.erosions = erosions
self.prepare_kernels()
def prepare_kernels(self):
cross = np.array([cv.getStructuringElement(cv.MORPH_CROSS, (3, 3))])
bound = np.array([[[0, 0, 0], [0, 1, 0], [0, 0, 0]]])
self.kernel2D = cross * 0.2
self.kernel3D = np.array([bound, cross, bound]) * (1 / 7)
@torch.no_grad()
def perform_erosion(
self, pred: np.ndarray, target: np.ndarray, debug
) -> np.ndarray:
bound = (pred - target) ** 2
if bound.ndim == 5:
kernel = self.kernel3D
elif bound.ndim == 4:
kernel = self.kernel2D
else:
raise ValueError(f"Dimension {bound.ndim} is nor supported.")
eroted = np.zeros_like(bound)
erosions = []
for batch in range(len(bound)):
# debug
erosions.append(np.copy(bound[batch][0]))
for k in range(self.erosions):
# compute convolution with kernel
dilation = convolve(bound[batch], kernel, mode="constant", cval=0.0)
# apply soft thresholding at 0.5 and normalize
erosion = dilation - 0.5
erosion[erosion < 0] = 0
if erosion.ptp() != 0:
erosion = (erosion - erosion.min()) / erosion.ptp()
# save erosion and add to loss
bound[batch] = erosion
eroted[batch] += erosion * (k + 1) ** self.alpha
if debug:
erosions.append(np.copy(erosion[0]))
# image visualization in debug mode
if debug:
return eroted, erosions
else:
return eroted
def forward(
self, pred: torch.Tensor, target: torch.Tensor, debug=False
) -> torch.Tensor:
"""
Uses one binary channel: 1 - fg, 0 - bg
pred: (b, 1, x, y, z) or (b, 1, x, y)
target: (b, 1, x, y, z) or (b, 1, x, y)
"""
assert pred.dim() == 4 or pred.dim() == 5, "Only 2D and 3D supported"
assert (
pred.dim() == target.dim()
), "Prediction and target need to be of same dimension"
# pred = torch.sigmoid(pred)
if debug:
eroted, erosions = self.perform_erosion(
pred.cpu().numpy(), target.cpu().numpy(), debug
)
return eroted.mean(), erosions
else:
eroted = torch.from_numpy(
self.perform_erosion(pred.cpu().numpy(), target.cpu().numpy(), debug)
).float()
loss = eroted.mean()
return loss