-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdatasets.py
445 lines (380 loc) · 14.8 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
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
from pathlib import Path
import yaml
import json
from torch.utils.data import DataLoader, Dataset
from imageio import imread
from torchvision import transforms
import numpy as np
from .transforms import get_transforms
from PIL import Image
from addict import Dict
from utils import get_normalized_depth
IMG_EXTENSIONS = set(
[".jpg", ".JPG", ".jpeg", ".JPEG", ".png", ".PNG", ".ppm", ".PPM", ".bmp", ".BMP"]
)
class SimDataset(Dataset):
def __init__(self, opts, transform=None, no_check=False):
isTrain = opts.model.is_train
if isTrain:
file_list_path = Path(opts.data.files.train)
else:
file_list_path = Path(opts.data.files.val)
if file_list_path.suffix == ".json":
self.samples_paths = self.json_load(file_list_path)
elif file_list_path.suffix in {".yaml", ".yml"}:
self.samples_paths = self.yaml_load(file_list_path)
else:
raise ValueError("Unknown file list type in {}".format(file_list_path))
self.file_list_path = str(file_list_path)
if not no_check:
self.check_samples()
self.transform = transform
self.opts = opts
def check_samples(self):
"""Checks that every file listed in samples_paths actually
exist on the file-system
"""
l, p = (len(self.samples_paths), self.file_list_path)
print(f"Checking {l} samples in {p}...", end="", flush=True)
for s in self.samples_paths:
for k, v in s.items():
assert Path(v).exists(), f"{k} {v} does not exist"
print(" ok.")
def json_load(self, file_path):
with open(file_path, "r") as f:
return json.load(f)
def yaml_load(self, file_path):
with open(file_path, "r") as f:
return yaml.safe_load(f)
def __getitem__(self, i):
"""Return an item in the dataset with fields:
{
data: transform({pil_image_loader(path, task)}) ,
paths: [{task: path}],
mode: [train|val]
}
Args:
i (int): index of item to retrieve
Returns:
dict: dataset item where tensors of data are in item["data"] which is a dict
{task: tensor}
"""
paths = self.samples_paths[i]
if self.transform:
return Dict(
{
"data": self.transform(
{
task: pil_image_loader(path, task)
for task, path in paths.items()
}
),
"paths": paths,
}
)
return Dict(
{
"data": {
task: pil_image_loader(path, task) for task, path in paths.items()
},
"paths": paths,
}
)
def __len__(self):
return len(self.samples_paths)
def pil_image_loader(path, task):
if Path(path).suffix == ".npy":
arr = np.load(path).astype(np.uint8)
elif is_image_file(path):
arr = imread(path).astype(np.uint8)
else:
raise ValueError("Unknown data type {}".format(path))
if task == "m" or task == "rm":
# Check if >1 channel:
if len(arr.shape) > 2 and arr.shape[-1] > 1:
mask_thresh = (np.max(arr) - np.min(arr)) / 2.0
arr = np.squeeze((arr > mask_thresh).astype(np.float)[:, :, 0])
# if task == "s":
# arr = decode_segmap(arr)
# assert len(arr.shape) == 3, (path, task, arr.shape)
return Image.fromarray(arr)
def is_image_file(filename):
"""Check that a file's name points to a known image format
"""
return Path(filename).suffix in IMG_EXTENSIONS
class RealSimDataset(Dataset):
def __init__(self, opts, transform=None, no_check=False):
isTrain = opts.model.is_train
if isTrain:
file_list_path = Path(opts.data.files.train)
real_file_list_path = Path(opts.data.real_files.train)
else:
file_list_path = Path(opts.data.files.val)
real_file_list_path = Path(opts.data.real_files.val)
if file_list_path.suffix == ".json":
self.samples_paths = self.json_load(file_list_path)
self.real_samples_paths = self.json_load(real_file_list_path)
elif file_list_path.suffix in {".yaml", ".yml"}:
self.samples_paths = self.yaml_load(file_list_path)
self.real_samples_paths = self.yaml_load(real_file_list_path)
else:
raise ValueError("Unknown file list type in {}".format(file_list_path))
self.file_list_path = str(file_list_path)
self.real_file_list_path = str(real_file_list_path)
if not no_check:
self.check_samples()
self.transform = transform
self.opts = opts
def check_samples(self):
"""Checks that every file listed in samples_paths actually
exist on the file-system
"""
l, p = (len(self.samples_paths), self.file_list_path)
print(f"Checking {l} samples in {p}...", end="", flush=True)
for s in self.samples_paths:
for k, v in s.items():
assert Path(v).exists(), f"{k} {v} does not exist"
print(" ok.")
l, p = (len(self.real_samples_paths), self.real_file_list_path)
print(f"Checking {l} samples in {p}...", end="", flush=True)
for s in self.real_samples_paths:
for k, v in s.items():
assert Path(v).exists(), f"{k} {v} does not exist"
print(" ok.")
def json_load(self, file_path):
with open(file_path, "r") as f:
return json.load(f)
def yaml_load(self, file_path):
with open(file_path, "r") as f:
return yaml.safe_load(f)
def __getitem__(self, i):
"""Return an item in the dataset with fields:
{
data: transform({pil_image_loader(path, task)}),
paths: [{task: path}],
mode: [train|val]
}
Args:
i (int): index of item to retrieve
Returns:
dict: dataset item where tensors of data are in item["data"] which is a dict
{task: tensor}
"""
real_i = i % len(self.real_samples_paths) - 1
paths = self.samples_paths[i]
paths["rx"] = self.real_samples_paths[real_i]["x"]
paths["rm"] = self.real_samples_paths[real_i]["m"]
if self.transform:
return Dict(
{
"data": self.transform(
{
task: pil_image_loader(path, task)
for task, path in paths.items()
}
),
"paths": paths,
}
)
return Dict(
{
"data": {
task: pil_image_loader(path, task) for task, path in paths.items()
},
"paths": paths,
}
)
def __len__(self):
return len(self.samples_paths)
def get_loader(opts, real=True, depth=True, no_check=False):
if real:
if depth:
return DataLoader(
RealSimDepthDataset(
opts,
transform=transforms.Compose(get_transforms(Dict(opts))),
no_check=no_check,
),
batch_size=opts.data.loaders.get("batch_size", 4),
shuffle=True,
num_workers=opts.data.loaders.get("num_workers", 8),
)
else:
return DataLoader(
RealSimDataset(
opts,
transform=transforms.Compose(get_transforms(Dict(opts))),
no_check=no_check,
),
batch_size=opts.data.loaders.get("batch_size", 4),
shuffle=True,
num_workers=opts.data.loaders.get("num_workers", 8),
)
else:
if depth:
return DataLoader(
SimDepthDataset(
opts,
transform=transforms.Compose(get_transforms(Dict(opts))),
no_check=no_check,
),
batch_size=opts.data.loaders.get("batch_size", 4),
shuffle=True,
num_workers=opts.data.loaders.get("num_workers", 8),
)
else:
return DataLoader(
SimDataset(
opts,
transform=transforms.Compose(get_transforms(Dict(opts))),
no_check=no_check,
),
batch_size=opts.data.loaders.get("batch_size", 4),
shuffle=True,
num_workers=opts.data.loaders.get("num_workers", 8),
)
class RealSimDepthDataset(Dataset):
def __init__(self, opts, transform=None, no_check=False):
isTrain = opts.model.is_train
if isTrain:
file_list_path = Path(opts.data.files.train)
real_file_list_path = Path(opts.data.real_files.train)
else:
file_list_path = Path(opts.data.files.val)
real_file_list_path = Path(opts.data.real_files.val)
if file_list_path.suffix == ".json":
self.samples_paths = self.json_load(file_list_path)
self.real_samples_paths = self.json_load(real_file_list_path)
elif file_list_path.suffix in {".yaml", ".yml"}:
self.samples_paths = self.yaml_load(file_list_path)
self.real_samples_paths = self.yaml_load(real_file_list_path)
else:
raise ValueError("Unknown file list type in {}".format(file_list_path))
if not no_check:
self.check_samples()
self.file_list_path = str(file_list_path)
self.real_file_list_path = str(real_file_list_path)
self.transform = transform
self.opts = opts
def check_samples(self):
"""Checks that every file listed in samples_paths actually
exist on the file-system
"""
for s in self.samples_paths:
for k, v in s.items():
assert Path(v).exists(), f"{k} {v} does not exist"
for s in self.real_samples_paths:
for k, v in s.items():
assert Path(v).exists(), f"{k} {v} does not exist"
def json_load(self, file_path):
with open(file_path, "r") as f:
return json.load(f)
def yaml_load(self, file_path):
with open(file_path, "r") as f:
return yaml.safe_load(f)
def __getitem__(self, i):
"""Return an item in the dataset with fields:
{
data: transform({pil_image_loader(path, task)}),
paths: [{task: path}],
mode: [train|val]
}
Args:
i (int): index of item to retrieve
Returns:
dict: dataset item where tensors of data are in item["data"] which is a dict
{task: tensor}
"""
real_i = i % len(self.real_samples_paths) - 1
paths = self.samples_paths[i]
paths["rx"] = self.real_samples_paths[real_i]["x"]
paths["rm"] = self.real_samples_paths[real_i]["m"]
paths["rd"] = self.real_samples_paths[real_i]["d"]
if self.transform:
# first perform transform on input images and then convert depth image
# to depth array
datadict = self.transform(
{task: pil_image_loader(path, task) for task, path in paths.items()}
)
datadict["d"] = get_normalized_depth(
datadict["d"], mode=self.opts.data.depth.sim_mode
)
datadict["rd"] = get_normalized_depth(
datadict["rd"], mode=self.opts.data.depth.real_mode
)
return Dict({"data": datadict, "paths": paths})
datadict = self.transform(
{task: pil_image_loader(path, task) for task, path in paths.items()}
)
datadict["d"] = get_normalized_depth(
np.array(datadict["d"]), mode=self.opts.depth.sim_mode
)
datadict["rd"] = get_normalized_depth(
np.array(datadict["rd"]), mode=self.opts.depth.real_mode
)
return Dict({"data": datadict, "paths": paths})
def __len__(self):
return len(self.samples_paths)
class SimDepthDataset(Dataset):
def __init__(self, opts, transform=None, no_check=False):
isTrain = opts.model.is_train
if isTrain:
file_list_path = Path(opts.data.files.train)
else:
file_list_path = Path(opts.data.files.val)
if file_list_path.suffix == ".json":
self.samples_paths = self.json_load(file_list_path)
elif file_list_path.suffix in {".yaml", ".yml"}:
self.samples_paths = self.yaml_load(file_list_path)
else:
raise ValueError("Unknown file list type in {}".format(file_list_path))
if not no_check:
self.check_samples()
self.file_list_path = str(file_list_path)
self.transform = transform
self.opts = opts
def check_samples(self):
"""Checks that every file listed in samples_paths actually
exist on the file-system
"""
for s in self.samples_paths:
for k, v in s.items():
assert Path(v).exists(), f"{k} {v} does not exist"
def json_load(self, file_path):
with open(file_path, "r") as f:
return json.load(f)
def yaml_load(self, file_path):
with open(file_path, "r") as f:
return yaml.safe_load(f)
def __getitem__(self, i):
"""Return an item in the dataset with fields:
{
data: transform({pil_image_loader(path, task)}),
paths: [{task: path}],
mode: [train|val]
}
Args:
i (int): index of item to retrieve
Returns:
dict: dataset item where tensors of data are in item["data"] which is a dict
{task: tensor}
"""
paths = self.samples_paths[i]
if self.transform:
# first perform transform on input images and then convert depth image to depth array
datadict = self.transform(
{task: pil_image_loader(path, task) for task, path in paths.items()}
)
datadict["d"] = get_normalized_depth(
np.array(datadict["d"]), mode=self.opts.depth.sim_mode
)
return Dict({"data": datadict, "paths": paths})
datadict = self.transform(
{task: pil_image_loader(path, task) for task, path in paths.items()}
)
datadict["d"] = get_normalized_depth(
np.array(datadict["d"]), mode=self.opts.depth.sim_mode
)
return Dict({"data": datadict, "paths": paths})
def __len__(self):
return len(self.samples_paths)