-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataset.py
279 lines (197 loc) · 10.2 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
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
import os
import torch
from torch.utils.data import Dataset
import SimpleITK as sitk
import numpy as np
import torch.nn as nn
import matplotlib.pyplot as plt
from monai.transforms import ScaleIntensity
from ipywidgets import interact
import ipywidgets as widgets
# from monai.transforms import SpatialPadd
class PelvisDataset(Dataset):
def __init__(self, root_dir, input_dim=(224, 224, 224), nlabels=4, transform=None):
super(PelvisDataset, self).__init__()
self.root_dir = root_dir
self.input_dim = input_dim
self.transform = transform
self.nlabels = nlabels
# define the path for images and their labels
self.images_path = self.root_dir + '/images/'
self.labels_path = self.root_dir + '/multilabel_landmarks/'
# sort the list of images and labels so that they match
self.images = sorted(os.listdir(self.images_path))
self.labels = sorted(os.listdir(self.labels_path))
def __len__(self):
return len(self.images)
def __getitem__(self, idx):
# Select the item of interest
img_name = self.images[idx]
label_name = self.labels[idx]
# print(img_name)
# read the images and labels and convert them to numpy arrays
image = sitk.ReadImage(self.images_path + img_name)
label = sitk.ReadImage(self.labels_path + label_name)
# Transform them if specified
if self.transform:
image, label = self.transform((image, label))
image = sitk.GetArrayFromImage(image)
labels = sitk.GetArrayFromImage(label)
label_img = np.copy(label)
# Generar un tensor de 7 canales para el background y los 6 labels:
n_labels = int(labels.max())
tensor = torch.zeros((7, labels.shape[0], labels.shape[1], labels.shape[2]), dtype=torch.int64)
for i in range(n_labels):
label_copy = labels.copy()
label_copy[label_copy!=i]=0
# print(label_copy.max())
label_copy[label_copy!=0]= 1
# print(label_copy.max())
tensor[i,:,:,:]= torch.from_numpy(label_copy)
# if n_labels < 7:
# for i in range(7-n_labels):
# label_copy = np.zeros_like(labels)
# tensor[n_labels+i,:,:,:]= torch.from_numpy(label_copy)
label_tensor = tensor
n_labels = int(labels.max())
tensor = torch.zeros((7, labels.shape[0], labels.shape[1], labels.shape[2]), dtype=torch.int64)
for i in range(n_labels):
label_copy = labels.copy()
label_copy[label_copy!=i]=0
tensor[i,:,:,:]= torch.from_numpy(label_copy)
# if n_labels < 7:
# for i in range(7-n_labels):
# label_copy = np.zeros_like(labels)
# tensor[n_labels+i,:,:,:]= torch.from_numpy(label_copy)
label_tensor = tensor
def plot_targets(targets):
depth_slice = targets[:, :, :, :]
def plot_images(slice_index):
fig, axes = plt.subplots(1, 7, figsize=(20, 10))
for i in range(7):
image_array = depth_slice[i, slice_index, :, :].cpu().detach().numpy()
axes[i].imshow(image_array, cmap="gray")
axes[i].set_title("Channel {}".format(i))
axes[i].axis('off')
plt.show()
interact(plot_images, slice_index=widgets.IntSlider(min=0, max=depth_slice.shape[1] - 1, step=1, value=22))
# plot_targets(label_tensor)
# change the order so that it is CxWxHxD instead of WxHxDxC
# label_tensor = label_one_hot.permute(3, 0, 1, 2)
# label_tensor = label_one_hot[0:1,:,:,:]
# Convert image to PyTorch tensor so that dimensions are CxWxHxD
image_tensor = torch.from_numpy(image).float().unsqueeze(0)
# image_tensor = torch.repeat_interleave(image_tensor, 7, dim=0)
# padding_layer = nn.ConstantPad3d(padding=(31, 31, 54, 54, 75, 76), value=0)
padding_layer = nn.ConstantPad3d(padding=(7, 7, 6, 6, 4, 3), value=0)
image_tensor = padding_layer(image_tensor)
label_tensor = padding_layer(label_tensor)
# print("label tensor", label_tensor.shape)
# print("image tensor", image_tensor.shape)
return image_tensor, label_tensor, img_name, label_name
# import os
# import torch
# from torch.utils.data import Dataset
# import SimpleITK as sitk
# import numpy as np
# import torch.nn as nn
# import matplotlib.pyplot as plt
# from monai.transforms import ScaleIntensity
# from monai.data import DataLoader, CacheDataset, ImageDataset, Dataset, image_reader
# # from monai.transforms import SpatialPadd
# class PelvisDataset(Dataset):
# def __init__(self, root_dir, input_dim=(224, 224, 224), nlabels=4, transform=None):
# super(PelvisDataset).__init__()
# self.root_dir = root_dir
# self.input_dim = input_dim
# self.transform = transform
# self.nlabels = nlabels
# # define the path for images and their labels
# self.images_path = self.root_dir + '/images/'
# self.labels_path = self.root_dir + '/landmarks/'
# # sort the list of images and labels so that they match
# self.images = sorted(os.listdir(self.images_path))
# self.labels = sorted(os.listdir(self.labels_path))
# def __len__(self):
# return len(self.images)
# def __getitem__(self, idx):
# # Select the item of interest
# img_name = self.images[idx]
# label_name = self.labels[idx]
# # print(img_name)
# # read the images and labels and convert them to numpy arrays
# image = sitk.ReadImage(self.images_path + img_name)
# label = sitk.ReadImage(self.labels_path + label_name)
# # Transform them if specified
# if self.transform:
# image, label = self.transform((image, label))
# image = sitk.GetArrayFromImage(image)
# label = sitk.GetArrayFromImage(label)
# # image = (image_array - np.min(image_array)) / (np.max(image_array) - np.min(image_array))
# # fig, axes = plt.subplots(1, 2, figsize=(10, 5))
# # axes[1].imshow(image_array[22,:,:],cmap="gray")
# # axes[1].set_title("before norm")
# # axes[0].imshow(image[22,:,:],cmap="gray")
# # axes[0].set_title("afternorm")
# # print('image size', image.shape)
# # print("label size", label.shape)
# # Apply the transform to your image
# # label_t = np.transpose(label, (2,1,0) )
# label_t = label
# # axes[1].imshow(label_t[22,:,:],cmap="gray")
# # axes[1].set_title("label")
# # axes[0].imshow(image[22,:,:],cmap="gray")
# # axes[0].set_title("image")
# label_img = np.copy(label_t)
# # Establecer todos los valores distintos de 0 a 1
# label_img[abs(label_img) > 1e-3] = 1
# label_img[abs(label_img) <= 1e-3] = 0
# label_one_hot = torch.from_numpy(label_img).float().unsqueeze(0)
# label_tensor = label_one_hot[0:1,:,:,:]
# # Convert image to PyTorch tensor so that dimensions are CxWxHxD
# image_tensor = torch.from_numpy(image).float().unsqueeze(0)
# desired_size = [256,256,256]
# im_size=image.shape
# # padding_layer = nn.ConstantPad3d(padding=( (desired_size[0]-im_size[0]//2), (desired_size[0]-im_size[0]//2), (desired_size[1]-im_size[1]//2), (desired_size[1]-im_size[1]//2), (desired_size[2]-im_size[2]//2), (desired_size[2]-im_size[2]//2)), value=0)
# padding_layer = nn.ConstantPad3d(padding=( 3, 3, 5, 5, 7, 7), value=0)
# image_tensor = padding_layer(image_tensor)
# label_tensor = padding_layer(label_tensor)
# image_tensor = image_tensor.permute(0,3,2,1)
# label_tensor = label_tensor.permute(0,3,2,1)
# print('final image tensor, ', image_tensor.shape)
# print('final label tensor, ', label_tensor.shape)
# return image_tensor, label_tensor
# # def plotitem(self, idx, slc=None):
# # # Select the item of interest
# # img_name = self.images[idx]
# # label_name = self.labels[idx]
# # # Read the images and labels
# # image = sitk.ReadImage(self.images_path + img_name)
# # image = np.array(sitk.GetArrayFromImage(image))
# # label = sitk.ReadImage(self.labels_path + label_name)
# # label = np.array(sitk.GetArrayFromImage(label))
# # # Transform them if specified
# # if self.transform:
# # sample = (image, label)
# # sample = self.transform(sample)
# # image, label = sample
# # # Select the middle slice if not specified
# # if slc is None:
# # slc = image.shape[2] // 2
# # image = sitk.GetImageFromArray(image)
# # label = sitk.GetImageFromArray(label)
# # fig, axs = plt.subplots(2, 3, figsize=(10, 8))
# # axs[0, 0].imshow(sitk.GetArrayViewFromImage(image)[:, :, slc], cmap=plt.cm.Greys_r)
# # axs[0, 0].set_title(f'Sagittal plane image {img_name.strip(".nii.gz")}')
# # axs[0, 1].imshow(sitk.GetArrayViewFromImage(image)[:, slc, :], cmap=plt.cm.Greys_r)
# # axs[0, 1].set_title(f'Coronal Plane {img_name.strip(".nii.gz")}')
# # axs[0, 2].imshow(sitk.GetArrayViewFromImage(image)[slc, :, :], cmap=plt.cm.Greys_r)
# # axs[0, 2].set_title(f'Axial plane {img_name.strip(".nii.gz")}')
# # axs[1, 0].imshow(sitk.GetArrayViewFromImage(label)[:, :, slc], cmap=plt.cm.Greys_r)
# # axs[1, 0].set_title(f'Sagittal plane label {label_name.strip(".nii.gz")}')
# # axs[1, 1].imshow(sitk.GetArrayViewFromImage(label)[:, slc, :], cmap=plt.cm.Greys_r)
# # axs[1, 1].set_title(f'Coronal Plane {label_name.strip(".nii.gz")}')
# # axs[1, 2].imshow(sitk.GetArrayViewFromImage(label)[slc, :, :], cmap=plt.cm.Greys_r)
# # axs[1, 2].set_title(f'Axial plane {label_name.strip(".nii.gz")}')
# # plt.tight_layout()
# # plt.show()