-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcompute_seg.py
248 lines (198 loc) · 8.54 KB
/
compute_seg.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 9 14:12:16 2021
@author: endocv challenges
Disclaimer: Most codes are imported from the previous EndoCV challenges!!!
Requires:
!pip install --upgrade scikit-learn
!pip install numba==0.49.1
!pip install hausdorff
"""
# TODO: Add distance metrics for evaluation!!!
import numpy as np
def rescale_im_stack(imfiles, size=(256,256)):
from skimage.transform import resize
from skimage.io import imread
X = []
for imfile in imfiles:
im = imread(imfile)
im = resize(im, size).astype(np.float32)
X.append(im[None,:])
X = np.concatenate(X, axis=0)
return X
def panel_imgs(imgs, grid):
N,m,n,c = imgs.shape
new_im = np.zeros((grid[0]*m, grid[1]*n, c))
for ii in range(grid[0]):
for jj in range(grid[1]):
im = imgs[ii*grid[1]+jj]
new_im[ii*m:(ii+1)*m, jj*n:(jj+1)*n] = im.copy()
return new_im
def locate_folders(rootfolder):
import os
folders = []
for root, dirs, files in os.walk(rootfolder):
for f in files:
if 'c' in f and '.tif' in f:
if root not in folders:
folders.append(root)
return np.hstack(folders)
def roi_area(mask):
from skimage.measure import label, regionprops
areas = []
if mask.max()>0:
reg = regionprops(label(mask))
for re in reg:
areas.append(re.area)
areas = np.hstack(areas)
return np.mean(areas)
else:
return np.sum(mask)
def get_args():
import argparse
parser = argparse.ArgumentParser(description="Semantic segmentation of EndoCV2021 challenge", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--GT_maskDIR", type=str, default="./examples/segmentation/GT", help="ground truth mask image (5 channel tif image only)")
parser.add_argument("--Eval_maskDIR", type=str, default="./examples/segmentation/testType1", help="provide folder for testType1 dataset under that name")
parser.add_argument("--testType", type=str, default="testType1", help="predicted mask image (5 channel tif image only)")
args = parser.parse_args()
return args
if __name__ == '__main__':
import glob
import os
from misc import EndoCV_misc
import cv2
from metrics_seg import get_confusion_matrix_elements, jac_score, dice_score, F2, precision, recall
# ---> requires: !pip install hausdorff (first install !pip install numba==0.49.1)
from hausdorff import hausdorff_distance
classTypes=['polyp']
args = get_args()
# can be multiple test sets: 1 -- 5
testType = args.testType
# ground truth folder
GT_folder = args.GT_maskDIR
GT_files = glob.glob(os.path.join(GT_folder,'*.jpg'))
# evaluation/predicted folder
participantsFolder = args.Eval_maskDIR
# save folder
savefolder = 'semantic_results'
os.makedirs(savefolder, exist_ok=True)
fnames = []
fpath = participantsFolder
os.makedirs(savefolder, exist_ok = True)
pred_mask_files = glob.glob(os.path.join(fpath, '*.jpg'))
fnames.append(pred_mask_files)
if len(pred_mask_files) > 0:
gt_mask_files = np.hstack([f for f in pred_mask_files])
jac_scores = []
dice_scores = []
f2_scores = []
PPV_scores = []
Rec_scores = []
acc_scores = []
Hfd_score = []
# print(gt_mask_files)
for jj in range(len(pred_mask_files))[:]:
gt_mask = (cv2.imread(gt_mask_files[jj]) > 0).astype(np.uint8)[:,:,0]
pred_mask = (cv2.imread(pred_mask_files[jj]) > 0).astype(np.uint8)
pred_mask = cv2.resize(pred_mask, (gt_mask.shape[1], gt_mask.shape[0]), interpolation = cv2.INTER_AREA)[:,:,0]
tn, fp, fn, tp = get_confusion_matrix_elements(gt_mask.flatten().tolist(), pred_mask.flatten().tolist())
overall_acc = (tp+tn)/(tp+tn+fp+fn)
Hf = hausdorff_distance(gt_mask, pred_mask, distance='euclidean')
jac_set = np.hstack([jac_score(gt_mask,pred_mask)])
dice_set = np.hstack([dice_score(gt_mask,pred_mask)])
f2_set = np.hstack([F2(gt_mask,pred_mask)])
PPV_set = np.hstack([precision(gt_mask,pred_mask)])
Rec_set = np.hstack([recall(gt_mask,pred_mask)])
acc = np.hstack([overall_acc])
jac_scores.append(jac_set)
dice_scores.append(dice_set)
f2_scores.append(f2_set)
PPV_scores.append(PPV_set)
Rec_scores.append(Rec_set)
acc_scores.append(acc)
Hfd_score.append(Hf)
jac_scores = np.vstack(jac_scores)
dice_scores = np.vstack(dice_scores)
f2_scores = np.vstack(f2_scores)
PPV_scores = np.vstack(PPV_scores)
Rec_scores = np.vstack(Rec_scores)
acc_scores = np.vstack(acc_scores)
print('----')
print(testType)
print ('jac: ', jac_scores.mean(axis=0)), '+', jac_scores.mean(axis=0).mean()
print('dice: ', dice_scores.mean(axis=0)), '+', dice_scores.mean(axis=0).mean()
print('F2: ', f2_scores.mean(axis=0)), '+', f2_scores.mean(axis=0).mean()
print('PPV: ', PPV_scores.mean(axis=0)), '+', PPV_scores.mean(axis=0).mean()
print('Rec: ', Rec_scores.mean(axis=0)), '+', Rec_scores.mean(axis=0).mean()
print('Acc: ', acc_scores.mean(axis=0)), '+', acc_scores.mean(axis=0).mean()
# Normalise
print('Hdf: ', np.mean(Hfd_score)/np.max(Hfd_score)), '+', np.mean(Hfd_score)/np.max(Hfd_score)
print('++++')
all_scores = np.vstack([jac_scores.mean(axis=0),
dice_scores.mean(axis=0),
f2_scores.mean(axis=0),
PPV_scores.mean(axis=0),
Rec_scores.mean(axis=0),
acc_scores.mean(axis=0),
np.mean(Hfd_score)/np.max(Hfd_score)])
all_scores = np.hstack([np.hstack(['jac',
'dice',
'F2',
'PPV',
'Rec', 'Acc', 'Hfd'])[:,None], all_scores])
# final scores are wrapped in json file
my_dictionary = {"EndoCV2021_seg":{
"dice":{
"value": ( dice_scores.mean(axis=0)[0])
},
"jaccard":{
"value": (jac_scores.mean(axis=0)[0])
},
"typeIIerror":{
"value": (f2_scores.mean(axis=0)[0])
},
"PPV":{
"value": (PPV_scores.mean(axis=0)[0]),
},
"recall":{
"value": (Rec_scores.mean(axis=0)[0]),
},
"OverallAcc":{
"value": (np.mean(acc_scores)),
},
"hausdorff_distance":{
"value": (np.mean(Hfd_score)/np.max(Hfd_score)),
},
"hausdorff_distance_nonNorm":{
"value": (np.mean(Hfd_score)),
},
"dice_std":{
"value": (np.std(dice_scores)),
},
"jc_std":{
"value": (np.std(jac_scores)),
},
"f2_std":{
"value": (np.std(f2_scores)),
},
"ppv_std":{
"value": (np.std(PPV_scores)),
},
"r_std":{
"value": (np.std(Rec_scores)),
},
"acc_std":{
"value": (np.std(acc_scores)),
},
"hdf_std":{
"value": (np.std(Hfd_score/np.max(Hfd_score))),
},
"hdf_std_noNorm":{
"value": (np.std(Hfd_score)),
},
}
}
# write to json
jsonFileName=os.path.join(savefolder, 'semantic_'+ testType + '.json')
EndoCV_misc.write2json(jsonFileName, my_dictionary)