File size: 11,483 Bytes
d3d3177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# from concurrent.futures import ThreadPoolExecutor

# import sys
# import os


# import numpy as np
# import torch
# from torch.utils.data.dataset import Dataset

# import glob
# import cv2
# import torchio as tio
# import matplotlib.pyplot as plt
# from torch.utils.data import DataLoader
# from sdf import compute_sdf


# PREPROCESSING_TRANSORMS_CT = tio.Compose([
#     tio.Clamp(out_min=-250, out_max=800),
#     tio.RescaleIntensity(in_min_max=(-250, 800),
#                          out_min_max=(-1.0, 1.0)),
#     tio.CropOrPad(target_shape=(64, 64, 64))
# ])

# PREPROCESSING_TRANSORMS_MRI = tio.Compose([
#     tio.Clamp(out_min=0, out_max=1000),
#     tio.RescaleIntensity(in_min_max=(0, 1000),
#                          out_min_max=(-1.0, 1.0)),
#     tio.CropOrPad(target_shape=(64, 64, 64))
# ])


# PREPROCESSING_MASK_TRANSORMS = tio.Compose([
#     tio.CropOrPad(target_shape=(64, 64, 64))
# ])


# class MMWHS_Dataset(Dataset):
#     def __init__(self, root_dir='', data_type='', mode = ''):
#         self.root_dir = root_dir
#         self.data_type = data_type
#         self.mode = mode
#         self.file_names = self.get_file_names()
#         self.preprocessing_img_ct = PREPROCESSING_TRANSORMS_CT
#         self.preprocessing_img_mri = PREPROCESSING_TRANSORMS_MRI
#         self.preprocessing_mask = PREPROCESSING_MASK_TRANSORMS
    
#     @staticmethod
#     def create_mask(shape):
#         return torch.zeros(shape, dtype=torch.uint8)

#     @staticmethod 
#     def project_to_2d(mask):
#         projection = torch.max(mask, dim=0)[0]
#         return projection.numpy()

#     @staticmethod
#     def min_enclosing_circle(projection):

#         points = np.column_stack(np.where(projection > 0))
#         points = points.astype(np.float32)
#         print(points.shape)       
#         (x, y), radius = cv2.minEnclosingCircle(points.astype(np.float32))
#         center = (int(x), int(y))
#         radius = int(radius)
#         return center, radius

#     @staticmethod
#     def create_circle_mask_2d(shape, center, radius):
#         mask = np.zeros(shape, dtype=np.uint8)
#         cv2.circle(mask, center, radius, 1, thickness=-1)
#         return mask

#     @staticmethod
#     def apply_circle_mask_to_3d(mask, circle_mask_2d):
#         for i in range(mask.shape[0]):
#             mask[i] = torch.from_numpy(circle_mask_2d)
#         return mask
    
#     def train_transform(self, image, label, p):
#         TRAIN_TRANSFORMS = tio.Compose([
#             tio.RandomFlip(axes=(1), flip_probability=p),
#         ])
#         image = TRAIN_TRANSFORMS(image)
#         label = TRAIN_TRANSFORMS(label)
#         return image, label

#     def get_file_names(self):
#         all_img_names = glob.glob(os.path.join(self.root_dir, './*image.nii.gz'), recursive=True)
#         return all_img_names

#     def __len__(self):
#         return len(self.file_names)
    
#     def __getitem__(self, index):
#         img_path = self.file_names[index]
#         mask_path = img_path.replace("image.nii.gz", "label.nii.gz")
#         sdf_path = img_path.split()

#         img = tio.ScalarImage(img_path)
#         mask = tio.LabelMap(mask_path) 
#         name = img_path.split('/')[-1]
#         name = name.split('.nii')[0]
        
#         if self.data_type.upper() == 'CT':
#             img = self.preprocessing_img_ct(img)
#         elif self.data_type.upper() == 'MRI':
#             img = self.preprocessing_img_mri(img)
#         else:
#             raise ValueError("Wrong Data Type!")
#         mask = self.preprocessing_mask(mask)

#         # p = np.random.choice([0, 1])
#         # if self.mode == 'train':
#         #     img, mask = self.train_transform(img, mask, p)
        
#         affine = img.affine
#         mask = mask.data
#         img = img.data

#         label_1 = (mask == 1).float()
#         label_1_sdf = compute_sdf(label_1)
#         label_2 = (mask == 2).float()
#         label_2_sdf = compute_sdf(label_2)
#         label_3 = (mask == 3).float()
#         label_3_sdf = compute_sdf(label_3)
#         label_4 = (mask == 4).float()
#         label_4_sdf = compute_sdf(label_4)
#         label_5 = (mask == 5).float()
#         label_5_sdf = compute_sdf(label_5)
#         label = torch.cat((label_1, label_2, label_3, label_4, label_5), dim=0)
#         label_sdf = torch.cat((torch.tensor(label_1_sdf), torch.tensor(label_2_sdf), torch.tensor(label_3_sdf), torch.tensor(label_4_sdf), torch.tensor(label_5_sdf)), dim=0)
        
#         sdf_to_save = tio.ScalarImage(tensor=label_sdf, channels_last=False, affine=affine)
#         os.makedirs(self.root_dir, exist_ok=True)
#         sdf_to_save.save(os.path.join(self.root_dir, f"{name.replace('image', 'sdf')}.nii.gz"))
            
#         return {
#             'name': name,
#             'img': img,
#             'mask_sdf': label_sdf,
#             'mask': label,
#             'affine': affine
#         }

# def get_MMWHS_dataloader(root_dir, data_type, mode, batch_size=1, drop_last=False):
#     dataset = MMWHS_Dataset(root_dir=root_dir, data_type=data_type, mode=mode)
#     if mode == 'train':
#         shuffle = True
#         return dataset
#     elif mode == 'test':
#         shuffle = False
#     else:
#         raise ValueError('No Such Mode')
#     loader = DataLoader(
#         dataset, batch_size=batch_size, shuffle=shuffle, num_workers=20, pin_memory=True, drop_last=drop_last
#     )
#     return loader

# def test_dataset():
    
#     dl = get_MMWHS_dataloader(root_dir='/mnt/data2/data/store/MSN/data_v2/MMWHS-CT/MMWHS-CT-resize-try-tiny-train', data_type='CT', mode='test')
    
#     for batch in iter(dl):
#         print(batch['name'])

#     print(len(dl))

# if __name__ == '__main__':
#     test_dataset()



from concurrent.futures import ThreadPoolExecutor

import sys
import os


import numpy as np
import torch
from torch.utils.data.dataset import Dataset

import glob
import cv2
import torchio as tio
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader
from sdf import compute_sdf


PREPROCESSING_TRANSORMS_CT = tio.Compose([
    tio.Clamp(out_min=-250, out_max=800),
    tio.RescaleIntensity(in_min_max=(-250, 800),
                         out_min_max=(-1.0, 1.0)),
    tio.CropOrPad(target_shape=(64, 64, 64))
])

PREPROCESSING_TRANSORMS_MRI = tio.Compose([
    tio.Clamp(out_min=0, out_max=1000),
    tio.RescaleIntensity(in_min_max=(0, 1000),
                         out_min_max=(-1.0, 1.0)),
    tio.CropOrPad(target_shape=(64, 64, 64))
])


PREPROCESSING_MASK_TRANSORMS = tio.Compose([
    tio.CropOrPad(target_shape=(64, 64, 64))
])


class MMWHS_Dataset(Dataset):
    def __init__(self, root_dir='', data_type='', mode = ''):
        self.root_dir = root_dir
        self.data_type = data_type
        self.mode = mode
        self.file_names = self.get_file_names()
        self.preprocessing_img_ct = PREPROCESSING_TRANSORMS_CT
        self.preprocessing_img_mri = PREPROCESSING_TRANSORMS_MRI
        self.preprocessing_mask = PREPROCESSING_MASK_TRANSORMS
    
    @staticmethod
    def create_mask(shape):
        return torch.zeros(shape, dtype=torch.uint8)

    @staticmethod 
    def project_to_2d(mask):
        projection = torch.max(mask, dim=0)[0]
        return projection.numpy()

    @staticmethod
    def min_enclosing_circle(projection):

        points = np.column_stack(np.where(projection > 0))
        points = points.astype(np.float32)
        print(points.shape)       
        (x, y), radius = cv2.minEnclosingCircle(points.astype(np.float32))
        center = (int(x), int(y))
        radius = int(radius)
        return center, radius

    @staticmethod
    def create_circle_mask_2d(shape, center, radius):
        mask = np.zeros(shape, dtype=np.uint8)
        cv2.circle(mask, center, radius, 1, thickness=-1)
        return mask

    @staticmethod
    def apply_circle_mask_to_3d(mask, circle_mask_2d):
        for i in range(mask.shape[0]):
            mask[i] = torch.from_numpy(circle_mask_2d)
        return mask
    
    def train_transform(self, image, label, sdf, p):
        TRAIN_TRANSFORMS = tio.Compose([
            tio.RandomFlip(axes=(1), flip_probability=p),
        ])
        image = TRAIN_TRANSFORMS(image)
        label = TRAIN_TRANSFORMS(label)
        sdf = TRAIN_TRANSFORMS(sdf)
        return image, label, sdf

    def get_file_names(self):
        all_img_names = glob.glob(os.path.join(self.root_dir, './*image.nii.gz'), recursive=True)
        return all_img_names

    def __len__(self):
        return len(self.file_names)
    
    def __getitem__(self, index):
        img_path = self.file_names[index]
        mask_path = img_path.replace("image.nii.gz", "label.nii.gz")
        sdf_path = img_path.replace("image.nii.gz", "sdf.nii.gz")

        img = tio.ScalarImage(img_path)
        mask = tio.LabelMap(mask_path) 
        sdf = tio.ScalarImage(sdf_path) 
        name = img_path.split('/')[-1]
        name = name.split('.nii')[0]
        
        if self.data_type.upper() == 'CT':
            img = self.preprocessing_img_ct(img)
        elif self.data_type.upper() == 'MRI':
            img = self.preprocessing_img_mri(img)
        else:
            raise ValueError("Wrong Data Type!")
        mask = self.preprocessing_mask(mask)

        p = np.random.choice([0, 1])
        if self.mode == 'train':
            img, mask, sdf = self.train_transform(img, mask, sdf, p)
        
        affine = img.affine
        mask = mask.data
        img = img.data
        sdf = sdf.data

        label_1 = (mask == 1).float()
        # label_1_sdf = compute_sdf(label_1)
        label_2 = (mask == 2).float()
        # label_2_sdf = compute_sdf(label_2)
        label_3 = (mask == 3).float()
        # label_3_sdf = compute_sdf(label_3)
        label_4 = (mask == 4).float()
        # label_4_sdf = compute_sdf(label_4)
        label_5 = (mask == 5).float()
        # label_5_sdf = compute_sdf(label_5)
        label = torch.cat((label_1, label_2, label_3, label_4, label_5), dim=0)
        # label_sdf = torch.cat((torch.tensor(label_1_sdf), torch.tensor(label_2_sdf), torch.tensor(label_3_sdf), torch.tensor(label_4_sdf), torch.tensor(label_5_sdf)), dim=0)
        label_sdf = sdf
        # sdf_to_save = tio.LabelMap(tensor=label_sdf, channels_last=False, affine=affine)
        # os.makedirs(self.root_dir, exist_ok=True)
        # sdf_to_save.save(os.path.join(self.root_dir, f"{name.replace('image', 'sdf')}.nii.gz"))

        return {
            'name': name,
            'img': img,
            'mask_sdf': label_sdf,
            'mask': label,
            'affine': affine
        }

def get_MMWHS_dataloader(root_dir, data_type, mode, batch_size=1, drop_last=False):
    dataset = MMWHS_Dataset(root_dir=root_dir, data_type=data_type, mode=mode)
    if mode == 'train':
        shuffle = True
        return dataset
    elif mode == 'test':
        shuffle = False
    else:
        raise ValueError('No Such Mode')
    loader = DataLoader(
        dataset, batch_size=batch_size, shuffle=shuffle, num_workers=20, pin_memory=True, drop_last=drop_last
    )
    return loader

# def test_dataset():
    
#     dl = get_MMWHS_dataloader(root_dir='/mnt/data2/data/store/MSN/data/MMWHS-MRI/mr_train_clean_resize_to_64_train_10percent', data_type='MRI', mode='test')
    
#     for batch in iter(dl):
#         print(batch['name'])

#     print(len(dl))

# if __name__ == '__main__':
#     test_dataset()