-
Notifications
You must be signed in to change notification settings - Fork 29
/
test.py
292 lines (243 loc) · 11.8 KB
/
test.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
'''
Capsules for Object Segmentation (SegCaps)
Original Paper by Rodney LaLonde and Ulas Bagci (https://arxiv.org/abs/1804.04241)
Code written by: Rodney LaLonde
If you use significant portions of this code or the ideas from our paper, please cite it :)
If you have any questions, please email me at [email protected].
This file is used for testing models. Please see the README for details about testing.
==============
This is the entry point of the test procedure for UNet, tiramisu,
Capsule Nets (capsbasic) or SegCaps(segcapsr1 or segcapsr3).
@author: Cheng-Lin Li a.k.a. Clark
@copyright: 2018 Cheng-Lin Li@Insight AI. All rights reserved.
@license: Licensed under the Apache License v2.0.
http://www.apache.org/licenses/
@contact: [email protected]
Tasks:
The program based on parameters from main.py to perform testing tasks
on all models.
Data:
MS COCO 2017 or LUNA 2016 were tested on this package.
You can leverage your own data set but the mask images should follow the format of
MS COCO or with background color = 0 on each channel.
Enhancement:
1. Integrated with MS COCO 2017 dataset.
'''
from __future__ import print_function
import logging
import matplotlib
import matplotlib.pyplot as plt
from os.path import join
from os import makedirs
import csv
import SimpleITK as sitk
import numpy as np
import scipy.ndimage.morphology
from skimage import measure, filters
from utils.metrics import dc, jc, assd
from PIL import Image
from keras import backend as K
from keras.utils import print_summary
from utils.data_helper import get_generator
from utils.custom_data_aug import convert_img_data, convert_mask_data
matplotlib.use('Agg')
plt.ioff()
K.set_image_data_format('channels_last')
RESOLUTION = 512
GRAYSCALE = True
def threshold_mask(raw_output, threshold):
# raw_output 3d:(119, 512, 512)
if threshold == 0:
try:
threshold = filters.threshold_otsu(raw_output)
except:
threshold = 0.5
logging.info('\tThreshold: {}'.format(threshold))
raw_output[raw_output > threshold] = 1
raw_output[raw_output < 1] = 0
# all_labels 3d:(119, 512, 512)
all_labels = measure.label(raw_output)
# props 3d: region of props=>
# list(_RegionProperties:<skimage.measure._regionprops._RegionProperties object>)
# with bbox.
props = measure.regionprops(all_labels)
props.sort(key=lambda x: x.area, reverse=True)
thresholded_mask = np.zeros(raw_output.shape)
if len(props) >= 2:
# if the largest is way larger than the second largest
if props[0].area / props[1].area > 5:
# only turn on the largest component
thresholded_mask[all_labels == props[0].label] = 1
else:
# turn on two largest components
thresholded_mask[all_labels == props[0].label] = 1
thresholded_mask[all_labels == props[1].label] = 1
elif len(props):
thresholded_mask[all_labels == props[0].label] = 1
# threshold_mask: 3d=(119, 512, 512)
thresholded_mask = scipy.ndimage.morphology.binary_fill_holes(thresholded_mask).astype(np.uint8)
return thresholded_mask
def test(args, test_list, model_list, net_input_shape):
if args.weights_path == '':
weights_path = join(args.check_dir, args.output_name + '_model_' + args.time + '.hdf5')
else:
weights_path = join(args.data_root_dir, args.weights_path)
output_dir = join(args.data_root_dir, 'results', args.net, 'split_' + str(args.split_num))
raw_out_dir = join(output_dir, 'raw_output')
fin_out_dir = join(output_dir, 'final_output')
fig_out_dir = join(output_dir, 'qual_figs')
try:
makedirs(raw_out_dir)
except:
pass
try:
makedirs(fin_out_dir)
except:
pass
try:
makedirs(fig_out_dir)
except:
pass
if len(model_list) > 1:
eval_model = model_list[1]
else:
eval_model = model_list[0]
try:
logging.info('\nWeights_path=%s'%(weights_path))
eval_model.load_weights(weights_path)
except:
logging.warning('\nUnable to find weights path. Testing with random weights.')
print_summary(model=eval_model, positions=[.38, .65, .75, 1.])
# Set up placeholders
outfile = ''
if args.compute_dice:
dice_arr = np.zeros((len(test_list)))
outfile += 'dice_'
if args.compute_jaccard:
jacc_arr = np.zeros((len(test_list)))
outfile += 'jacc_'
if args.compute_assd:
assd_arr = np.zeros((len(test_list)))
outfile += 'assd_'
# Testing the network
logging.info('\nTesting... This will take some time...')
with open(join(output_dir, args.save_prefix + outfile + 'scores.csv'), 'w') as csvfile:
writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
row = ['Scan Name']
if args.compute_dice:
row.append('Dice Coefficient')
if args.compute_jaccard:
row.append('Jaccard Index')
if args.compute_assd:
row.append('Average Symmetric Surface Distance')
writer.writerow(row)
for i, img in enumerate((test_list)):
sitk_img = sitk.ReadImage(join(args.data_root_dir, 'imgs', img[0]))
img_data = sitk.GetArrayFromImage(sitk_img) # 3d:(slices, 512, 512), 2d:(512, 512, channels=4)
# Change RGB to single slice of grayscale image for MS COCO 17 dataset.
if args.dataset == 'mscoco17':
img_data = convert_img_data(img_data, 3)
num_slices = 1
logging.info('\ntest.test: eval_model.predict_generator')
_, _, generate_test_batches = get_generator(args.dataset)
output_array = eval_model.predict_generator(generate_test_batches(args.data_root_dir, [img],
net_input_shape,
batchSize=args.batch_size,
numSlices=args.slices,
subSampAmt=0,
stride=1),
steps=num_slices, max_queue_size=1, workers=4,
use_multiprocessing=args.use_multiprocessing,
verbose=1)
logging.info('\ntest.test: output_array=%s'%(output_array))
if args.net.find('caps') != -1:
# A list with two images [mask, recon], get mask image.#3d:
# output_array=[mask(Slices, x=512, y=512, 1), recon(slices, x=512, y=512, 1)]
output = output_array[0][:,:,:,0] # output = (slices, 512, 512)
#recon = output_array[1][:,:,:,0]
else:
output = output_array[:,:,:,0]
#output_image = RTTI size:[512, 512, 119]
output_img = sitk.GetImageFromArray(output)
print('Segmenting Output')
# output_bin (119, 512, 512)
output_bin = threshold_mask(output, args.thresh_level)
# output_mask = RIIT (512, 512, 119)
output_mask = sitk.GetImageFromArray(output_bin)
if args.dataset == 'luna16':
output_img.CopyInformation(sitk_img)
output_mask.CopyInformation(sitk_img)
print('Saving Output')
sitk.WriteImage(output_img, join(raw_out_dir, img[0][:-4] + '_raw_output' + img[0][-4:]))
sitk.WriteImage(output_mask, join(fin_out_dir, img[0][:-4] + '_final_output' + img[0][-4:]))
else: # MS COCO 17
plt.imshow(output[0,:,:], cmap = 'gray')
plt.imsave(join(raw_out_dir, img[0][:-4] + '_raw_output' + img[0][-4:]), output[0,:,:])
plt.imshow(output_bin[0,:,:], cmap = 'gray')
plt.imsave(join(fin_out_dir, img[0][:-4] + '_final_output' + img[0][-4:]), output_bin[0,:,:])
# Load gt mask
# sitk_mask: 3d RTTI(512, 512, slices)
sitk_mask = sitk.ReadImage(join(args.data_root_dir, 'masks', img[0]))
# gt_data: 3d=(slices, 512, 512), Ground Truth data
gt_data = sitk.GetArrayFromImage(sitk_mask)
# Change RGB to single slice of grayscale image for MS COCO 17 dataset.
if args.dataset == 'mscoco17':
gt_data = convert_mask_data(gt_data)
# Reshape numpy from 2 to 3 dimensions (slices, heigh, width)
gt_data = gt_data.reshape([1, gt_data.shape[0], gt_data.shape[1]])
# Plot Qual Figure
print('Creating Qualitative Figure for Quick Reference')
f, ax = plt.subplots(1, 3, figsize=(15, 5))
if args.dataset == 'mscoco17':
pass
else: # 3D data
ax[0].imshow(img_data[img_data.shape[0] // 3, :, :], alpha=1, cmap='gray')
ax[0].imshow(output_bin[img_data.shape[0] // 3, :, :], alpha=0.5, cmap='Blues')
ax[0].imshow(gt_data[img_data.shape[0] // 3, :, :], alpha=0.2, cmap='Reds')
ax[0].set_title('Slice {}/{}'.format(img_data.shape[0] // 3, img_data.shape[0]))
ax[0].axis('off')
ax[1].imshow(img_data[img_data.shape[0] // 2, :, :], alpha=1, cmap='gray')
ax[1].imshow(output_bin[img_data.shape[0] // 2, :, :], alpha=0.5, cmap='Blues')
ax[1].imshow(gt_data[img_data.shape[0] // 2, :, :], alpha=0.2, cmap='Reds')
ax[1].set_title('Slice {}/{}'.format(img_data.shape[0] // 2, img_data.shape[0]))
ax[1].axis('off')
ax[2].imshow(img_data[img_data.shape[0] // 2 + img_data.shape[0] // 4, :, :], alpha=1, cmap='gray')
ax[2].imshow(output_bin[img_data.shape[0] // 2 + img_data.shape[0] // 4, :, :], alpha=0.5,
cmap='Blues')
ax[2].imshow(gt_data[img_data.shape[0] // 2 + img_data.shape[0] // 4, :, :], alpha=0.2,
cmap='Reds')
ax[2].set_title(
'Slice {}/{}'.format(img_data.shape[0] // 2 + img_data.shape[0] // 4, img_data.shape[0]))
ax[2].axis('off')
fig = plt.gcf()
fig.suptitle(img[0][:-4])
plt.savefig(join(fig_out_dir, img[0][:-4] + '_qual_fig' + '.png'),
format='png', bbox_inches='tight')
plt.close('all')
# Compute metrics
row = [img[0][:-4]]
if args.compute_dice:
logging.info('\nComputing Dice')
dice_arr[i] = dc(output_bin, gt_data)
logging.info('\tDice: {}'.format(dice_arr[i]))
row.append(dice_arr[i])
if args.compute_jaccard:
logging.info('\nComputing Jaccard')
jacc_arr[i] = jc(output_bin, gt_data)
logging.info('\tJaccard: {}'.format(jacc_arr[i]))
row.append(jacc_arr[i])
if args.compute_assd:
logging.info('\nComputing ASSD')
assd_arr[i] = assd(output_bin, gt_data, voxelspacing=sitk_img.GetSpacing(), connectivity=1)
logging.info('\tASSD: {}'.format(assd_arr[i]))
row.append(assd_arr[i])
writer.writerow(row)
row = ['Average Scores']
if args.compute_dice:
row.append(np.mean(dice_arr))
if args.compute_jaccard:
row.append(np.mean(jacc_arr))
if args.compute_assd:
row.append(np.mean(assd_arr))
writer.writerow(row)
print('Done.')