This repository has been archived by the owner on Sep 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 163
/
Copy pathdata.py
306 lines (278 loc) · 8.28 KB
/
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
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
import cv2
import numpy as np
import torch
def albumentations2torchvision(transforms):
"""Wrap albumentations transformation so that they can be used in torchvision dataset"""
from albumentations import Compose
def wrapper_func(image, target):
keys = ["image", "mask"]
np_dtypes = [np.float32, np.uint8]
torch_dtypes = [torch.float32, torch.long]
sample_dict = {
key: np.array(value, dtype=dtype)
for key, value, dtype in zip(keys, [image, target], np_dtypes)
}
output = Compose(transforms)(**sample_dict)
return [output[key].to(dtype) for key, dtype in zip(keys, torch_dtypes)]
return wrapper_func
def albumentations_transforms(
crop_size,
shorter_side,
low_scale,
high_scale,
img_mean,
img_std,
img_scale,
ignore_label,
num_stages,
dataset_type,
):
from albumentations import (
Normalize,
HorizontalFlip,
RandomCrop,
PadIfNeeded,
RandomScale,
LongestMaxSize,
SmallestMaxSize,
OneOf,
)
from albumentations.pytorch import ToTensorV2 as ToTensor
from densetorch.data import albumentations2densetorch
if dataset_type == "densetorch":
wrapper = albumentations2densetorch
elif dataset_type == "torchvision":
wrapper = albumentations2torchvision
else:
raise ValueError(f"Unknown dataset type: {dataset_type}")
common_transformations = [
Normalize(max_pixel_value=1.0 / img_scale, mean=img_mean, std=img_std),
ToTensor(),
]
train_transforms = []
for stage in range(num_stages):
train_transforms.append(
wrapper(
[
OneOf(
[
RandomScale(
scale_limit=(low_scale[stage], high_scale[stage])
),
LongestMaxSize(max_size=shorter_side[stage]),
SmallestMaxSize(max_size=shorter_side[stage]),
]
),
PadIfNeeded(
min_height=crop_size[stage],
min_width=crop_size[stage],
border_mode=cv2.BORDER_CONSTANT,
value=np.array(img_mean) / img_scale,
mask_value=ignore_label,
),
HorizontalFlip(p=0.5,),
RandomCrop(height=crop_size[stage], width=crop_size[stage],),
]
+ common_transformations
)
)
val_transforms = wrapper(common_transformations)
return train_transforms, val_transforms
def densetorch_transforms(
crop_size,
shorter_side,
low_scale,
high_scale,
img_mean,
img_std,
img_scale,
ignore_label,
num_stages,
dataset_type,
):
from torchvision.transforms import Compose
from densetorch.data import (
Pad,
RandomCrop,
RandomMirror,
ResizeAndScale,
ToTensor,
Normalise,
densetorch2torchvision,
)
if dataset_type == "densetorch":
wrapper = Compose
elif dataset_type == "torchvision":
wrapper = densetorch2torchvision
else:
raise ValueError(f"Unknown dataset type: {dataset_type}")
common_transformations = [
Normalise(scale=img_scale, mean=img_mean, std=img_std),
ToTensor(),
]
train_transforms = []
for stage in range(num_stages):
train_transforms.append(
wrapper(
[
ResizeAndScale(
shorter_side[stage], low_scale[stage], high_scale[stage]
),
Pad(crop_size[stage], img_mean, ignore_label),
RandomMirror(),
RandomCrop(crop_size[stage]),
]
+ common_transformations
)
)
val_transforms = wrapper(common_transformations)
return train_transforms, val_transforms
def get_transforms(
crop_size,
shorter_side,
low_scale,
high_scale,
img_mean,
img_std,
img_scale,
ignore_label,
num_stages,
augmentations_type,
dataset_type,
):
"""
Args:
crop_size (int) : square crop to apply during the training.
shorter_side (int) : parameter of the shorter_side resize transformation.
low_scale (float) : lowest scale ratio for augmentations.
high_scale (float) : highest scale ratio for augmentations.
img_mean (list of float) : image mean.
img_std (list of float) : image standard deviation
img_scale (list of float) : image scale.
ignore_label (int) : label to pad segmentation masks with.
num_stages (int): how many train_transforms to create.
augmentations_type (str): whether to use densetorch augmentations or albumentations.
dataset_type (str): whether to use densetorch or torchvision dataset;
needed to correctly wrap transformations.
Returns:
train_transforms, val_transforms
"""
if augmentations_type == "densetorch":
func = densetorch_transforms
elif augmentations_type == "albumentations":
func = albumentations_transforms
else:
raise ValueError(f"Unknown augmentations type {augmentations_type}")
return func(
crop_size=crop_size,
shorter_side=shorter_side,
low_scale=low_scale,
high_scale=high_scale,
img_mean=img_mean,
img_std=img_std,
img_scale=img_scale,
ignore_label=ignore_label,
num_stages=num_stages,
dataset_type=dataset_type,
)
def densetorch_dataset(
train_dir,
val_dir,
train_list_path,
val_list_path,
train_transforms,
val_transforms,
masks_names,
stage_names,
train_download,
val_download,
):
from densetorch.data import MMDataset as Dataset
def line_to_paths_fn(x):
rgb, segm = x.decode("utf-8").strip("\n").split("\t")[:2]
return [rgb, segm]
train_sets = [
Dataset(
data_file=train_list_path[i],
data_dir=train_dir[i],
line_to_paths_fn=line_to_paths_fn,
masks_names=masks_names,
transform=train_transforms[i],
)
for i in range(len(train_transforms))
]
val_set = Dataset(
data_file=val_list_path,
data_dir=val_dir,
line_to_paths_fn=line_to_paths_fn,
masks_names=masks_names,
transform=val_transforms,
)
return train_sets, val_set
def torchvision_dataset(
train_dir,
val_dir,
train_list_path,
val_list_path,
train_transforms,
val_transforms,
masks_names,
stage_names,
train_download,
val_download,
):
from torchvision.datasets.voc import VOCSegmentation
from torchvision.datasets import SBDataset
from functools import partial
train_sets = []
for i, stage in enumerate(stage_names):
if stage.lower() == "voc":
Dataset = partial(VOCSegmentation, image_set="train", year="2012",)
elif stage.lower() == "sbd":
Dataset = partial(SBDataset, mode="segmentation", image_set="train_noval")
train_sets.append(
Dataset(
root=train_dir[i],
transforms=train_transforms[i],
download=train_download[i],
)
)
val_set = VOCSegmentation(
root=val_dir,
image_set="val",
year="2012",
download=val_download,
transforms=val_transforms,
)
return train_sets, val_set
def get_datasets(
train_dir,
val_dir,
train_list_path,
val_list_path,
train_transforms,
val_transforms,
masks_names,
dataset_type,
stage_names,
train_download,
val_download,
):
if dataset_type == "densetorch":
func = densetorch_dataset
elif dataset_type == "torchvision":
func = torchvision_dataset
else:
raise ValueError(f"Unknown dataset type {dataset_type}")
return func(
train_dir,
val_dir,
train_list_path,
val_list_path,
train_transforms,
val_transforms,
masks_names,
stage_names,
train_download,
val_download,
)