This repository was archived by the owner on Jul 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdatasets.py
265 lines (203 loc) · 5.98 KB
/
datasets.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
"""
Implementation of data sets used by the deep learning models.
Each data set contains input images and associated targets. Targets depend
on the data set (a class for the ClassDataset and an image for the
ImageDataset).
"""
###########
# Imports #
###########
import cv2
import io
import json
import numpy as np
import torch
import torchvision.transforms as transforms
from PIL import Image, ImageFilter
from torch.utils.data import Dataset
from tqdm import tqdm
from typing import Tuple
##########
# Typing #
##########
PILImage = Image.Image
#############
# Functions #
#############
def to_edges(img: PILImage) -> PILImage:
"""
Extract the edges from an image.
"""
# Convert to numpy array
img = np.array(img)
# Extract edges
lo_thresh = 50
hi_thresh = 250
filter_size = 3
img = cv2.Canny(
img,
lo_thresh,
hi_thresh,
apertureSize=filter_size,
L2gradient=True
)
# Convert to PIL Image
img = Image.fromarray(img)
return img
###########
# Classes #
###########
class ClassDataset(Dataset):
"""
Data set that contains input images and associated target classes.
The JSON data file has to have the following format (example for a
4 classes classification problem):
[
{
"image": "path/to/image.png",
"target": [0, 0, 1, 0]
},
...
]
Each pair is composed of the path to the image and the target whose
format is the target tensor used by PyTorch.
"""
def __init__(
self,
json_pth: str,
augment: bool = False,
dtype: torch.dtype = torch.float,
edges: bool = False
):
super().__init__()
# Data
self.data = []
# Process
self.process = transforms.ToTensor()
# Data augmentation
if augment:
self.augment = transforms.RandomChoice([
lambda x: x,
lambda x: x.filter(ImageFilter.BLUR),
lambda x: x.filter(ImageFilter.EDGE_ENHANCE),
lambda x: x.filter(ImageFilter.SMOOTH),
transforms.ColorJitter(
brightness=0.25,
contrast=(0.2, 0.6),
saturation=(0.2, 0.6)
)
])
else:
self.augment = None
# Target data type
self.dtype = dtype
# Edges
self.edges = edges
# Get data
with open(json_pth, 'r') as json_file:
pairs = json.load(json_file)
for pair in tqdm(pairs):
data = []
# Image
with open(pair['image'], 'rb') as img:
img_bytes = io.BytesIO(img.read())
data.append(img_bytes)
# Target
target = pair['target']
data.append(target)
# Save tuple
self.data.append(tuple(data))
def __getitem__(self, index: int) -> Tuple[torch.Tensor, torch.Tensor]:
# Get data
img, target = self.data[index]
# Image
img = Image.open(img)
if self.edges:
img = to_edges(img)
elif self.augment is not None:
img = self.augment(img)
img = self.process(img)
# Target
target = torch.tensor(target, dtype=self.dtype)
return img, target
def __len__(self) -> int:
return len(self.data)
class ImageDataset(Dataset):
"""
Data set that contains input images and associated target images.
The JSON data file has to have the following format:
[
{
"image": "path/to/image.png",
"target": "path/to/target.png"
},
...
]
Each pair is composed of the path to the input image and the path to the
target image.
"""
def __init__(
self,
json_pth: str,
augment: bool = False,
dtype: torch.dtype = torch.long,
edges: bool = False
):
super().__init__()
# Data
self.data = []
# Process
self.process = transforms.ToTensor()
# Data augmentation
if augment:
self.augment = transforms.RandomChoice([
lambda x: x,
lambda x: x.filter(ImageFilter.BLUR),
lambda x: x.filter(ImageFilter.EDGE_ENHANCE),
lambda x: x.filter(ImageFilter.SMOOTH),
transforms.ColorJitter(
brightness=0.25,
contrast=(0.2, 0.6),
saturation=(0.2, 0.6)
)
])
else:
self.augment = None
# Target data type
self.dtype = dtype
# Edges
self.edges = edges
# Get data
with open(json_pth, 'r') as json_file:
pairs = json.load(json_file)
for pair in tqdm(pairs):
data = []
# Input
with open(pair['image'], 'rb') as img:
img_bytes = io.BytesIO(img.read())
data.append(img_bytes)
# Target
with open(pair['target'], 'rb') as img:
img_bytes = io.BytesIO(img.read())
data.append(img_bytes)
# Save tuple
self.data.append(tuple(data))
def __getitem__(self, index: int) -> Tuple[torch.Tensor, torch.Tensor]:
# Get data
inpt, trgt = self.data[index]
# Input
inpt = Image.open(inpt)
if self.edges:
img = to_edges(img)
elif self.augment is not None:
inpt = self.augment(inpt)
inpt = self.process(inpt)
# Target
trgt = Image.open(trgt)
trgt = np.array(trgt, dtype='uint8', copy=True)
trgt = torch.from_numpy(trgt)
trgt = trgt.to(dtype=self.dtype)
trgt = trgt.squeeze(0)
return inpt, trgt
def __len__(self) -> int:
return len(self.data)