-
Notifications
You must be signed in to change notification settings - Fork 68
/
data_sampler.py
291 lines (266 loc) · 10.6 KB
/
data_sampler.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
#####
# some functions are borrowed from https://github.com/taigw/brats17/
#####
import cv2
import numpy as np
import copy
import os, sys
from tqdm import tqdm
from tensorpack.utils.argtools import memoized, log_once
from tensorpack.dataflow import (ProxyDataFlow,
MapData, TestDataSpeed, MultiProcessMapData,
MapDataComponent, DataFromList, PrefetchDataZMQ)
from data_loader import BRATS_SEG
import config
from tensorpack.dataflow import RNGDataFlow
import nibabel
import random
import time
from utils import *
import six
class BatchData(ProxyDataFlow):
"""
Stack datapoints into batches.
It produces datapoints of the same number of components as ``ds``, but
each component has one new extra dimension of size ``batch_size``.
The batch can be either a list of original components, or (by default)
a numpy array of original components.
"""
def __init__(self, ds, batch_size, remainder=False, use_list=False):
"""
Args:
ds (DataFlow): When ``use_list=False``, the components of ``ds``
must be either scalars or :class:`np.ndarray`, and have to be consistent in shapes.
batch_size(int): batch size
remainder (bool): When the remaining datapoints in ``ds`` is not
enough to form a batch, whether or not to also produce the remaining
data as a smaller batch.
If set to False, all produced datapoints are guaranteed to have the same batch size.
If set to True, `ds.size()` must be accurate.
use_list (bool): if True, each component will contain a list
of datapoints instead of an numpy array of an extra dimension.
"""
super(BatchData, self).__init__(ds)
if not remainder:
try:
assert batch_size <= ds.size()
except NotImplementedError:
pass
self.batch_size = int(batch_size)
self.remainder = remainder
self.use_list = use_list
def size(self):
ds_size = self.ds.size()
div = ds_size // self.batch_size
rem = ds_size % self.batch_size
if rem == 0:
return div
return div + int(self.remainder)
def get_data(self):
"""
Yields:
Batched data by stacking each component on an extra 0th dimension.
"""
holder = []
for data in self.ds.get_data():
if config.DATA_SAMPLING == 'all_positive':
if data[2].sum() == 0:
continue
elif config.DATA_SAMPLING == 'one_positive':
if len(holder) == self.batch_size - 1:
# force to contain label
t = [x[2].sum() for x in holder]
if sum(t) == 0 and data[2].sum() == 0:
continue
else:
pass
holder.append(data)
if len(holder) == self.batch_size:
yield BatchData._aggregate_batch(holder, self.use_list)
del holder[:]
if self.remainder and len(holder) > 0:
yield BatchData._aggregate_batch(holder, self.use_list)
@staticmethod
def _aggregate_batch(data_holder, use_list=False):
size = len(data_holder[0])
result = []
for k in range(size):
if use_list:
result.append(
[x[k] for x in data_holder])
else:
dt = data_holder[0][k]
if type(dt) in list(six.integer_types) + [bool]:
tp = 'int32'
elif type(dt) == float:
tp = 'float32'
else:
try:
tp = dt.dtype
except AttributeError:
raise TypeError("Unsupported type to batch: {}".format(type(dt)))
try:
result.append(
np.asarray([x[k] for x in data_holder], dtype=tp))
except Exception as e: # noqa
logger.exception("Cannot batch data. Perhaps they are of inconsistent shape?")
if isinstance(dt, np.ndarray):
s = pprint.pformat([x[k].shape for x in data_holder])
logger.error("Shape of all arrays to be batched: " + s)
try:
# open an ipython shell if possible
import IPython as IP; IP.embed() # noqa
except ImportError:
pass
return result
class DataFromListOfDict(RNGDataFlow):
def __init__(self, lst, keys, shuffle=False):
self._lst = lst
self._keys = keys
self._shuffle = shuffle
self._size = len(lst)
def size(self):
return self._size
def get_data(self):
if self._shuffle:
self.rng.shuffle(self._lst)
for dic in self._lst:
dp = [dic[k] for k in self._keys]
yield dp
def sampler3d(volume_list, label, weight):
"""
sample 3d volume to size (depth, h, w, 4)
"""
margin = 5
volume_list = transpose_volumes(volume_list, config.DIRECTION)
data_shape = config.PATCH_SIZE
label_shape = config.PATCH_SIZE
data_slice_number = data_shape[0]
label_slice_number = label_shape[0]
volume_shape = volume_list[0].shape
sub_data_shape = [data_slice_number, data_shape[1], data_shape[2]]
sub_label_shape =[label_slice_number, label_shape[1], label_shape[2]]
label = transpose_volumes(label, config.DIRECTION)
center_point = get_random_roi_sampling_center(volume_shape, sub_label_shape, "full", None)
sub_label = extract_roi_from_volume(label,
center_point,
sub_label_shape,
fill = 'zero')
sub_data = []
flip = False
for moda in range(len(volume_list)):
sub_data_moda = extract_roi_from_volume(volume_list[moda],center_point,sub_data_shape)
if(flip):
sub_data_moda = np.flip(sub_data_moda, -1)
sub_data.append(sub_data_moda)
sub_data = np.array(sub_data) #4, depth, h, w
weight = transpose_volumes(weight, config.DIRECTION)
sub_weight = extract_roi_from_volume(weight,
center_point,
sub_label_shape,
fill = 'zero')
if(flip):
sub_weight = np.flip(sub_weight, -1)
if(flip):
sub_label = np.flip(sub_label, -1)
batch = {}
axis = [1,2,3,0] #[1,2,3,0] [d, h, w, modalities]
batch['images'] = np.transpose(sub_data, axis)
batch['weights'] = np.transpose(sub_weight[np.newaxis, ...], axis)
batch['labels'] = np.transpose(sub_label[np.newaxis, ...], axis)
# other meta info ?
return batch
def sampler3d_whole(volume_list, label, weight, original_shape, bbox):
"""
mods = sorted(im.keys())
volume_list = []
for mod_idx, mod in enumerate(mods):
filename = im[mod]
volume = load_nifty_volume_as_array(filename, with_header=False)
if mod_idx == 0:
# contain whole tumor
margin = 5 # small padding value
original_shape = volume.shape
bbmin, bbmax = get_none_zero_region(volume, margin)
volume = crop_ND_volume_with_bounding_box(volume, bbmin, bbmax)
if mod_idx == 0:
weight = np.asarray(volume > 0, np.float32)
if config.INTENSITY_NORM == 'modality':
volume = itensity_normalize_one_volume(volume)
volume_list.append(volume)
"""
sub_data = np.array(volume_list)
batch = {}
axis = [1,2,3,0] #[1,2,3,0] [d, h, w, modalities]
batch['images'] = np.transpose(sub_data, axis)
batch['weights'] = np.transpose(weight[np.newaxis, ...], axis)
batch['original_shape'] = original_shape
batch['bbox'] = bbox
return batch
def get_train_dataflow(add_mask=True):
"""
"""
if config.CROSS_VALIDATION:
imgs = BRATS_SEG.load_from_file(config.BASEDIR, config.TRAIN_DATASET)
else:
imgs = BRATS_SEG.load_many(
config.BASEDIR, config.TRAIN_DATASET, add_gt=False, add_mask=add_mask)
# no filter for training
imgs = list(imgs)
ds = DataFromList(imgs, shuffle=True)
def preprocess(data):
if config.NO_CACHE:
fname, gt, im = data['file_name'], data['gt'], data['image_data']
volume_list, label, weight, _, _ = crop_brain_region(im, gt)
batch = sampler3d(volume_list, label, weight)
else:
volume_list, label, weight, _, _ = data['preprocessed']
batch = sampler3d(volume_list, label, weight)
return [batch['images'], batch['weights'], batch['labels']]
ds = BatchData(MapData(ds, preprocess), config.BATCH_SIZE)
ds = PrefetchDataZMQ(ds, 6)
return ds
def get_eval_dataflow():
#if config.CROSS_VALIDATION:
imgs = BRATS_SEG.load_from_file(config.BASEDIR, config.VAL_DATASET)
# no filter for training
ds = DataFromListOfDict(imgs, ['file_name', 'id', 'preprocessed'])
def f(data):
volume_list, label, weight, original_shape, bbox = data
batch = sampler3d_whole(volume_list, label, weight, original_shape, bbox)
return batch
ds = MapDataComponent(ds, f, 2)
ds = PrefetchDataZMQ(ds, 1)
return ds
def get_test_dataflow():
imgs = BRATS_SEG.load_many(config.BASEDIR, config.TEST_DATASET, add_gt=False)
# no filter for training
ds = DataFromListOfDict(imgs, ['file_name', 'id', 'preprocessed'])
def f(data):
volume_list, label, weight, original_shape, bbox = data
batch = sampler3d_whole(volume_list, label, weight, original_shape, bbox)
return batch
ds = MapDataComponent(ds, f, 2)
ds = PrefetchDataZMQ(ds, 1)
return ds
if __name__ == "__main__":
df = get_train_dataflow()
df.reset_state()
for i in tqdm(df.get_data()):
pass
"""
for k in i:
arr = i[k][0]
arr = np.rot90(arr, k=2, axes= (1,2))
OUTPUT_AFFINE = np.array(
[[0, 0, 1, 0],
[0, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 1]])
if k == 'labels':
img = nibabel.Nifti1Image(arr.astype(np.int32), OUTPUT_AFFINE)
else:
img = nibabel.Nifti1Image(arr.astype(np.float32), OUTPUT_AFFINE)
#nibabel.save(img, "./debug_output/{}.nii".format(k))
break
"""