forked from seungjunlee96/U-Net_Lung-Segmentation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LungSegmentationDataset.py
161 lines (132 loc) · 5.59 KB
/
LungSegmentationDataset.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
import torch
import torchvision
import numpy as np
from torch.utils.data import DataLoader,Dataset
import os
import random
import cv2
from PIL import Image
from skimage import io
# torch.utils.data.Dataset is an abstract class representing a dataset
class CovidCTDataset(Dataset): # inherit from torch.utils.data.Dataset
"Lung sengmentation dataset."
def __init__(self,root_dir = os.path.join(os.getcwd(),"data/Lung Segmentation"),split, transforms = None , shuffle = True):
"""
Args:
:param root_dir (str):
:param split (str):
:param transforms (callable, optional) :
"""
self.root_dir = root_dir
self.split = split # train / val / test
self.transforms = transforms
# data
# train set : CHN
# test/validation set : MCU
self.image_path = self.root_dir + '/images/'
#image_file = os.listdir(self.image_path)
#self.train_image_file = [fName for fName in image_file if "CHNCXR" in fName]
#self.train_image_idx = sorted([int(fName.split("_")[1]) for fName in self.train_image_file])
#self.eval_image_file = [fName for fName in image_file if "MCUCXR" in fName]
#self.eval_image_idx = sorted([int(fName.split("_")[1]) for fName in self.eval_image_file])
# target
self.mask_path = os.path.join(self.root_dir,'masks_as_images')
#mask_file = os.listdir(self.mask_path)
#self.train_mask_file = [fName for fName in mask_file if "CHNCXR" in fName]
#self.train_mask_idx = sorted([int(fName.split("_")[1]) for fName in self.train_mask_file])
#self.eval_mask_file = [fName for fName in mask_file if "MCUCXR" in fName]
#self.eval_mask_idx = sorted([int(fName.split("_")[1]) for fName in self.eval_mask_file])
# train/ val / test
# for train set, we use CHN
# for test and validation set, we use MCU
#self.train_idx = [idx for idx in self.train_image_idx if idx in self.train_mask_idx]
#self.eval_idx = [idx for idx in self.eval_image_idx if idx in self.eval_mask_idx]
#self.val_idx = self.eval_idx[:int(0.5*len(self.eval_idx))]
#self.test_idx = self.eval_idx[int(0.5*len(self.eval_idx)):]
#self.data_file = {"train" : {"image":self.train_image_file , "mask": self.train_mask_file},
# "val" : {"image":self.eval_image_file , "mask": self.eval_mask_file },
# "test" : {"image":self.eval_image_file , "mask": self.eval_mask_file}}
#self.data_idx ={"train" : self.train_idx,
# "val" : self.val_idx,
# "test" : self.test_idx}
# print("The Total number of data =",len(self.train_idx) + len(self.val_idx) + len(self.test_idx))
# print("The Total number of train data =", len(self.train_idx))
# print("The Total number of val data =", len(self.val_idx))
# print("The Total number of test data =", len(self.test_idx))
def __len__(self):
return len(self.split)
def __getitem__(self, idx):
img_name = self.split[idx]
# set index
#for fName in self.data_file[self.split]["image"]:
# file_idx = int(fName.split('_')[1])
# if idx == file_idx:
# img_fName = fName
img_path = os.path.join(self.image_path, img_name)
img = Image.open(img_path).convert('LA') # open as PIL Image and set Channel = 1
# img = cv2.imread(img_path)
#for fName in self.data_file[self.split]["mask"]:
# file_idx = int(fName.split('_')[1])
# if idx == file_idx:
# mask_fName = fName
mask_path = os.path.join(self.mask_path, image_path)
mask = Image.open(mask_path) # PIL Image
# mask = cv2.imread(mask_path)
sample = {'image': img, 'mask': mask}
if self.transforms:
sample = self.transforms(sample)
if isinstance(img,torch.Tensor) and isinstance(mask, torch.Tensor):
assert img.size == mask.size
return sample
if __name__ == "__main__":
"""Visualization"""
import matplotlib.pyplot as plt
import numpy as np
import torchvision.transforms as transforms
from my_transforms import Resize, ToTensor, GrayScale
from torch.utils.data import DataLoader
# set img size
img_size = 512
scale = Resize(512)
composed = transforms.Compose([Resize(600),
GrayScale()])
data = LungSegDataset(split='val')
def show(img, mask):
combined = np.hstack((img, mask))
plt.imshow(combined)
fig = plt.figure(figsize=(30,30))
cnt = 0
for i in range(len(data)):
sample = data[i]
# for i in range(len(data)):
# if i == 3:
# break
# sample = data[i]
# for tsfrm in [composed]:
# transformed_sample = tsfrm(sample)
#
# ax = plt.subplot(1, 3, i + 1)
# plt.tight_layout()
# ax.set_title(type(tsfrm).__name__)
# show(transformed_sample['image'],transformed_sample['mask'])
#
#
#
# plt.show()
# print(data.train_image_idx)
# print(data.train_mask_idx)
# print(data.train_idx)
# # print(data.train_mask_file[1].split("_"))
# sample = []
# for i in range(6):
# i += 100
# combined = np.hstack((data[i]['image'],data[i]['mask']))
# sample.append(combined)
#
# plt.figure(figsize=(25, 10))
#
# for i in [0,3]:
# for j in [1,2,3]:
# plt.subplot(2, 3, i + j)
# plt.imshow(sample[i + j - 1])
# plt.show()