-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.py
189 lines (144 loc) · 5.01 KB
/
utils.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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import random
import torch
import numpy as np
import operator
import os
import logging
from scipy.spatial.distance import directed_hausdorff
def set_seed(seed):
"""
Set the random seed
"""
random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
CLASS_LABELS = {
'CHAOST2': {
'pa_all': set(range(1, 5)),
0: set([1, 4]), # upper_abdomen, leaving kidneies as testing classes
1: set([2, 3]), # lower_abdomen
},
}
def get_bbox(fg_mask, inst_mask):
"""
Get the ground truth bounding boxes
"""
fg_bbox = torch.zeros_like(fg_mask, device=fg_mask.device)
bg_bbox = torch.ones_like(fg_mask, device=fg_mask.device)
inst_mask[fg_mask == 0] = 0
area = torch.bincount(inst_mask.view(-1))
cls_id = area[1:].argmax() + 1
cls_ids = np.unique(inst_mask)[1:]
mask_idx = np.where(inst_mask[0] == cls_id)
y_min = mask_idx[0].min()
y_max = mask_idx[0].max()
x_min = mask_idx[1].min()
x_max = mask_idx[1].max()
fg_bbox[0, y_min:y_max + 1, x_min:x_max + 1] = 1
for i in cls_ids:
mask_idx = np.where(inst_mask[0] == i)
y_min = max(mask_idx[0].min(), 0)
y_max = min(mask_idx[0].max(), fg_mask.shape[1] - 1)
x_min = max(mask_idx[1].min(), 0)
x_max = min(mask_idx[1].max(), fg_mask.shape[2] - 1)
bg_bbox[0, y_min:y_max + 1, x_min:x_max + 1] = 0
return fg_bbox, bg_bbox
def t2n(img_t):
"""
torch to numpy regardless of whether tensor is on gpu or memory
"""
if img_t.is_cuda:
return img_t.data.cpu().numpy()
else:
return img_t.data.numpy()
def to01(x_np):
"""
normalize a numpy to 0-1 for visualize
"""
return (x_np - x_np.min()) / (x_np.max() - x_np.min() + 1e-5)
class Scores():
def __init__(self):
self.TP = 0
self.TN = 0
self.FP = 0
self.FN = 0
self.patient_dice = []
self.patient_iou = []
def record(self, preds, label):
assert len(torch.unique(preds)) < 3
tp = torch.sum((label == 1) * (preds == 1))
tn = torch.sum((label == 0) * (preds == 0))
fp = torch.sum((label == 0) * (preds == 1))
fn = torch.sum((label == 1) * (preds == 0))
self.patient_dice.append(2 * tp / (2 * tp + fp + fn))
self.patient_iou.append(tp / (tp + fp + fn))
self.TP += tp
self.TN += tn
self.FP += fp
self.FN += fn
def compute_dice(self):
return 2 * self.TP / (2 * self.TP + self.FP + self.FN)
def compute_iou(self):
return self.TP / (self.TP + self.FP + self.FN)
class Scores_new():
def __init__(self):
self.TP = 0
self.TN = 0
self.FP = 0
self.FN = 0
self.patient_dice = []
self.patient_iou = []
self.patient_hausdorff = [] # 新增
def record(self, preds, label):
assert len(torch.unique(preds)) < 3
tp = torch.sum((label == 1) * (preds == 1))
tn = torch.sum((label == 0) * (preds == 0))
fp = torch.sum((label == 0) * (preds == 1))
fn = torch.sum((label == 1) * (preds == 0))
self.patient_dice.append(2 * tp / (2 * tp + fp + fn))
self.patient_iou.append(tp / (tp + fp + fn))
# 计算95% Hausdorff Distance
hausdorff_dist = self.compute_95_hausdorff(preds, label)
self.patient_hausdorff.append(hausdorff_dist)
self.TP += tp
self.TN += tn
self.FP += fp
self.FN += fn
def compute_95_hausdorff(self, pred, label):
pred = pred.cpu().numpy()
label = label.cpu().numpy()
# 确保pred和label是二维数组
if pred.ndim > 2:
pred = np.squeeze(pred)
if label.ndim > 2:
label = np.squeeze(label)
# 获取非零元素的坐标
pred_points = np.array(np.nonzero(pred)).T
label_points = np.array(np.nonzero(label)).T
if len(pred_points) == 0 or len(label_points) == 0:
return 0 # 或者返回一个特定的值表示无法计算
# 计算Hausdorff距离
d1 = directed_hausdorff(pred_points, label_points)[0]
d2 = directed_hausdorff(label_points, pred_points)[0]
hausdorff_dist = max(d1, d2)
return hausdorff_dist # 返回Hausdorff距离,不计算百分位数
def compute_dice(self):
return 2 * self.TP / (2 * self.TP + self.FP + self.FN)
def compute_iou(self):
return self.TP / (self.TP + self.FP + self.FN)
def compute_avg_hausdorff(self):
return np.mean(self.patient_hausdorff)
def set_logger(path):
logger = logging.getLogger()
logger.handlers = []
formatter = logging.Formatter('[%(levelname)] - %(name)s - %(message)s')
logger.setLevel("INFO")
# log to .txt
file_handler = logging.FileHandler(path)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# log to console
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
return logger