forked from vqdang/hover_net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compute_stats.py
executable file
·248 lines (204 loc) · 8.9 KB
/
compute_stats.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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import argparse
import cProfile as profile
import glob
import os
import cv2
import numpy as np
import pandas as pd
import scipy.io as sio
from metrics.stats_utils import (
get_dice_1,
get_fast_aji,
get_fast_aji_plus,
get_fast_dice_2,
get_fast_pq,
remap_label,
pair_coordinates
)
def run_nuclei_type_stat(pred_dir, true_dir, type_uid_list=None, exhaustive=True):
"""GT must be exhaustively annotated for instance location (detection).
Args:
true_dir, pred_dir: Directory contains .mat annotation for each image.
Each .mat must contain:
--`inst_centroid`: Nx2, contains N instance centroid
of mass coordinates (X, Y)
--`inst_type` : Nx1: type of each instance at each index
`inst_centroid` and `inst_type` must be aligned and each
index must be associated to the same instance
type_uid_list : list of id for nuclei type which the score should be calculated.
Default to `None` means available nuclei type in GT.
exhaustive : Flag to indicate whether GT is exhaustively labelled
for instance types
"""
file_list = glob.glob(pred_dir + "*.mat")
file_list.sort() # ensure same order [1]
paired_all = [] # unique matched index pair
unpaired_true_all = [] # the index must exist in `true_inst_type_all` and unique
unpaired_pred_all = [] # the index must exist in `pred_inst_type_all` and unique
true_inst_type_all = [] # each index is 1 independent data point
pred_inst_type_all = [] # each index is 1 independent data point
for file_idx, filename in enumerate(file_list[:]):
filename = os.path.basename(filename)
basename = filename.split(".")[0]
true_info = sio.loadmat(os.path.join(true_dir, basename + ".mat"))
# dont squeeze, may be 1 instance exist
true_centroid = (true_info["inst_centroid"]).astype("float32")
true_inst_type = (true_info["inst_type"]).astype("int32")
if true_centroid.shape[0] != 0:
true_inst_type = true_inst_type[:, 0]
else: # no instance at all
true_centroid = np.array([[0, 0]])
true_inst_type = np.array([0])
# * for converting the GT type in CoNSeP
# true_inst_type[(true_inst_type == 3) | (true_inst_type == 4)] = 3
# true_inst_type[(true_inst_type == 5) | (true_inst_type == 6) | (true_inst_type == 7)] = 4
pred_info = sio.loadmat(os.path.join(pred_dir, basename + ".mat"))
# dont squeeze, may be 1 instance exist
pred_centroid = (pred_info["inst_centroid"]).astype("float32")
pred_inst_type = (pred_info["inst_type"]).astype("int32")
if pred_centroid.shape[0] != 0:
pred_inst_type = pred_inst_type[:, 0]
else: # no instance at all
pred_centroid = np.array([[0, 0]])
pred_inst_type = np.array([0])
# ! if take longer than 1min for 1000 vs 1000 pairing, sthg is wrong with coord
paired, unpaired_true, unpaired_pred = pair_coordinates(
true_centroid, pred_centroid, 12
)
# * Aggreate information
# get the offset as each index represent 1 independent instance
true_idx_offset = (
true_idx_offset + true_inst_type_all[-1].shape[0] if file_idx != 0 else 0
)
pred_idx_offset = (
pred_idx_offset + pred_inst_type_all[-1].shape[0] if file_idx != 0 else 0
)
true_inst_type_all.append(true_inst_type)
pred_inst_type_all.append(pred_inst_type)
# increment the pairing index statistic
if paired.shape[0] != 0: # ! sanity
paired[:, 0] += true_idx_offset
paired[:, 1] += pred_idx_offset
paired_all.append(paired)
unpaired_true += true_idx_offset
unpaired_pred += pred_idx_offset
unpaired_true_all.append(unpaired_true)
unpaired_pred_all.append(unpaired_pred)
paired_all = np.concatenate(paired_all, axis=0)
unpaired_true_all = np.concatenate(unpaired_true_all, axis=0)
unpaired_pred_all = np.concatenate(unpaired_pred_all, axis=0)
true_inst_type_all = np.concatenate(true_inst_type_all, axis=0)
pred_inst_type_all = np.concatenate(pred_inst_type_all, axis=0)
paired_true_type = true_inst_type_all[paired_all[:, 0]]
paired_pred_type = pred_inst_type_all[paired_all[:, 1]]
unpaired_true_type = true_inst_type_all[unpaired_true_all]
unpaired_pred_type = pred_inst_type_all[unpaired_pred_all]
###
def _f1_type(paired_true, paired_pred, unpaired_true, unpaired_pred, type_id, w):
type_samples = (paired_true == type_id) | (paired_pred == type_id)
paired_true = paired_true[type_samples]
paired_pred = paired_pred[type_samples]
tp_dt = ((paired_true == type_id) & (paired_pred == type_id)).sum()
tn_dt = ((paired_true != type_id) & (paired_pred != type_id)).sum()
fp_dt = ((paired_true != type_id) & (paired_pred == type_id)).sum()
fn_dt = ((paired_true == type_id) & (paired_pred != type_id)).sum()
if not exhaustive:
ignore = (paired_true == -1).sum()
fp_dt -= ignore
fp_d = (unpaired_pred == type_id).sum()
fn_d = (unpaired_true == type_id).sum()
f1_type = (2 * (tp_dt + tn_dt)) / (
2 * (tp_dt + tn_dt)
+ w[0] * fp_dt
+ w[1] * fn_dt
+ w[2] * fp_d
+ w[3] * fn_d
)
return f1_type
# overall
# * quite meaningless for not exhaustive annotated dataset
w = [1, 1]
tp_d = paired_pred_type.shape[0]
fp_d = unpaired_pred_type.shape[0]
fn_d = unpaired_true_type.shape[0]
tp_tn_dt = (paired_pred_type == paired_true_type).sum()
fp_fn_dt = (paired_pred_type != paired_true_type).sum()
if not exhaustive:
ignore = (paired_true_type == -1).sum()
fp_fn_dt -= ignore
acc_type = tp_tn_dt / (tp_tn_dt + fp_fn_dt)
f1_d = 2 * tp_d / (2 * tp_d + w[0] * fp_d + w[1] * fn_d)
w = [2, 2, 1, 1]
if type_uid_list is None:
type_uid_list = np.unique(true_inst_type_all).tolist()
results_list = [f1_d, acc_type]
for type_uid in type_uid_list:
f1_type = _f1_type(
paired_true_type,
paired_pred_type,
unpaired_true_type,
unpaired_pred_type,
type_uid,
w,
)
results_list.append(f1_type)
np.set_printoptions(formatter={"float": "{: 0.5f}".format})
print(np.array(results_list))
return
def run_nuclei_inst_stat(pred_dir, true_dir, print_img_stats=False, ext=".mat"):
# print stats of each image
print(pred_dir)
file_list = glob.glob("%s/*%s" % (pred_dir, ext))
file_list.sort() # ensure same order
metrics = [[], [], [], [], [], []]
for filename in file_list[:]:
filename = os.path.basename(filename)
basename = filename.split(".")[0]
true = sio.loadmat(os.path.join(true_dir, basename + ".mat"))
true = (true["inst_map"]).astype("int32")
pred = sio.loadmat(os.path.join(pred_dir, basename + ".mat"))
pred = (pred["inst_map"]).astype("int32")
# to ensure that the instance numbering is contiguous
pred = remap_label(pred, by_size=False)
true = remap_label(true, by_size=False)
pq_info = get_fast_pq(true, pred, match_iou=0.5)[0]
metrics[0].append(get_dice_1(true, pred))
metrics[1].append(get_fast_aji(true, pred))
metrics[2].append(pq_info[0]) # dq
metrics[3].append(pq_info[1]) # sq
metrics[4].append(pq_info[2]) # pq
metrics[5].append(get_fast_aji_plus(true, pred))
if print_img_stats:
print(basename, end="\t")
for scores in metrics:
print("%f " % scores[-1], end=" ")
print()
####
metrics = np.array(metrics)
metrics_avg = np.mean(metrics, axis=-1)
np.set_printoptions(formatter={"float": "{: 0.5f}".format})
print(metrics_avg)
metrics_avg = list(metrics_avg)
return metrics
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--mode",
help="mode to run the measurement,"
"`type` for nuclei instance type classification or"
"`instance` for nuclei instance segmentation",
nargs="?",
default="instance",
const="instance",
)
parser.add_argument(
"--pred_dir", help="point to output dir", nargs="?", default="", const=""
)
parser.add_argument(
"--true_dir", help="point to ground truth dir", nargs="?", default="", const=""
)
args = parser.parse_args()
if args.mode == "instance":
run_nuclei_inst_stat(args.pred_dir, args.true_dir, print_img_stats=False)
if args.mode == "type":
run_nuclei_type_stat(args.pred_dir, args.true_dir)