-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathhausdorff_metric.py
36 lines (24 loc) · 1 KB
/
hausdorff_metric.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
import numpy as np
import torch
from torch import nn
from scipy.ndimage.morphology import distance_transform_edt as edt
class HausdorffDistance:
def hd_distance(self, x: np.ndarray, y: np.ndarray) -> np.ndarray:
if np.count_nonzero(x) == 0 or np.count_nonzero(y) == 0:
return np.array([np.Inf])
indexes = np.nonzero(x)
distances = edt(np.logical_not(y))
return np.array(np.max(distances[indexes]))
def compute(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
assert (
pred.shape[1] == 1 and target.shape[1] == 1
), "Only binary channel supported"
pred = (pred > 0.5).byte()
target = (target > 0.5).byte()
right_hd = torch.from_numpy(
self.hd_distance(pred.cpu().numpy(), target.cpu().numpy())
).float()
left_hd = torch.from_numpy(
self.hd_distance(target.cpu().numpy(), pred.cpu().numpy())
).float()
return torch.max(right_hd, left_hd)