-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathsampling.py
executable file
·280 lines (203 loc) · 10.6 KB
/
sampling.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
import numpy as np
import nibabel as nib
from sklearn.feature_extraction.image import extract_patches as sk_extract_patches
import pdb
import itertools
def generate_indexes(patch_shape, expected_shape) :
ndims = len(patch_shape)
#poss_shape = [patch_shape[i+1] * (expected_shape[i] // patch_shape[i+1]) for i in range(ndims-1)]
pad_shape = (9, 9, 3)
poss_shape = [patch_shape[i + 1] * ((expected_shape[i] - pad_shape[i] * 2) // patch_shape[i + 1]) + pad_shape[i] * 2 for i in range(ndims - 1)]
#idxs = [range(patch_shape[i+1], poss_shape[i] - patch_shape[i+1], patch_shape[i+1]) for i in range(ndims-1)]
idxs = [range(pad_shape[i], poss_shape[i] - pad_shape[i], patch_shape[i + 1]) for i in range(ndims - 1)]
#pdb.set_trace()
return itertools.product(*idxs)
def extract_patches(volume, patch_shape, extraction_step) :
#patches = sk_extract_patches(
# volume,
# patch_shape=patch_shape,
# extraction_step=extraction_step)
#ndim = len(volume.shape)
#npatches = np.prod(patches.shape[:ndim])
#numPatches = 0
patchesList = []
for x_i in range(0,volume.shape[0]-patch_shape[0],extraction_step[0]):
for y_i in range(0,volume.shape[1]-patch_shape[1],extraction_step[1]):
for z_i in range(0,volume.shape[2]-patch_shape[2],extraction_step[2]):
#print('{}:{} to {}:{} to {}:{}'.format(x_i,x_i+patch_shape[0],y_i,y_i+patch_shape[1],z_i,z_i+patch_shape[2]))
patchesList.append(volume[x_i:x_i + patch_shape[0],
y_i:y_i + patch_shape[1],
z_i:z_i + patch_shape[2]])
#pdb.set_trace()
patches = np.concatenate(patchesList, axis=0)
#return patches.reshape((npatches, ) + patch_shape)
return patches.reshape((len(patchesList), ) + patch_shape)
# Double check that number of labels is continuous
def get_one_hot(targets, nb_classes):
#return np.eye(nb_classes)[np.array(targets).reshape(-1)]
return np.swapaxes(np.eye(nb_classes)[np.array(targets)],0,3) # Jose. To have the same shape as pytorch (batch_size, numclasses,x,y,z)
def build_set(imageData, numModalities) :
num_classes = 4
patch_shape = (27, 27, 27)
extraction_step=(5, 5, 5)
#extraction_step=(9, 9, 3)
label_selector = [slice(None)] + [slice(9, 18) for i in range(3)]
# Extract patches from input volumes and ground truth
imageData_1 = np.squeeze(imageData[0,:,:,:])
imageData_2 = np.squeeze(imageData[1,:,:,:])
if (numModalities==3):
imageData_3 = np.squeeze(imageData[2,:,:,:])
imageData_g = np.squeeze(imageData[3,:,:,:])
if (numModalities == 2):
imageData_g = np.squeeze(imageData[2, :, :, :])
num_classes = len(np.unique(imageData_g))
x = np.zeros((0, numModalities, 27, 27, 27))
y = np.zeros((0, 9, 9, 9))
#for idx in range(len(imageData)) :
y_length = len(y)
label_patches = extract_patches(imageData_g, patch_shape, extraction_step)
label_patches = label_patches[label_selector]
# Select only those who are important for processing
valid_idxs = np.where(np.sum(label_patches, axis=(1, 2, 3)) != 0)
# Filtering extracted patches
label_patches = label_patches[valid_idxs]
x = np.vstack((x, np.zeros((len(label_patches), numModalities, 27, 27, 27))))
y = np.vstack((y, np.zeros((len(label_patches), 9, 9, 9)))) # Jose
y = label_patches
del label_patches
# Sampling strategy: reject samples which labels are only zeros
T1_train = extract_patches(imageData_1, patch_shape, extraction_step)
x[y_length:, 0, :, :, :] = T1_train[valid_idxs]
del T1_train
# Sampling strategy: reject samples which labels are only zeros
T2_train = extract_patches(imageData_2, patch_shape, extraction_step)
x[y_length:, 1, :, :, :] = T2_train[valid_idxs]
del T2_train
if (numModalities==3):
# Sampling strategy: reject samples which labels are only zeros
Fl_train = extract_patches(imageData_3, patch_shape, extraction_step)
x[y_length:, 2, :, :, :] = Fl_train[valid_idxs]
del Fl_train
return x, y
def reconstruct_volume(patches, expected_shape) :
patch_shape = patches.shape
assert len(patch_shape) - 1 == len(expected_shape)
reconstructed_img = np.zeros(expected_shape)
for count, coord in enumerate(generate_indexes(patch_shape, expected_shape)) :
selection = [slice(coord[i], coord[i] + patch_shape[i+1]) for i in range(len(coord))]
#pdb.set_trace()
reconstructed_img[selection] = patches[count]
return reconstructed_img
def my_reconstruct_volume(patches, expected_shape, patch_shape, extraction_step) :
reconstructed_img = np.zeros(expected_shape)
idx = 0
#pdb.set_trace()
for x_i in range(0,expected_shape[0]-patch_shape[0],extraction_step[0]):
for y_i in range(0,expected_shape[1]-patch_shape[1],extraction_step[1]):
for z_i in range(0,expected_shape[2]-patch_shape[2],extraction_step[2]):
#pdb.set_trace()
reconstructed_img[(x_i + extraction_step[0]):(x_i + 2 * extraction_step[0]),
(y_i + extraction_step[1]):(y_i + 2 * extraction_step[1]),
(z_i + extraction_step[2]):(z_i + 2 * extraction_step[2])] = patches[idx]
#reconstructed_img[(x_i + extraction_step[0]):(x_i + 2 * extraction_step[0]),
# (y_i + extraction_step[1]):(y_i + 2 * extraction_step[1]),
# (z_i ):(z_i + extraction_step[2])] = patches[idx]
idx = idx + 1
return reconstructed_img
def load_data_trainG(paths, pathg, imageNames, numSamples, numModalities):
samplesPerImage = int(numSamples / len(imageNames))
# print(' - Extracting {} samples per image'.format(samplesPerImage))
X_train = []
Y_train = []
for num in range(len(imageNames)):
imageData_1 = nib.load(paths[0] + '/' + imageNames[num]).get_data()
imageData_2 = nib.load(paths[1] + '/' + imageNames[num]).get_data()
if (numModalities==3):
imageData_3 = nib.load(paths[2] + '/' + imageNames[num]).get_data()
imageData_g = nib.load(pathg + '/' + imageNames[num]).get_data()
num_classes = len(np.unique(imageData_g))
if (numModalities == 2):
imageData = np.stack((imageData_1, imageData_2, imageData_g))
if (numModalities == 3):
imageData = np.stack((imageData_1, imageData_2, imageData_3, imageData_g))
img_shape = imageData.shape
x_train, y_train = build_set(imageData, numModalities)
idx = np.arange(x_train.shape[0])
np.random.shuffle(idx)
x_train = x_train[idx[:samplesPerImage],]
y_train = y_train[idx[:samplesPerImage],]
X_train.append(x_train)
Y_train.append(y_train)
del x_train
del y_train
X_train = np.asarray(X_train)
Y_train = np.asarray(Y_train)
X = np.concatenate(X_train, axis=0)
del X_train
Y = np.concatenate(Y_train, axis=0)
del Y_train
idx = np.arange(X.shape[0])
np.random.shuffle(idx)
return X[idx], Y[idx], img_shape
def load_data_train(path1, path2, path3, pathg, imageNames, numSamples):
samplesPerImage = int(numSamples/len(imageNames))
X_train = []
Y_train = []
for num in range(len(imageNames)):
imageData_1 = nib.load(path1 + '/' + imageNames[num]).get_data()
imageData_2 = nib.load(path2 + '/' + imageNames[num]).get_data()
imageData_3 = nib.load(path3 + '/' + imageNames[num]).get_data()
imageData_g = nib.load(pathg + '/' + imageNames[num]).get_data()
num_classes = len(np.unique(imageData_g))
imageData = np.stack((imageData_1, imageData_2, imageData_3, imageData_g))
img_shape = imageData.shape
x_train, y_train = build_set(imageData)
idx = np.arange(x_train.shape[0])
np.random.shuffle(idx)
x_train = x_train[idx[:samplesPerImage],]
y_train = y_train[idx[:samplesPerImage],]
X_train.append(x_train)
Y_train.append(y_train)
del x_train
del y_train
X_train = np.asarray(X_train)
Y_train = np.asarray(Y_train)
X = np.concatenate(X_train, axis=0)
del X_train
Y = np.concatenate(Y_train, axis=0)
del Y_train
idx = np.arange(X.shape[0])
np.random.shuffle(idx)
return X[idx], Y[idx], img_shape
def load_data_test(path_n, pathg, imgName, number_modalities):
extraction_step_value = 9
imageData_1 = nib.load(path_n[0] + '/' + imgName).get_data()
imageData_2 = nib.load(path_n[1] + '/' + imgName).get_data()
if number_modalities==3 :
imageData_3 = nib.load(path_n[2] + '/' + imgName).get_data()
imageData_g = nib.load(pathg + '/' + imgName).get_data()
imageData_1_new = np.zeros((imageData_1.shape[0],imageData_1.shape[1], imageData_1.shape[2] + 2*extraction_step_value))
imageData_2_new = np.zeros((imageData_1.shape[0],imageData_1.shape[1], imageData_1.shape[2] + 2*extraction_step_value))
if number_modalities == 3:
imageData_3_new = np.zeros((imageData_1.shape[0],imageData_1.shape[1], imageData_1.shape[2] + 2*extraction_step_value))
imageData_g_new = np.zeros((imageData_1.shape[0],imageData_1.shape[1], imageData_1.shape[2] + 2*extraction_step_value))
imageData_1_new[:,:,extraction_step_value:extraction_step_value+imageData_1.shape[2]] = imageData_1
imageData_2_new[:,:,extraction_step_value:extraction_step_value+imageData_2.shape[2]] = imageData_2
if number_modalities == 3:
imageData_3_new[:,:,extraction_step_value:extraction_step_value+imageData_3.shape[2]] = imageData_3
imageData_g_new[:,:,extraction_step_value:extraction_step_value+imageData_g.shape[2]] = imageData_g
num_classes = len(np.unique(imageData_g))
if number_modalities == 2:
imageData = np.stack((imageData_1_new, imageData_2_new, imageData_g_new))
if number_modalities == 3:
imageData = np.stack((imageData_1_new, imageData_2_new, imageData_3_new, imageData_g_new))
img_shape = imageData.shape
patch_1 = extract_patches(imageData_1_new, patch_shape=(27, 27, 27), extraction_step=(9, 9, 9))
patch_2 = extract_patches(imageData_2_new, patch_shape=(27, 27, 27), extraction_step=(9, 9, 9))
if number_modalities == 3:
patch_3 = extract_patches(imageData_3_new, patch_shape=(27, 27, 27), extraction_step=(9, 9, 9))
patch_g = extract_patches(imageData_g_new, patch_shape=(27, 27, 27), extraction_step=(9, 9, 9))
if number_modalities==2 :
return patch_1, patch_2, patch_g, img_shape
if number_modalities==3 :
return patch_1, patch_2, patch_3, patch_g, img_shape