-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdataset.py
491 lines (365 loc) · 15.6 KB
/
dataset.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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
import torch
import torch.utils.data as data
from time import time
import os, math, random, re
from os.path import *
import numpy as np
from glob import glob
from scipy import ndimage
import cv2
from cv2 import imread
import flow_transform
class StaticRandomCrop(object):
def __init__(self, image_size, crop_size):
self.th, self.tw = crop_size
h, w = image_size
self.h1 = random.randint(0, h - self.th)
self.w1 = random.randint(0, w - self.tw)
def __call__(self, img):
return img[self.h1:(self.h1+self.th), self.w1:(self.w1+self.tw),:]
class StaticCenterCrop(object):
def __init__(self, image_size, crop_size):
self.th, self.tw = crop_size
self.h, self.w = image_size
def __call__(self, img):
return img[(self.h-self.th)//2:(self.h+self.th)//2, (self.w-self.tw)//2:(self.w+self.tw)//2,:]
class FlyingChairs(data.Dataset):
def __init__(self, is_augment=False, root = '/path/to/FlyingChairs_release/data'):
self.augmentation = flow_transform.Compose([
flow_transform.RandomAffineTransformation(0.9, 2.0, 0.03, 12, 5),
flow_transform.RandomConstraintCrop((256, 448), (300, 500)),
flow_transform.RandomVerticalFlip(),
flow_transform.RandomHorizontalFlip(),
# flow_transform.ContrastAdjust(0.8, 1.4),
# flow_transform.GammaAdjust(0.7, 1.5),
# flow_transform.BrightnessAdjust(0, 0.2),
# flow_transform.SaturationAdjust(0.5, 2),
# flow_transform.HueAdjust(-0.2, 0.2)
])
self.is_augment = is_augment
images = sorted(glob(join(root, '*.ppm')))
self.flow_list = sorted(glob(join(root, '*.flo')))
assert (len(images)//2 == len(self.flow_list))
self.image_list = []
for i in range(len(self.flow_list)):
im1 = images[i*2]
im2 = images[i*2 + 1]
self.image_list += [ [ im1, im2 ] ]
assert len(self.image_list) == len(self.flow_list)
self.size = len(self.image_list)
self.frame_size = read_gen(self.image_list[0][0]).shape
def __getitem__(self, index):
index = index % self.size
img1 = read_gen(self.image_list[index][0])
img2 = read_gen(self.image_list[index][1])
# add fog
atmosphere = np.exp(-np.random.uniform(1,3))
scatter = np.random.uniform(50,150)
img1 = img1 * atmosphere + scatter * (1 - atmosphere)
img2 = img2 * atmosphere + scatter * (1 - atmosphere)
flow = readFlow(self.flow_list[index])
images = [img1, img2]
if self.is_augment:
images, flow = self.augmentation(images, flow)
images[0] = np.array(images[0])
images[1] = np.array(images[1])
else:
image_size = np.array(images[0].shape[:2])
crop_size = (image_size // 64) * 64
cropper = StaticCenterCrop(image_size, crop_size)
images = list(map(cropper, images))
flow = cropper(flow)
assert (images[0].shape[:2] == images[1].shape[:2])
images = np.array(images).transpose(3,0,1,2)
flow = flow.transpose(2,0,1)
images = torch.from_numpy(images.astype(np.float32))
flow = torch.from_numpy(flow.astype(np.float32))
return [images], [flow]
def __len__(self):
return self.size
class FlyingThings(data.Dataset):
def __init__(self, is_augment=False, root = '/path/to/flyingthings3d', dstype = 'frames_cleanpass'):
self.augmentation = flow_transform.Compose([
flow_transform.RandomAffineTransformation(0.9, 1.5, 0.03, 12, 5),
flow_transform.RandomConstraintCrop((256, 448), (300, 500)),
flow_transform.RandomVerticalFlip(),
flow_transform.RandomHorizontalFlip()
# flow_transform.ContrastAdjust(0.8, 1.4),
# flow_transform.GammaAdjust(0.7, 1.5),
# flow_transform.BrightnessAdjust(0, 0.2),
# flow_transform.SaturationAdjust(0.5, 2),
# flow_transform.HueAdjust(-0.2, 0.2)
])
self.is_augment = is_augment
image_dirs = sorted(glob(join(root, dstype, 'TEST/*/*')))
image_dirs = sorted([join(f, 'left') for f in image_dirs] + [join(f, 'right') for f in image_dirs])
flow_dirs = sorted(glob(join(root, 'optical_flow/TEST/*/*')))
flow_dirs = sorted([join(f, 'into_future/left') for f in flow_dirs] + [join(f, 'into_future/right') for f in flow_dirs])
depth_dirs = sorted(glob(join(root, 'disparity/TEST/*/*')))
depth_dirs = sorted([join(f, 'left') for f in depth_dirs] + [join(f, 'right') for f in depth_dirs])
self.root_len = len(root) + len(dstype) + 2
assert len(image_dirs) == len(flow_dirs) == len(depth_dirs)
self.image_list = []
self.flow_list = []
self.depth_list = []
self.ex_list = []
ex_dirs = open(join(root, 'all_unused_files.txt'), 'r').readlines()
for ex_num in range(len(ex_dirs)):
self.ex_list += [ex_dirs[ex_num][:-1]]
for idir, fdir, ddir in zip(image_dirs, flow_dirs, depth_dirs):
images = sorted(glob(join(idir, '*.png')))
flows = sorted(glob(join(fdir, '*.pfm')))
depths = sorted(glob(join(ddir, '*.pfm')))
for i in range(len(flows)-1):
if images[i][self.root_len:] in self.ex_list or images[i+1][self.root_len:] in self.ex_list:
print('Exclusion Detected\n')
continue
self.image_list += [[images[i], images[i+1]]]
self.depth_list += [[depths[i], depths[i+1]]]
self.flow_list += [flows[i]]
assert len(self.image_list) == len(self.flow_list) == len(self.depth_list)
self.size = len(self.image_list)
self.frame_size = read_gen(self.image_list[0][0]).shape
def __getitem__(self, index):
index = index % self.size
img1 = read_gen(self.image_list[index][0])
img2 = read_gen(self.image_list[index][1])
dept1, _ = readPFM(self.depth_list[index][0])
dept1 = dept1[:,:,np.newaxis]
dept2, _ = readPFM(self.depth_list[index][1])
dept2 = dept2[:,:,np.newaxis]
dept1 = 1 / (dept1 + 0.001)
dept2 = 1 / (dept2 + 0.001)
# add fog
b = np.random.uniform(1, 3)
scatter = np.random.uniform(50,150)
atmosphere1 = np.exp(-b * dept1)
atmosphere2 = np.exp(-b * dept2)
img1 = np.clip(img1 * atmosphere1 + scatter * (1 - atmosphere1), 0, 255)
img2 = np.clip(img2 * atmosphere2 + scatter * (1 - atmosphere2), 0, 255)
flow, _ = readPFM(self.flow_list[index])
flow = flow[:,:,0:2]
images = [img1, img2]
if self.is_augment:
images, flow = self.augmentation(images, flow)
images[0] = np.array(images[0])
images[1] = np.array(images[1])
else:
image_size = np.array(images[0].shape[:2])
crop_size = (image_size // 64) * 64
cropper = StaticCenterCrop(image_size, crop_size)
images = list(map(cropper, images))
flow = cropper(flow)
assert (images[0].shape[:2] == images[1].shape[:2])
images = np.array(images).transpose(3,0,1,2)
flow = flow.transpose(2,0,1)
images = torch.from_numpy(images.astype(np.float32))
flow = torch.from_numpy(flow.astype(np.float32))
return [images], [flow]
def __len__(self):
return self.size
class VirtualKITTI(data.Dataset):
def __init__(self, root = ''):
flow_root = join(root, 'vkitti_1.3.1_flowgt')
image_root = join(root, 'vkitti_1.3.1_rgb')
file_list = sorted(glob(join(flow_root, '*/*.png')))
self.flow_list = []
self.image_list = []
for file in file_list:
fbase = file[-14:]
fnum = int(file[-9:-4])
img1 = join(image_root, file[-14:])
img2 = join(image_root, file[-14:-9]+"%05d"%(fnum+1) + '.png')
if not isfile(img1) or not isfile(img2) or not isfile(file):
continue
self.image_list += [[img1, img2]]
self.flow_list += [file]
self.size = len(self.image_list)
self.frame_size = read_gen(self.image_list[0][0]).shape
assert (len(self.image_list) == len(self.flow_list))
def __getitem__(self, index):
index = index % self.size
img1 = read_gen(self.image_list[index][0])
img2 = read_gen(self.image_list[index][1])
flow = read_vkitti_png_flow(self.flow_list[index])
images = [img1, img2]
assert (images[0].shape[:2] == images[1].shape[:2])
image_size = np.array(images[0].shape[:2])
crop_size = (image_size // 64) * 64
cropper = StaticCenterCrop(image_size, crop_size)
images = list(map(cropper, images))
flow = cropper(flow)
images = np.array(images).transpose(3,0,1,2)
flow = flow.transpose(2,0,1)
images = torch.from_numpy(images.astype(np.float32))
flow = torch.from_numpy(flow.astype(np.float32))
return [images], [flow]
def __len__(self):
return self.size
class FoggyZurich(data.Dataset):
def __init__(self, is_cropped = True, root = '', replicates = 1):
self.is_cropped = is_cropped
self.crop_size = [1024, 1024]
self.replicates = replicates
file_list = sorted(glob(join(root, '*/*.png')))
self.image_list = []
for file in file_list:
fnum = int(file[-10:-4])
img1 = file
img2 = file[:-10]+"%06d"%(fnum+1) + '.png'
if not isfile(img1) or not isfile(img2) or not isfile(file):
continue
self.image_list += [[img1, img2]]
self.size = len(self.image_list)
self.frame_size = read_gen(self.image_list[0][0]).shape
def __getitem__(self, index):
index = index % self.size
img1 = read_gen(self.image_list[index][0])
img2 = read_gen(self.image_list[index][1])
images = [img1, img2]
assert (images[0].shape[:2] == images[1].shape[:2])
image_size = images[0].shape[:2]
if self.is_cropped:
cropper = StaticRandomCrop(image_size, self.crop_size)
images = list(map(cropper, images))
images = np.array(images).transpose(3,0,1,2)
images = torch.from_numpy(images.astype(np.float32))
return [images]
def __len__(self):
return self.size * self.replicates
class MpiSintel(data.Dataset):
def __init__(self, root = '', dstype = 'clean'):
flow_root = join(root, 'flow')
image_root = join(root, dstype)
file_list = sorted(glob(join(flow_root, '*/*.flo')))
self.flow_list = []
self.image_list = []
for file in file_list:
if 'test' in file:
# print file
continue
fbase = file[len(flow_root)+1:]
fprefix = fbase[:-8]
fnum = int(fbase[-8:-4])
img1 = join(image_root, fprefix + "%04d"%(fnum+0) + '.png')
img2 = join(image_root, fprefix + "%04d"%(fnum+1) + '.png')
if not isfile(img1) or not isfile(img2) or not isfile(file):
continue
self.image_list += [[img1, img2]]
self.flow_list += [file]
self.size = len(self.image_list)
assert (len(self.image_list) == len(self.flow_list))
def __getitem__(self, index):
index = index % self.size
img1 = read_gen(self.image_list[index][0])
img2 = read_gen(self.image_list[index][1])
flow = readFlow(self.flow_list[index])
images = [img1, img2]
image_size = np.array(images[0].shape[:2])
crop_size = (image_size // 64) * 64
cropper = StaticCenterCrop(image_size, crop_size)
images = list(map(cropper, images))
flow = cropper(flow)
images = np.array(images).transpose(3,0,1,2)
flow = flow.transpose(2,0,1)
images = torch.from_numpy(images.astype(np.float32))
flow = torch.from_numpy(flow.astype(np.float32))
return [images], [flow]
def __len__(self):
return self.size
def read_vkitti_png_flow(flow_fn):
bgr = imread(flow_fn, cv2.IMREAD_ANYCOLOR | cv2.IMREAD_ANYDEPTH)
h, w, _c = bgr.shape
assert bgr.dtype == np.uint16 and _c == 3
# b == invalid flow flag: == 0 for sky or other invalid flow
invalid = bgr[..., 0] == 0
# g,r == flow_y,x normalized by height,width and scaled to [0;2**16 - 1]
out_flow = 2.0 / (2**16 - 1.0) * bgr[..., 2:0:-1].astype('f4') - 1
out_flow[..., 0] *= w - 1
out_flow[..., 1] *= h - 1
out_flow[invalid] = 0 # or another value (e.g., np.nan)
return out_flow
def read_gen(file_name):
ext = splitext(file_name)[-1]
if ext == '.png' or ext == '.jpeg' or ext == '.ppm' or ext == '.jpg':
im = imread(file_name)
if im.shape[2] > 3:
return im[:,:,:3]
else:
return im
# elif ext == '.bin' or ext == '.raw':
# return np.load(file_name)
# elif ext == '.flo':
# return flow_utils.readFlow(file_name).astype(np.float32)
return []
def readFlow(fn):
""" Read .flo file in Middlebury format"""
# Code adapted from:
# http://stackoverflow.com/questions/28013200/reading-middlebury-flow-files-with-python-bytes-array-numpy
# WARNING: this will work on little-endian architectures (eg Intel x86) only!
# print 'fn = %s'%(fn)
with open(fn, 'rb') as f:
magic = np.fromfile(f, np.float32, count=1)
if 202021.25 != magic:
print('Magic number incorrect. Invalid .flo file')
return None
else:
w = np.fromfile(f, np.int32, count=1)
h = np.fromfile(f, np.int32, count=1)
# print 'Reading %d x %d flo file\n' % (w, h)
data = np.fromfile(f, np.float32, count=2*int(w)*int(h))
# Reshape data into 3D array (columns, rows, bands)
# The reshape here is for visualization, the original code is (w,h,2)
return np.resize(data, (int(h), int(w), 2))
def writeFlow(filename,uv,v=None):
nBands = 2
if v is None:
assert(uv.ndim == 3)
assert(uv.shape[2] == 2)
u = uv[:,:,0]
v = uv[:,:,1]
else:
u = uv
assert(u.shape == v.shape)
height,width = u.shape
f = open(filename,'wb')
# write the header
f.write(TAG_CHAR)
np.array(width).astype(np.int32).tofile(f)
np.array(height).astype(np.int32).tofile(f)
# arrange into matrix form
tmp = np.zeros((height, width*nBands))
tmp[:,np.arange(width)*2] = u
tmp[:,np.arange(width)*2 + 1] = v
tmp.astype(np.float32).tofile(f)
f.close()
def readPFM(file):
file = open(file, 'rb')
color = None
width = None
height = None
scale = None
endian = None
header = file.readline().rstrip()
if header.decode("ascii") == 'PF':
color = True
elif header.decode("ascii") == 'Pf':
color = False
else:
raise Exception('Not a PFM file.')
dim_match = re.match(r'^(\d+)\s(\d+)\s$', file.readline().decode("ascii"))
if dim_match:
width, height = list(map(int, dim_match.groups()))
else:
raise Exception('Malformed PFM header.')
scale = float(file.readline().decode("ascii").rstrip())
if scale < 0:
endian = '<'
scale = -scale
else:
endian = '>'
data = np.fromfile(file, endian + 'f')
shape = (height, width, 3) if color else (height, width)
data = np.reshape(data, shape)
data = np.flipud(data)
return data, scale