-
Notifications
You must be signed in to change notification settings - Fork 43
/
dataset.py
176 lines (144 loc) · 6.56 KB
/
dataset.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
'''
@Author: Zhou Kai
@GitHub: https://github.com/athon2
@Date: 2018-11-30 09:53:44
'''
from torch.utils.data import Dataset
import tables
import numpy as np
import nibabel as nib
from nilearn.image import new_img_like, resample_to_img
from utils import pickle_load
def open_data_file(filename, readwrite="r"):
return tables.open_file(filename, readwrite)
def random_flip_dimensions(n_dimensions):
axis = list()
for dim in range(n_dimensions):
if np.random.choice([True, False]):
axis.append(dim)
return axis
def flip_image(image, axis):
try:
new_data = np.copy(image.get_data())
for axis_index in axis:
new_data = np.flip(new_data, axis=axis_index)
except TypeError:
new_data = np.flip(image.get_data(), axis=axis)
return new_img_like(image, data=new_data)
def offset_image(image, offset_factor):
image_data = image.get_data()
image_shape = image_data.shape
new_data = np.zeros(image_shape)
assert len(image_shape) == 3, "Wrong dimessions! Expected 3 but got {0}".format(len(image_shape))
if len(image_shape) == 3:
new_data[:] = image_data[0][0][0] # 左上角背景点像素值
oz = int(image_shape[0] * offset_factor[0])
oy = int(image_shape[1] * offset_factor[1])
ox = int(image_shape[2] * offset_factor[2])
if oy >= 0:
slice_y = slice(image_shape[1]-oy)
index_y = slice(oy, image_shape[1])
else:
slice_y = slice(-oy,image_shape[1])
index_y = slice(image_shape[1] + oy)
if ox >= 0:
slice_x = slice(image_shape[2]-ox)
index_x = slice(ox, image_shape[2])
else:
slice_x = slice(-ox,image_shape[2])
index_x = slice(image_shape[2] + ox)
if oz >= 0:
slice_z = slice(image_shape[0]-oz)
index_z = slice(oz, image_shape[0])
else:
slice_z = slice(-oz,image_shape[0])
index_z = slice(image_shape[0] + oz)
new_data[index_z, index_y, index_x] = image_data[slice_z,slice_y,slice_x]
return new_img_like(image, data=new_data)
def augment_image(image, flip_axis=None, offset_factor=None):
if flip_axis is not None:
image = flip_image(image, axis=flip_axis)
if offset_factor is not None:
image = offset_image(image, offset_factor=offset_factor)
return image
def get_target_label(label_data, config):
target_label = np.zeros(label_data.shape)
for l_idx in range(config["n_labels"]):
assert config["labels"][l_idx] in [1,2,4],"Wrong label!Expected 1 or 2 or 4, but got {0}".format(config["labels"][l_idx])
if not config["label_containing"]:
target_label[np.where(label_data == config["labels"][l_idx])]= 1
else:
if config["labels"][l_idx] == 1:
target_label[np.where(label_data == 1)] = 1
target_label[np.where(label_data == 4)] = 1
elif config["labels"][l_idx] == 2:
target_label[np.where(label_data > 0 )] = 1
elif config["labels"][l_idx] == 4:
target_label[np.where(label_data == 4)]= 1
return target_label
class BratsDataset(Dataset):
def __init__(self, phase, config):
super(BratsDataset, self).__init__()
self.config = config
self.phase = phase
self.data_name = config["data_file"]
if phase == "train":
self.data_ids = config["training_file"]
elif phase == "validate":
self.data_ids = config["validation_file"]
elif phase == "test":
self.data_ids = config["test_file"]
self.data_list = pickle_load(self.data_ids)
self.data_file = None
def file_open(self):
if self.data_file is None:
self.data_file = open_data_file(self.data_name)
def file_close(self):
if self.data_file is not None:
self.data_file.close()
self.data_file = None
def get_affine(self):
return self.affine
def __getitem__(self, index):
item = self.data_list[index]
input_data = self.data_file.root.data[item] # data shape:(4, 128, 128, 128)
label_data = self.data_file.root.truth[item] # truth shape:(1, 128, 128, 128)
seg_label = get_target_label(label_data, self.config)
self.affine = self.data_file.root.affine[item]
# dimessions of data
n_dim = len(seg_label[0].shape)
if self.phase == "train":
if self.config["random_offset"]:
offset_factor = -0.25 + np.random.random(n_dim)
else:
offset_factor = None
if self.config["random_flip"]:
flip_axis = random_flip_dimensions(n_dim)
else:
flip_axis = None
elif self.phase == "validate" or self.phase == "test":
offset_factor = None
flip_axis = None
# Apply random offset and flip to each channel according to randomly generated offset factor and flip axis respectively.
data_list = list()
for data_channel in range(input_data.shape[0]):
# Transform ndarray data to Nifti1Image
channel_image = nib.Nifti1Image(dataobj=input_data[data_channel], affine=self.affine)
data_list.append(resample_to_img(augment_image(channel_image, flip_axis=flip_axis, offset_factor=offset_factor), channel_image, interpolation="continuous").get_data())
input_data = np.asarray(data_list)
# Transform ndarray segmentation label to Nifti1Image
seg_image = nib.Nifti1Image(dataobj=seg_label[0], affine=self.affine)
seg_label = resample_to_img(augment_image(seg_image, flip_axis=flip_axis, offset_factor=offset_factor), seg_image, interpolation="nearest").get_data()
if len(seg_label.shape) == 3:
seg_label = seg_label[np.newaxis]
if self.config["VAE_enable"]:
# Concatenate to (5, 128, 128, 128) as network output
final_label = np.concatenate((seg_label, input_data), axis=0)
else:
final_label = seg_label
if self.phase == "test":
subject_id = np.array(self.data_file.root.subject_ids[item].decode('utf-8'), dtype=str())[0]
return input_data, final_label, subject_id
return input_data, final_label
def __len__(self):
return len(self.data_list)