-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdataHelper.py
213 lines (192 loc) · 8.04 KB
/
dataHelper.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
from __future__ import division
import numpy as np
import os
import pandas as pd
import argparse
import sys
import random
import png
from matplotlib.pyplot import imsave, imread
import matplotlib
from PIL import Image
import cv2
matplotlib.use("Agg")
import torchvision.datasets as datasets
from skimage.transform import resize
import ast
import pickle
import csv
import pydicom as dcm
import Augmentor
from tqdm import tqdm
import pathlib
from torch import randint, manual_seed
from copy import copy
from collections import defaultdict
def make_dataset(dir, class_to_idx, extensions=None, is_valid_file=None):
images = []
dir = os.path.expanduser(dir)
if not ((extensions is None) ^ (is_valid_file is None)):
raise ValueError("Both extensions and is_valid_file cannot be None or not None at the same time")
for target in sorted(class_to_idx.keys()):
d = os.path.join(dir, target)
if not os.path.isdir(d):
continue
for root, _, fnames in sorted(os.walk(d)):
for fname in sorted(fnames):
path = os.path.join(root, fname)
item = (path, class_to_idx[target])
images.append(item)
return images
def random_flip(input, axis, with_fa=False):
ran = random.random()
if ran > 0.5:
if with_fa:
axis += 1
return np.flip(input, axis=axis)
else:
return input
def random_crop(input, with_fa=False):
ran = random.random()
if ran > 0.2:
# find a random place to be the left upper corner of the crop
if with_fa:
rx = int(random.random() * input.shape[1] // 10)
ry = int(random.random() * input.shape[2] // 10)
return input[:, rx: rx + int(input.shape[1] * 9 // 10), ry: ry + int(input.shape[2] * 9 // 10)]
else:
rx = int(random.random() * input.shape[0] // 10)
ry = int(random.random() * input.shape[1] // 10)
return input[rx: rx + int(input.shape[0] * 9 // 10), ry: ry + int(input.shape[1] * 9 // 10)]
else:
return input
def random_rotate_90(input, with_fa=False):
ran = random.random()
if ran > 0.5:
if with_fa:
return np.rot90(input, axes=(1,2))
return np.rot90(input)
else:
return input
def random_rotation(x, chance, with_fa=False):
ran = random.random()
if with_fa:
img = Image.fromarray(x[0])
mask = Image.fromarray(x[1])
if ran > 1 - chance:
# create black edges
angle = np.random.randint(0, 90)
img = img.rotate(angle=angle, expand=1)
mask = mask.rotate(angle=angle, expand=1, fillcolor=1)
return np.stack([np.asarray(img), np.asarray(mask)])
else:
return np.stack([np.asarray(img), np.asarray(mask)])
img = Image.fromarray(x)
if ran > 1 - chance:
# create black edges
angle = np.random.randint(0, 90)
img = img.rotate(angle=angle, expand=1)
return np.asarray(img)
else:
return np.asarray(img)
class DatasetFolder(datasets.DatasetFolder):
def __init__(self, root, loader, augmentation=False, extensions=None, transform=None,
target_transform=None, is_valid_file=None, target_size=(224, 224)):
super(DatasetFolder, self).__init__(root, loader, ("npy",),
transform=transform,
target_transform=target_transform, )
classes, class_to_idx = self._find_classes(self.root)
samples = make_dataset(self.root, class_to_idx, extensions, is_valid_file)
if len(samples) == 0:
raise (RuntimeError("Found 0 files in subfolders of: " + self.root + "\n"
"Supported extensions are: " + ",".join(
extensions)))
self.loader = loader
self.extensions = extensions
self.classes = classes
self.class_to_idx = class_to_idx
self.samples = samples
self.augment = augmentation
self.target_size = target_size
self.targets = [s[1] for s in samples]
def _find_classes(self, dir):
if sys.version_info >= (3, 5):
# Faster and available in Python 3.5 and above
classes = [d.name for d in os.scandir(dir) if d.is_dir()]
else:
classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]
classes.sort()
class_to_idx = {classes[i]: i for i in range(len(classes))}
return classes, class_to_idx
def __getitem__(self, index):
path, target = self.samples[index]
patient_id = path.split("/")[-1][:-4]
sample = self.loader(path)
if len(sample.shape) == 3:
if self.target_size:
sample = np.stack([resize(sample[0], self.target_size), resize(sample[1], self.target_size)])
temp = [sample[0], sample[0], sample[0], sample[1]]
else:
if self.target_size:
sample = resize(sample, self.target_size)
if self.augment:
sample = random_rotation(sample, 0.7)
temp = [sample, sample, sample]
n = np.stack(temp)
if self.transform is not None:
sample = self.transform(n)
if self.target_transform is not None:
target = self.target_transform(target)
# print("after transform", sample.shape)
return sample.float(), target, patient_id
class DatasetFolder_WithReplacement(datasets.DatasetFolder):
def __init__(self, root, loader, augmentation=False, extensions=None, transform=None,
target_transform=None, is_valid_file=None, target_size=(224, 224)):
super(DatasetFolder_WithReplacement, self).__init__(root, loader, ("npy",),
transform=transform,
target_transform=target_transform, )
classes, class_to_idx = self._find_classes(self.root)
samples = make_dataset(self.root, class_to_idx, extensions, is_valid_file)
if len(samples) == 0:
raise (RuntimeError("Found 0 files in subfolders of: " + self.root + "\n"
"Supported extensions are: " + ",".join(
extensions)))
self.loader = loader
self.extensions = extensions
self.classes = classes
self.class_to_idx = class_to_idx
self.samples = samples
self.augment = augmentation
self.target_size = target_size
self.targets = [s[1] for s in samples]
def _find_classes(self, dir):
if sys.version_info >= (3, 5):
# Faster and available in Python 3.5 and above
classes = [d.name for d in os.scandir(dir) if d.is_dir()]
else:
classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]
classes.sort()
class_to_idx = {classes[i]: i for i in range(len(classes))}
return classes, class_to_idx
def __getitem__(self, index):
index = randint(0, len(self.samples), (1,))[0] #pull with replacement
path, target = self.samples[index]
patient_id = path.split("/")[-1][:-4]
sample = self.loader(path)
if len(sample.shape) == 3:
if self.target_size:
sample = np.stack([resize(sample[0], self.target_size), resize(sample[1], self.target_size)])
temp = [sample[0], sample[0], sample[0], sample[1]]
else:
if self.target_size:
sample = resize(sample, self.target_size)
if self.augment:
sample = random_rotation(sample, 0.7)
temp = [sample, sample, sample]
n = np.stack(temp)
if self.transform is not None:
sample = self.transform(n)
if self.target_transform is not None:
target = self.target_transform(target)
# print("after transform", sample.shape)
return sample.float(), target, patient_id