-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpan_radiographs_data.py
163 lines (131 loc) · 5.12 KB
/
pan_radiographs_data.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
import os
from pathlib import Path
from typing import List, Union, Tuple
import numpy as np
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
import torch
from torch.utils.data import Dataset
import torchvision.transforms as T
import sys
# sys.path.append('..')
class FullRadiographDataset(Dataset):
def __init__(
self,
root_dir: str,
fold_nums: list,
transforms,
fold_txt_dir: str='splits',
albumentations_package: bool=True
):
super().__init__()
self.root_dir = root_dir
self.fold_nums = fold_nums
self.transforms = transforms
self.albumentations = albumentations_package
# labels
self.filepaths = []
self._load_images(fold_txt_dir)
# this maybe useful later for reproducibility
self.filepaths.sort()
print(f"> Successfully Loaded {len(self.filepaths)} images.")
def _load_images(self,fold_txt_dir):
for i in self.fold_nums:
filepath = os.path.join(self.root_dir, fold_txt_dir, f'{i:02d}.txt')
with open(filepath) as txt_file:
for line in txt_file:
img_relpath = line.strip()
filename = img_relpath.split('/')[-1]
sex = filename.split('-')[10]
# if sex not in ['M', 'F']:
# continue
self.filepaths.append(os.path.join(self.root_dir, img_relpath))
def __len__(self) -> int:
return len(self.filepaths)
def __getitem__(self, index: int):
# image and label
filepath = self.filepaths[index]
filename = filepath.split('/')[-1]
# get the labels
sex = filename.split('-')[10]
# age = filename.split('-')[-2][1:]
# months = filename.split('-')[-1][1:3]
assert sex in ['F', 'M', 'NA']
if sex == 'F':
label = 0
elif sex == 'M':
label = 1
else:
label = -1
label_tensor = torch.tensor(label, dtype=torch.int64)
image = Image.open(filepath).convert('RGB')
# apply transforms
if self.transforms:
#image = np.array(image)
image = self.transforms(image)
return image, label_tensor
class LabelledSet(FullRadiographDataset):
def __init__(self, root_dir, fold_nums, transforms):
super().__init__(root_dir, fold_nums, transforms)
def _load_images(self,fold_txt_dir):
for i in self.fold_nums:
filepath = os.path.join(self.root_dir, fold_txt_dir, f'{i:02d}.txt')
with open(filepath) as txt_file:
for line in txt_file:
img_relpath = line.strip()
filename = img_relpath.split('/')[-1]
sex = filename.split('-')[10]
if sex not in ['M', 'F']: # Assert all images are labelled.
continue
self.filepaths.append(os.path.join(self.root_dir, img_relpath))
def __getitem__(self, index: int):
# image and label
filepath = self.filepaths[index]
filename = filepath.split('/')[-1]
# get the labels
sex = filename.split('-')[10]
# age = filename.split('-')[-2][1:]
# months = filename.split('-')[-1][1:3]
label = 0 if sex == "M" else 1
#label_tensor = torch.tensor(label)
image = Image.open(filepath)
image = image.convert('RGB')
# apply transforms
if self.transforms:
# image = np.array(image)
image = self.transforms(image)
return image, label
class UnlabelledSet(FullRadiographDataset):
def __init__(self, root_dir, fold_nums, transforms):
super().__init__(root_dir, fold_nums, transforms)
def _load_images(self,fold_txt_dir):
for i in self.fold_nums:
filepath = os.path.join(self.root_dir, fold_txt_dir, f'{i:02d}.txt')
with open(filepath) as txt_file:
for line in txt_file:
img_relpath = line.strip()
filename = img_relpath.split('/')[-1]
sex = filename.split('-')[10]
self.filepaths.append(os.path.join(self.root_dir, img_relpath))
def __getitem__(self, index: int):
# image and label
filepath = self.filepaths[index]
image = Image.open(filepath)
image = image.convert('RGB')
# apply transforms
if self.transforms:
# image = np.array(image)
image = self.transforms(image)
return image
if __name__ == "__main__":
root = "/datasets/pan-radiographs/"
f = FullRadiographDataset(root, list(range(1,31)), None)
print("[!] Successfully loaded full radiograph dataset.")
print(" > Sample batch:\n", f[0])
u = UnlabelledSet(root, list(range(1,26)), None)
print("[!] Successfully loaded unlabelled dataset.")
print(" > Sample batch:\n", u[0])
l = LabelledSet(root, list(range(26,31)), None)
print("[!] Successfully loaded labelled dataset.")
print(" > Sample batch:\n", l[0])
print("[!] All good!")