forked from avinashpaliwal/Super-SloMo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataloader.py
537 lines (437 loc) · 15.6 KB
/
dataloader.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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
import torch.utils.data as data
from PIL import Image
import os
import os.path
import random
def _make_dataset(dir):
"""
Creates a 2D list of all the frames in N clips containing
M frames each.
2D List Structure:
[[frame00, frame01,...frameM] <-- clip0
[frame00, frame01,...frameM] <-- clip0
:
[frame00, frame01,...frameM]] <-- clipN
Parameters
----------
dir : string
root directory containing clips.
Returns
-------
list
2D list described above.
"""
framesPath = []
# Find and loop over all the clips in root `dir`.
for index, folder in enumerate(os.listdir(dir)):
clipsFolderPath = os.path.join(dir, folder)
# Skip items which are not folders.
if not (os.path.isdir(clipsFolderPath)):
continue
framesPath.append([])
# Find and loop over all the frames inside the clip.
for image in sorted(os.listdir(clipsFolderPath)):
# Add path to list.
framesPath[index].append(os.path.join(clipsFolderPath, image))
return framesPath
def _make_video_dataset(dir):
"""
Creates a 1D list of all the frames.
1D List Structure:
[frame0, frame1,...frameN]
Parameters
----------
dir : string
root directory containing frames.
Returns
-------
list
1D list described above.
"""
framesPath = []
# Find and loop over all the frames in root `dir`.
for image in sorted(os.listdir(dir)):
# Add path to list.
framesPath.append(os.path.join(dir, image))
return framesPath
def _pil_loader(path, cropArea=None, resizeDim=None, frameFlip=0):
"""
Opens image at `path` using pil and applies data augmentation.
Parameters
----------
path : string
path of the image.
cropArea : tuple, optional
coordinates for cropping image. Default: None
resizeDim : tuple, optional
dimensions for resizing image. Default: None
frameFlip : int, optional
Non zero to flip image horizontally. Default: 0
Returns
-------
list
2D list described above.
"""
# open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
with open(path, 'rb') as f:
img = Image.open(f)
# Resize image if specified.
resized_img = img.resize(resizeDim, Image.ANTIALIAS) if (resizeDim != None) else img
# Crop image if crop area specified.
cropped_img = img.crop(cropArea) if (cropArea != None) else resized_img
# Flip image horizontally if specified.
flipped_img = cropped_img.transpose(Image.FLIP_LEFT_RIGHT) if frameFlip else cropped_img
return flipped_img.convert('RGB')
class SuperSloMo(data.Dataset):
"""
A dataloader for loading N samples arranged in this way:
|-- clip0
|-- frame00
|-- frame01
:
|-- frame11
|-- frame12
|-- clip1
|-- frame00
|-- frame01
:
|-- frame11
|-- frame12
:
:
|-- clipN
|-- frame00
|-- frame01
:
|-- frame11
|-- frame12
...
Attributes
----------
framesPath : list
List of frames' path in the dataset.
Methods
-------
__getitem__(index)
Returns the sample corresponding to `index` from dataset.
__len__()
Returns the size of dataset. Invoked as len(datasetObj).
__repr__()
Returns printable representation of the dataset object.
"""
def __init__(self, root, transform=None, dim=(640, 360), randomCropSize=(352, 352), train=True):
"""
Parameters
----------
root : string
Root directory path.
transform : callable, optional
A function/transform that takes in
a sample and returns a transformed version.
E.g, ``transforms.RandomCrop`` for images.
dim : tuple, optional
Dimensions of images in dataset. Default: (640, 360)
randomCropSize : tuple, optional
Dimensions of random crop to be applied. Default: (352, 352)
train : boolean, optional
Specifies if the dataset is for training or testing/validation.
`True` returns samples with data augmentation like random
flipping, random cropping, etc. while `False` returns the
samples without randomization. Default: True
"""
# Populate the list with image paths for all the
# frame in `root`.
framesPath = _make_dataset(root)
# Raise error if no images found in root.
if len(framesPath) == 0:
raise(RuntimeError("Found 0 files in subfolders of: " + root + "\n"))
self.randomCropSize = randomCropSize
self.cropX0 = dim[0] - randomCropSize[0]
self.cropY0 = dim[1] - randomCropSize[1]
self.root = root
self.transform = transform
self.train = train
self.framesPath = framesPath
def __getitem__(self, index):
"""
Returns the sample corresponding to `index` from dataset.
The sample consists of two reference frames - I0 and I1 -
and a random frame chosen from the 7 intermediate frames
available between I0 and I1 along with it's relative index.
Parameters
----------
index : int
Index
Returns
-------
tuple
(sample, returnIndex) where sample is
[I0, intermediate_frame, I1] and returnIndex is
the position of `random_intermediate_frame`.
e.g.- `returnIndex` of frame next to I0 would be 0 and
frame before I1 would be 6.
"""
sample = []
if (self.train):
### Data Augmentation ###
# To select random 9 frames from 12 frames in a clip
firstFrame = random.randint(0, 3)
# Apply random crop on the 9 input frames
cropX = random.randint(0, self.cropX0)
cropY = random.randint(0, self.cropY0)
cropArea = (cropX, cropY, cropX + self.randomCropSize[0], cropY + self.randomCropSize[1])
# Random reverse frame
#frameRange = range(firstFrame, firstFrame + 9) if (random.randint(0, 1)) else range(firstFrame + 8, firstFrame - 1, -1)
IFrameIndex = random.randint(firstFrame + 1, firstFrame + 7)
if (random.randint(0, 1)):
frameRange = [firstFrame, IFrameIndex, firstFrame + 8]
returnIndex = IFrameIndex - firstFrame - 1
else:
frameRange = [firstFrame + 8, IFrameIndex, firstFrame]
returnIndex = firstFrame - IFrameIndex + 7
# Random flip frame
randomFrameFlip = random.randint(0, 1)
else:
# Fixed settings to return same samples every epoch.
# For validation/test sets.
firstFrame = 0
cropArea = (0, 0, self.randomCropSize[0], self.randomCropSize[1])
IFrameIndex = ((index) % 7 + 1)
returnIndex = IFrameIndex - 1
frameRange = [0, IFrameIndex, 8]
randomFrameFlip = 0
# Loop over for all frames corresponding to the `index`.
for frameIndex in frameRange:
# Open image using pil and augment the image.
image = _pil_loader(self.framesPath[index][frameIndex], cropArea=cropArea, frameFlip=randomFrameFlip)
# Apply transformation if specified.
if self.transform is not None:
image = self.transform(image)
sample.append(image)
return sample, returnIndex
def __len__(self):
"""
Returns the size of dataset. Invoked as len(datasetObj).
Returns
-------
int
number of samples.
"""
return len(self.framesPath)
def __repr__(self):
"""
Returns printable representation of the dataset object.
Returns
-------
string
info.
"""
fmt_str = 'Dataset ' + self.__class__.__name__ + '\n'
fmt_str += ' Number of datapoints: {}\n'.format(self.__len__())
fmt_str += ' Root Location: {}\n'.format(self.root)
tmp = ' Transforms (if any): '
fmt_str += '{0}{1}\n'.format(tmp, self.transform.__repr__().replace('\n', '\n' + ' ' * len(tmp)))
return fmt_str
class UCI101Test(data.Dataset):
"""
A dataloader for loading N samples arranged in this way:
|-- clip0
|-- frame00
|-- frame01
|-- frame02
|-- clip1
|-- frame00
|-- frame01
|-- frame02
:
:
|-- clipN
|-- frame00
|-- frame01
|-- frame02
...
Attributes
----------
framesPath : list
List of frames' path in the dataset.
Methods
-------
__getitem__(index)
Returns the sample corresponding to `index` from dataset.
__len__()
Returns the size of dataset. Invoked as len(datasetObj).
__repr__()
Returns printable representation of the dataset object.
"""
def __init__(self, root, transform=None):
"""
Parameters
----------
root : string
Root directory path.
transform : callable, optional
A function/transform that takes in
a sample and returns a transformed version.
E.g, ``transforms.RandomCrop`` for images.
"""
# Populate the list with image paths for all the
# frame in `root`.
framesPath = _make_dataset(root)
# Raise error if no images found in root.
if len(framesPath) == 0:
raise(RuntimeError("Found 0 files in subfolders of: " + root + "\n"))
self.root = root
self.framesPath = framesPath
self.transform = transform
def __getitem__(self, index):
"""
Returns the sample corresponding to `index` from dataset.
The sample consists of two reference frames - I0 and I1 -
and a intermediate frame between I0 and I1.
Parameters
----------
index : int
Index
Returns
-------
tuple
(sample, returnIndex) where sample is
[I0, intermediate_frame, I1] and returnIndex is
the position of `intermediate_frame`.
The returnIndex is always 3 and is being returned
to maintain compatibility with the `SuperSloMo`
dataloader where 3 corresponds to the middle frame.
"""
sample = []
# Loop over for all frames corresponding to the `index`.
for framePath in self.framesPath[index]:
# Open image using pil.
image = _pil_loader(framePath)
# Apply transformation if specified.
if self.transform is not None:
image = self.transform(image)
sample.append(image)
return sample, 3
def __len__(self):
"""
Returns the size of dataset. Invoked as len(datasetObj).
Returns
-------
int
number of samples.
"""
return len(self.framesPath)
def __repr__(self):
"""
Returns printable representation of the dataset object.
Returns
-------
string
info.
"""
fmt_str = 'Dataset ' + self.__class__.__name__ + '\n'
fmt_str += ' Number of datapoints: {}\n'.format(self.__len__())
fmt_str += ' Root Location: {}\n'.format(self.root)
tmp = ' Transforms (if any): '
fmt_str += '{0}{1}\n'.format(tmp, self.transform.__repr__().replace('\n', '\n' + ' ' * len(tmp)))
return fmt_str
class Video(data.Dataset):
"""
A dataloader for loading all video frames in a folder:
|-- frame0
|-- frame1
:
:
|-- frameN
...
Attributes
----------
framesPath : list
List of frames' path in the dataset.
origDim : tuple
original dimensions of the video.
dim : tuple
resized dimensions of the video (for CNN).
Methods
-------
__getitem__(index)
Returns the sample corresponding to `index` from dataset.
__len__()
Returns the size of dataset. Invoked as len(datasetObj).
__repr__()
Returns printable representation of the dataset object.
"""
def __init__(self, root, transform=None):
"""
Parameters
----------
root : string
Root directory path.
transform : callable, optional
A function/transform that takes in
a sample and returns a transformed version.
E.g, ``transforms.RandomCrop`` for images.
"""
# Populate the list with image paths for all the
# frame in `root`.
framesPath = _make_video_dataset(root)
# Get dimensions of frames
frame = _pil_loader(framesPath[0])
self.origDim = frame.size
self.dim = int(self.origDim[0] / 32) * 32, int(self.origDim[1] / 32) * 32
# Raise error if no images found in root.
if len(framesPath) == 0:
raise(RuntimeError("Found 0 files in: " + root + "\n"))
self.root = root
self.framesPath = framesPath
self.transform = transform
def __getitem__(self, index):
"""
Returns the sample corresponding to `index` from dataset.
The sample consists of two reference frames - I0 and I1.
Parameters
----------
index : int
Index
Returns
-------
list
sample is [I0, I1] where I0 is the frame with index
`index` and I1 is the next frame.
"""
sample = []
# Loop over for all frames corresponding to the `index`.
for framePath in [self.framesPath[index], self.framesPath[index + 1]]:
# Open image using pil.
image = _pil_loader(framePath, resizeDim=self.dim)
# Apply transformation if specified.
if self.transform is not None:
image = self.transform(image)
sample.append(image)
return sample
def __len__(self):
"""
Returns the size of dataset. Invoked as len(datasetObj).
Returns
-------
int
number of samples.
"""
# Using `-1` so that dataloader accesses only upto
# frames [N-1, N] and not [N, N+1] which because frame
# N+1 doesn't exist.
return len(self.framesPath) - 1
def __repr__(self):
"""
Returns printable representation of the dataset object.
Returns
-------
string
info.
"""
fmt_str = 'Dataset ' + self.__class__.__name__ + '\n'
fmt_str += ' Number of datapoints: {}\n'.format(self.__len__())
fmt_str += ' Root Location: {}\n'.format(self.root)
tmp = ' Transforms (if any): '
fmt_str += '{0}{1}\n'.format(tmp, self.transform.__repr__().replace('\n', '\n' + ' ' * len(tmp)))
return fmt_str