forked from CSAILVision/GazeCapture
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathITrackerData.py
829 lines (715 loc) · 34.6 KB
/
ITrackerData.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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
import torch
import os
import os.path
import scipy.io as sio
import numpy as np
import math
from random import random, shuffle
# CPU data loader
from PIL import Image
import torchvision.transforms as transforms
from utility_functions.Utilities import centered_text
from torch.utils.data.dataloader import default_collate
try:
# GPU data loader
from nvidia.dali.pipeline import Pipeline
import nvidia.dali.ops as ops
import nvidia.dali.types as types
from nvidia.dali.plugin.pytorch import DALIGenericIterator
except ImportError:
# If running on a non-CUDA system, stub out Pipeline to prevent code crash
class Pipeline:
def __init__(self, *args):
return
# If running on a non-CUDA system, stub out DALIGenericIterator to prevent code crash
class DALIGenericIterator:
def __init__(self, *args):
return
def normalize_image_transform(image_size, split, jitter, color_space):
normalize_image = []
# Only for training
if split == 'train':
normalize_image.append(transforms.Resize(240))
if jitter:
normalize_image.append(transforms.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1))
normalize_image.append(transforms.RandomCrop(image_size))
# For training and Eval
normalize_image.append(transforms.Resize(image_size))
normalize_image.append(transforms.ToTensor())
if color_space == 'RGB':
normalize_image.append(transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])) # Well known ImageNet values
return transforms.Compose(normalize_image)
def resize_image_transform(image_size):
normalize_image = []
normalize_image.append(transforms.Resize(image_size))
normalize_image.append(transforms.ToTensor())
return transforms.Compose(normalize_image)
class ExternalSourcePipeline(Pipeline):
def __init__(self, data, batch_size, image_size, split, silent, num_threads, device_id, data_loader, color_space, shuffle=False):
super(ExternalSourcePipeline, self).__init__(batch_size,
num_threads,
device_id)
self.split = split
self.color_space = color_space
self.data_loader = data_loader
if shuffle:
data.shuffle()
self.sourceIterator = iter(data)
self.rowBatch = ops.ExternalSource()
self.imFaceBatch = ops.ExternalSource()
self.imEyeLBatch = ops.ExternalSource()
self.imEyeRBatch = ops.ExternalSource()
self.imFaceGridBatch = ops.ExternalSource()
self.gazeBatch = ops.ExternalSource()
self.indexBatch = ops.ExternalSource()
mean = None
std = None
if color_space == 'RGB':
output_type = types.RGB
mean=[0.485 * 255, 0.456 * 255, 0.406 * 255]
std=[0.229 * 255, 0.224 * 255, 0.225 * 255]
elif color_space == 'YCbCr':
output_type = types.YCbCr
elif color_space == 'L':
output_type = types.GRAY
elif color_space == 'BGR':
output_type = types.BGR
else:
print("Unsupported color_space:", color_space)
# Variation range for Saturation, Contrast, Brightness and Hue
self.dSaturation = ops.Uniform(range=[0.9, 1.1])
self.dContrast = ops.Uniform(range=[0.9, 1.1])
self.dBright = ops.Uniform(range=[0.9, 1.1])
self.dHue = ops.Uniform(range=[-0.1, 0.1])
if data_loader == "cpu":
print("Error: cpu data loader shouldn't be handled by DALI")
else:
# ---------- Decoding Operations --------- #
# ImageDecoder in mixed mode doesn't support YCbCr
# Ref: https://github.com/NVIDIA/DALI/pull/582/files
self.decode = ops.ImageDecoder(device="cpu", output_type=output_type)
# ---------- Augmentation Operations --------- #
# execute rest of the operations on the target device based upon the mode
device = "cpu" if data_loader == "dali_cpu" else "gpu"
self.resize_big = ops.Resize(device=device, resize_x=240, resize_y=240)
# depreciated replace with HSV and ops.BrightnessContrast soon
self.color_jitter = ops.ColorTwist(device=device, image_type=output_type)
# random area 0.93-1.0 corresponds to croping randomly from an image of size between (224-240)
self.crop = ops.RandomResizedCrop(device=device, random_area=[0.93, 0.93], size=image_size)
# ---------- Normalization Operations --------- #
self.resize = ops.Resize(device=device, resize_x=image_size[0], resize_y=image_size[1])
self.norm = ops.CropMirrorNormalize(device=device,
output_dtype=types.FLOAT,
output_layout='CHW',
image_type=output_type,
mean=mean,
std=std)
def define_graph(self):
self.row = self.rowBatch()
self.imFace = self.imFaceBatch()
self.imEyeL = self.imEyeLBatch()
self.imEyeR = self.imEyeRBatch()
self.imFaceGrid = self.imFaceGridBatch()
self.gaze = self.gazeBatch()
self.index = self.indexBatch()
sat, con, bri, hue = self.dSaturation(), self.dContrast(), self.dBright(), self.dHue()
def stream(image, augment=True):
# Decoding
image = self.decode(image)
if self.data_loader == "dali_gpu":
image = image.gpu()
# Augmentations (for training only)
if self.split == 'train' and augment:
image = self.resize_big(image)
image = self.color_jitter(image, saturation=sat, contrast=con, brightness=bri, hue=hue)
# Normalize
image = self.resize(image)
image = self.norm(image)
return image
# pass the input through dali stream
imFaceD = stream(self.imFace)
imEyeLD = stream(self.imEyeL)
imEyeRD = stream(self.imEyeR)
imFaceGridD = stream(self.imFaceGrid, False)
return (self.row, imFaceD, imEyeLD, imEyeRD, imFaceGridD, self.gaze, self.index)
@property
def size(self):
return len(self.sourceIterator)
def iter_setup(self):
(rowBatch, imFaceBatch, imEyeLBatch, imEyeRBatch, imFaceGridBatch, gazeBatch,
indexBatch) = self.sourceIterator.next()
self.feed_input(self.row, rowBatch)
self.feed_input(self.imFace, imFaceBatch)
self.feed_input(self.imEyeL, imEyeLBatch)
self.feed_input(self.imEyeR, imEyeRBatch)
self.feed_input(self.imFaceGrid, imFaceGridBatch)
self.feed_input(self.gaze, gazeBatch)
self.feed_input(self.index, indexBatch)
# class ExternalSourcePipeline(Pipeline):
# def __init__(self, data, batch_size, image_size, split, silent, num_threads, device_id, data_loader, color_space, shuffle=False):
# super(ExternalSourcePipeline, self).__init__(batch_size,
# num_threads,
# device_id)
# self.split = split
# self.color_space = color_space
# self.data_loader = data_loader
# if shuffle:
# data.shuffle()
# self.sourceIterator = iter(data)
# self.rowBatch = ops.ExternalSource()
# self.imFaceBatch = ops.ExternalSource()
# self.imEyeLBatch = ops.ExternalSource()
# self.imEyeRBatch = ops.ExternalSource()
# self.imFaceGridBatch = ops.ExternalSource()
# self.gazeBatch = ops.ExternalSource()
# self.indexBatch = ops.ExternalSource()
# self.frameBatch = ops.ExternalSource()
# mean = None
# std = None
# if color_space == 'RGB':
# output_type = types.RGB
# mean=[0.485 * 255, 0.456 * 255, 0.406 * 255]
# std=[0.229 * 255, 0.224 * 255, 0.225 * 255]
# elif color_space == 'YCbCr':
# output_type = types.YCbCr
# elif color_space == 'L':
# output_type = types.GRAY
# elif color_space == 'BGR':
# output_type = types.BGR
# else:
# print("Unsupported color_space:", color_space)
# # Variation range for Saturation, Contrast, Brightness and Hue
# self.dSaturation = ops.Uniform(range=[0.9, 1.1])
# self.dContrast = ops.Uniform(range=[0.9, 1.1])
# self.dBright = ops.Uniform(range=[0.9, 1.1])
# self.dHue = ops.Uniform(range=[-0.1, 0.1])
# if data_loader == "cpu":
# print("Error: cpu data loader shouldn't be handled by DALI")
# else:
# # ---------- Decoding Operations --------- #
# # ImageDecoder in mixed mode doesn't support YCbCr
# # Ref: https://github.com/NVIDIA/DALI/pull/582/files
# self.decode = ops.ImageDecoder(device="cpu", output_type=output_type)
# # ---------- Augmentation Operations --------- #
# # execute rest of the operations on the target device based upon the mode
# device = "cpu" if data_loader == "dali_cpu" else "gpu"
# self.resize_big = ops.Resize(device=device, resize_x=240, resize_y=240)
# # depreciated replace with HSV and ops.BrightnessContrast soon
# self.color_jitter = ops.ColorTwist(device=device, image_type=output_type)
# # random area 0.93-1.0 corresponds to croping randomly from an image of size between (224-240)
# self.crop = ops.RandomResizedCrop(device=device, random_area=[0.93, 0.93], size=image_size)
# # ---------- Normalization Operations --------- #
# self.resize = ops.Resize(device=device, resize_x=image_size[0], resize_y=image_size[1])
# self.norm = ops.CropMirrorNormalize(device=device,
# output_dtype=types.FLOAT,
# output_layout='CHW',
# image_type=output_type,
# mean=mean,
# std=std)
# def define_graph(self):
# self.row = self.rowBatch()
# self.imFace = self.imFaceBatch()
# self.imEyeL = self.imEyeLBatch()
# self.imEyeR = self.imEyeRBatch()
# self.imFaceGrid = self.imFaceGridBatch()
# self.gaze = self.gazeBatch()
# self.index = self.indexBatch()
# self.frame = self.frameBatch()
# sat, con, bri, hue = self.dSaturation(), self.dContrast(), self.dBright(), self.dHue()
# def stream(image, augment=True):
# # Decoding
# image = self.decode(image)
# if self.data_loader == "dali_gpu":
# image = image.gpu()
# # Augmentations (for training only)
# if self.split == 'train' and augment:
# image = self.resize_big(image)
# image = self.color_jitter(image, saturation=sat, contrast=con, brightness=bri, hue=hue)
# # Normalize
# image = self.resize(image)
# image = self.norm(image)
# return image
# # pass the input through dali stream
# imFaceD = stream(self.imFace)
# imEyeLD = stream(self.imEyeL)
# imEyeRD = stream(self.imEyeR)
# imFaceGridD = stream(self.imFaceGrid, False)
# return (self.row, imFaceD, imEyeLD, imEyeRD, imFaceGridD, self.gaze, self.index, self.frame)
# @property
# def size(self):
# return len(self.sourceIterator)
# def iter_setup(self):
# (rowBatch, imFaceBatch, imEyeLBatch, imEyeRBatch, imFaceGridBatch, gazeBatch,
# indexBatch, frameBatch) = self.sourceIterator.next()
# self.feed_input(self.row, rowBatch)
# self.feed_input(self.imFace, imFaceBatch)
# self.feed_input(self.imEyeL, imEyeLBatch)
# self.feed_input(self.imEyeR, imEyeRBatch)
# self.feed_input(self.imFaceGrid, imFaceGridBatch)
# self.feed_input(self.gaze, gazeBatch)
# self.feed_input(self.index, indexBatch)
# self.feed_input(self.frame, frameBatch)
class ITrackerMetadata(object):
def __init__(self, dataPath, silent=True):
if not silent:
print('Loading iTracker dataset')
metadata_file = os.path.join(dataPath, 'metadata.mat')
self.metadata = self.loadMetadata(metadata_file, silent)
def loadMetadata(self, filename, silent):
if filename is None or not os.path.isfile(filename):
raise RuntimeError('There is no such file %s! Provide a valid dataset path.' % filename)
try:
# http://stackoverflow.com/questions/6273634/access-array-contents-from-a-mat-file-loaded-using-scipy-io-loadmat-python
if not silent:
print('\tReading metadata from %s' % filename)
metadata = sio.loadmat(filename, squeeze_me=True, struct_as_record=False)
except:
raise RuntimeError('Could not read metadata file %s! Provide a valid dataset path.' % filename)
return metadata
class Dataset:
def __init__(self, split, data, size, loader):
self.split = split
self.data = data
self.size = size
self.loader = loader
# class ITrackerData(object):
# def __init__(self,
# dataPath,
# metadata,
# batch_size,
# imSize,
# gridSize,
# split,
# silent=True,
# jitter=True,
# color_space='YCbCr',
# data_loader='cpu',
# shard_id=0,
# num_shards=1,
# data_format='V2'):
# self.dataPath = dataPath
# self.metadata = metadata
# self.batch_size = batch_size
# self.imSize = imSize
# self.gridSize = gridSize
# self.color_space = color_space
# self.data_loader = data_loader
# self.index = 0
# self.split = split
# self.data_format = data_format
# # ======= Sharding configuration variables ========
# if num_shards > 0:
# self.num_shards = num_shards
# else:
# raise ValueError("num_shards cannot be negative")
# if shard_id >= 0 and shard_id < self.num_shards:
# self.shard_id = shard_id
# else:
# raise ValueError(f"shard_id should be between 0 and %d i.e. 0 <= shard_id < num_shards."%(num_shards))
# # ====================================================
# if self.split == 'test':
# mask = self.metadata['labelTest']
# elif self.split == 'val':
# mask = self.metadata['labelVal']
# elif self.split == 'train':
# mask = self.metadata['labelTrain']
# elif self.split == 'all':
# mask = np.ones[len(self.metadata)]
# else:
# raise Exception('split should be test, val or train. The value of split was: {}'.format(self.split))
# self.indices = np.argwhere(mask)[:, 0]
# if not silent:
# print('Loaded iTracker dataset split "%s" with %d records.' % (self.split, len(self.indices)))
# if self.data_loader == 'cpu':
# self.normalize_image = normalize_image_transform(image_size=self.imSize, jitter=jitter, split=self.split, color_space=self.color_space)
# self.resize_transform = resize_image_transform(image_size=self.imSize)
# self.mirror_transform = transforms.RandomHorizontalFlip(p=1.0)
# self.mirrorCoordinates = np.array([-1.0, 1.0])
# def __len__(self):
# return math.floor(len(self.indices)/self.num_shards)
# def loadImage(self, path):
# try:
# im = Image.open(path).convert(self.color_space)
# except OSError:
# raise RuntimeError('Could not read image: ' + path)
# return im
# def __getitem__(self, shard_index):
# # mapping for shards: shard index to absolute index
# index = self.shard_id * self.__len__() + shard_index
# rowIndex = self.indices[index]
# recordingNum = self.metadata['labelRecNum'][rowIndex]
# frameIndex = self.metadata['frameIndex'][rowIndex]
# if self.data_format == "V1":
# imFacePath = os.path.join(self.dataPath, '%05d/appleFace/%05d.jpg' % (recordingNum, frameIndex))
# imEyeLPath = os.path.join(self.dataPath, '%05d/appleLeftEye/%05d.jpg' % (recordingNum, frameIndex))
# imEyeRPath = os.path.join(self.dataPath, '%05d/appleRightEye/%05d.jpg' % (recordingNum, frameIndex))
# imFaceGridPath = os.path.join(self.dataPath, '%05d/faceGrid/%05d.jpg' % (recordingNum, frameIndex))
# else:
# # For new V2 format data
# imFacePath = os.path.join(self.dataPath, '%s/appleFace/%s.jpg' % (recordingNum, frameIndex))
# imEyeLPath = os.path.join(self.dataPath, '%s/appleLeftEye/%s.jpg' % (recordingNum, frameIndex))
# imEyeRPath = os.path.join(self.dataPath, '%s/appleRightEye/%s.jpg' % (recordingNum, frameIndex))
# imFaceGridPath = os.path.join(self.dataPath, '%s/faceGrid/%s.jpg' % (recordingNum, frameIndex))
# # Note: Converted from double (float64) to float (float32) as pipeline output is float in MSE calculation
# gaze = np.array([self.metadata['labelDotXCam'][rowIndex], self.metadata['labelDotYCam'][rowIndex]], np.float32)
# # V1
# # frame = np.array([self.metadata['labelRecNum'][rowIndex], self.metadata['frameIndex'][rowIndex]])
# # TODO: with new changes this becomes an array of string and makes dataloader grumpy because
# # default_collate metthod only supports primitive datatypes. To Pass strings to dataloader
# # use custom `frame_collate` method
# frame = np.array([self.metadata['labelRecNum'][rowIndex], self.metadata['frameIndex'][rowIndex]])
# # faceGrid = self.makeGrid(self.metadata['labelFaceGrid'][rowIndex, :])
# row = np.array([int(rowIndex)])
# index = np.array([int(index)])
# if self.data_loader == 'cpu':
# # Image loading, transformation and normalization happen here
# imFace = self.loadImage(imFacePath)
# imEyeL = self.loadImage(imEyeLPath)
# imEyeR = self.loadImage(imEyeRPath)
# imfaceGrid = self.loadImage(imFaceGridPath)
# # Data Augmentation: Mirroring
# # mirror data with 50% probablity
# if self.split == 'train' and random() >= 0.5:
# imFace = transforms.functional.hflip(imFace)
# imEyeR, imEyeL = transforms.functional.hflip(imEyeL), transforms.functional.hflip(imEyeR)
# imfaceGrid = transforms.functional.hflip(imfaceGrid)
# gaze = self.mirrorCoordinates * gaze
# # Data Augmentation: Random Crop, Color Jitter
# # faceGrid mustn't have these augmentations
# imFace = self.normalize_image(imFace)
# imEyeL = self.normalize_image(imEyeL)
# imEyeR = self.normalize_image(imEyeR)
# imfaceGrid = self.resize_transform(imfaceGrid)
# # to tensor
# row = torch.LongTensor([int(index)])
# # faceGrid = torch.FloatTensor(faceGrid)
# gaze = torch.FloatTensor(gaze)
# return row, imFace, imEyeL, imEyeR, imfaceGrid, gaze, index, frame
# else:
# # image loading, transformation and normalization happen in ExternalDataPipeline
# # we just pass imagePaths
# return row, imFacePath, imEyeLPath, imEyeRPath, imFaceGridPath, gaze, index, frame
# # TODO: Not in use anymore due to RC. Should eventually be removed
# def makeGrid(self, params):
# gridLen = self.gridSize[0] * self.gridSize[1]
# grid = np.zeros([gridLen, ], np.float32)
# indsY = np.array([i // self.gridSize[0] for i in range(gridLen)])
# indsX = np.array([i % self.gridSize[0] for i in range(gridLen)])
# condX = np.logical_and(indsX >= params[0], indsX < params[0] + params[2])
# condY = np.logical_and(indsY >= params[1], indsY < params[1] + params[3])
# cond = np.logical_and(condX, condY)
# grid[cond] = 1
# return grid
# # used by dali
# def __iter__(self):
# self.size = self.__len__()
# return self
# def shuffle(self):
# shuffle(self.indices)
# def __next__(self):
# rowBatch = []
# imFaceBatch = []
# imEyeLBatch = []
# imEyeRBatch = []
# imFaceGridBatch = []
# gazeBatch = []
# indexBatch = []
# frameBatch = []
# for local_index in range(self.batch_size):
# row, imFacePath, imEyeLPath, imEyeRPath, imFaceGridPath, gaze, index, frame = self.__getitem__(self.index)
# self.index = (self.index + 1) % self.__len__()
# imFace = open(imFacePath, 'rb')
# imEyeL = open(imEyeLPath, 'rb')
# imEyeR = open(imEyeRPath, 'rb')
# imFaceGrid = open(imFaceGridPath, 'rb')
# rowBatch.append(row)
# imFaceBatch.append(np.frombuffer(imFace.read(), dtype=np.uint8))
# imEyeLBatch.append(np.frombuffer(imEyeL.read(), dtype=np.uint8))
# imEyeRBatch.append(np.frombuffer(imEyeR.read(), dtype=np.uint8))
# imFaceGridBatch.append(np.frombuffer(imFaceGrid.read(), dtype=np.uint8))
# gazeBatch.append(gaze)
# indexBatch.append(index)
# frameBatch.append(frame)
# imFace.close()
# imEyeL.close()
# imEyeR.close()
# imFaceGrid.close()
# return rowBatch, imFaceBatch, imEyeLBatch, imEyeRBatch, imFaceGridBatch, gazeBatch, indexBatch, frameBatch
# # For compatibiity with Python 2
# def next(self):
# return self.__next__()
class ITrackerData(object):
def __init__(self,
dataPath,
metadata,
batch_size,
imSize,
gridSize,
split,
silent=True,
jitter=True,
color_space='YCbCr',
data_loader='cpu',
shard_id=0,
num_shards=1,
data_format='V2'):
self.dataPath = dataPath
self.metadata = metadata
self.batch_size = batch_size
self.imSize = imSize
self.gridSize = gridSize
self.color_space = color_space
self.data_loader = data_loader
self.index = 0
self.split = split
self.data_format = data_format
# ======= Sharding configuration variables ========
if num_shards > 0:
self.num_shards = num_shards
else:
raise ValueError("num_shards cannot be negative")
if shard_id >= 0 and shard_id < self.num_shards:
self.shard_id = shard_id
else:
raise ValueError(f"shard_id should be between 0 and %d i.e. 0 <= shard_id < num_shards."%(num_shards))
# ====================================================
if self.split == 'test':
mask = self.metadata['labelTest']
elif self.split == 'val':
mask = self.metadata['labelVal']
elif self.split == 'train':
mask = self.metadata['labelTrain']
elif self.split == 'all':
mask = np.ones[len(self.metadata)]
else:
raise Exception('split should be test, val or train. The value of split was: {}'.format(self.split))
self.indices = np.argwhere(mask)[:, 0]
if not silent:
print('Loaded iTracker dataset split "%s" with %d records.' % (self.split, len(self.indices)))
if self.data_loader == 'cpu':
self.normalize_image = normalize_image_transform(image_size=self.imSize, jitter=jitter, split=self.split, color_space=self.color_space)
self.resize_transform = resize_image_transform(image_size=self.imSize)
self.mirror_transform = transforms.RandomHorizontalFlip(p=1.0)
self.mirrorCoordinates = np.array([-1.0, 1.0])
def __len__(self):
return math.floor(len(self.indices)/self.num_shards)
def loadImage(self, path):
try:
im = Image.open(path).convert(self.color_space)
except OSError:
raise RuntimeError('Could not read image: ' + path)
return im
def __getitem__(self, shard_index):
# mapping for shards: shard index to absolute index
index = self.shard_id * self.__len__() + shard_index
rowIndex = self.indices[index]
recordingNum = self.metadata['labelRecNum'][rowIndex]
frameIndex = self.metadata['frameIndex'][rowIndex]
if self.data_format == "V1":
imFacePath = os.path.join(self.dataPath, '%05d/appleFace/%05d.jpg' % (recordingNum, frameIndex))
imEyeLPath = os.path.join(self.dataPath, '%05d/appleLeftEye/%05d.jpg' % (recordingNum, frameIndex))
imEyeRPath = os.path.join(self.dataPath, '%05d/appleRightEye/%05d.jpg' % (recordingNum, frameIndex))
imFaceGridPath = os.path.join(self.dataPath, '%05d/faceGrid/%05d.jpg' % (recordingNum, frameIndex))
else:
# For new V2 format data
imFacePath = os.path.join(self.dataPath, '%s/appleFace/%s.jpg' % (recordingNum, frameIndex))
imEyeLPath = os.path.join(self.dataPath, '%s/appleLeftEye/%s.jpg' % (recordingNum, frameIndex))
imEyeRPath = os.path.join(self.dataPath, '%s/appleRightEye/%s.jpg' % (recordingNum, frameIndex))
imFaceGridPath = os.path.join(self.dataPath, '%s/faceGrid/%s.jpg' % (recordingNum, frameIndex))
# Note: Converted from double (float64) to float (float32) as pipeline output is float in MSE calculation
gaze = np.array([self.metadata['labelDotXCam'][rowIndex], self.metadata['labelDotYCam'][rowIndex]], np.float32)
# frame = np.array([self.metadata['labelRecNum'][rowIndex], self.metadata['frameIndex'][rowIndex]])
# frame = np.array([self.metadata['labelRecNum'][rowIndex], self.metadata['frameIndex'][rowIndex]], np.object)
# faceGrid = self.makeGrid(self.metadata['labelFaceGrid'][rowIndex, :])
row = np.array([int(rowIndex)])
index = np.array([int(index)])
if self.data_loader == 'cpu':
# Image loading, transformation and normalization happen here
imFace = self.loadImage(imFacePath)
imEyeL = self.loadImage(imEyeLPath)
imEyeR = self.loadImage(imEyeRPath)
imfaceGrid = self.loadImage(imFaceGridPath)
# Data Augmentation: Mirroring
# mirror data with 50% probablity
if self.split == 'train' and random() >= 0.5:
imFace = transforms.functional.hflip(imFace)
imEyeR, imEyeL = transforms.functional.hflip(imEyeL), transforms.functional.hflip(imEyeR)
imfaceGrid = transforms.functional.hflip(imfaceGrid)
gaze = self.mirrorCoordinates * gaze
# Data Augmentation: Random Crop, Color Jitter
# faceGrid mustn't have these augmentations
imFace = self.normalize_image(imFace)
imEyeL = self.normalize_image(imEyeL)
imEyeR = self.normalize_image(imEyeR)
imfaceGrid = self.resize_transform(imfaceGrid)
# to tensor
row = torch.LongTensor([int(index)])
# faceGrid = torch.FloatTensor(faceGrid)
gaze = torch.FloatTensor(gaze)
return row, imFace, imEyeL, imEyeR, imfaceGrid, gaze, index
else:
# image loading, transformation and normalization happen in ExternalDataPipeline
# we just pass imagePaths
return row, imFacePath, imEyeLPath, imEyeRPath, imFaceGridPath, gaze, index
# TODO: Not in use anymore due to RC. Should eventually be removed
def makeGrid(self, params):
gridLen = self.gridSize[0] * self.gridSize[1]
grid = np.zeros([gridLen, ], np.float32)
indsY = np.array([i // self.gridSize[0] for i in range(gridLen)])
indsX = np.array([i % self.gridSize[0] for i in range(gridLen)])
condX = np.logical_and(indsX >= params[0], indsX < params[0] + params[2])
condY = np.logical_and(indsY >= params[1], indsY < params[1] + params[3])
cond = np.logical_and(condX, condY)
grid[cond] = 1
return grid
# used by dali
def __iter__(self):
self.size = self.__len__()
return self
def shuffle(self):
shuffle(self.indices)
def __next__(self):
rowBatch = []
imFaceBatch = []
imEyeLBatch = []
imEyeRBatch = []
imFaceGridBatch = []
gazeBatch = []
indexBatch = []
for local_index in range(self.batch_size):
row, imFacePath, imEyeLPath, imEyeRPath, imFaceGridPath, gaze, index = self.__getitem__(self.index)
self.index = (self.index + 1) % self.__len__()
imFace = open(imFacePath, 'rb')
imEyeL = open(imEyeLPath, 'rb')
imEyeR = open(imEyeRPath, 'rb')
imFaceGrid = open(imFaceGridPath, 'rb')
rowBatch.append(row)
imFaceBatch.append(np.frombuffer(imFace.read(), dtype=np.uint8))
imEyeLBatch.append(np.frombuffer(imEyeL.read(), dtype=np.uint8))
imEyeRBatch.append(np.frombuffer(imEyeR.read(), dtype=np.uint8))
imFaceGridBatch.append(np.frombuffer(imFaceGrid.read(), dtype=np.uint8))
gazeBatch.append(gaze)
indexBatch.append(index)
imFace.close()
imEyeL.close()
imEyeR.close()
imFaceGrid.close()
return rowBatch, imFaceBatch, imEyeLBatch, imEyeRBatch, imFaceGridBatch, gazeBatch, indexBatch
# For compatibiity with Python 2
def next(self):
return self.__next__()
def load_data(split,
dataPath,
metadata,
image_size,
grid_size,
workers,
batch_size,
verbose,
local_rank,
color_space,
data_loader,
eval_boost,
mode,
data_format):
shuffle = True if split == 'train' else False
# Enable shading here for ddp2 mode only
if mode == "ddp2":
shard_id, num_shards = local_rank[0], torch.cuda.device_count()
else:
shard_id, num_shards = 0, 1
if eval_boost:
batch_size = batch_size if split == 'train' else batch_size * 2
data = ITrackerData(dataPath,
metadata,
batch_size,
image_size,
grid_size,
split,
silent=not verbose,
jitter=True,
color_space=color_space,
data_loader=data_loader,
shard_id=shard_id,
num_shards=num_shards,
data_format=data_format)
size = len(data)
# DALI implementation would do a cross-shard shuffle
# CPU implementation would do a in-shard shuffle
if data_loader == "cpu":
loader = torch.utils.data.DataLoader(
data,
batch_size=batch_size,
shuffle=True,
num_workers=workers,
pin_memory=True,
collate_fn = custom_collate)
elif data_loader == "dali_gpu" or data_loader == "dali_cpu":
pipes = [ExternalSourcePipeline(data,
batch_size=batch_size,
image_size=image_size,
split=split,
silent=not verbose,
num_threads=8,
device_id=local_rank[0],
data_loader=data_loader,
color_space=color_space,
shuffle=True)]
# DALI automatically allocates Pinned memory whereever possible
# auto_reset=True resets the iterator after each epoch
# DALIGenericIterator has inbuilt build for all pipelines
loader = DALIGenericIterator(pipes,
['row', 'imFace', 'imEyeL', 'imEyeR', 'imFaceGrid', 'gaze', 'frame', 'indices'],
size=len(data),
fill_last_batch=False,
last_batch_padded=True, auto_reset=True)
# loader = DALIGenericIterator(pipes,
# ['row', 'imFace', 'imEyeL', 'imEyeR', 'imFaceGrid', 'gaze', 'indices'],
# size=len(data),
# fill_last_batch=False,
# last_batch_padded=True, auto_reset=True)
else:
raise ValueError(f"Invalid data_loader mode: %s"%(data_loader))
return Dataset(split, data, size, loader)
# Define the custom collate strategy for dataloader
def custom_collate(batch):
return default_collate(batch)
# def custom_collate(batch):
# new_batch = []
# frames = []
# for _batch in batch:
# new_batch.append(_batch[:-1])
# frames.append(_batch[-1])
# return default_collate(new_batch), frames
def load_all_data(path,
image_size,
grid_size,
workers,
batch_size,
verbose,
local_rank,
color_space='YCbCr',
data_loader='cpu',
eval_boost=False,
mode='none',
data_format='V2'):
print(centered_text('Loading Data'))
metadata = ITrackerMetadata(path, silent=not verbose).metadata
splits = ['train', 'val', 'test']
all_data = {
split: load_data(split,
path,
metadata,
image_size,
grid_size,
workers,
batch_size,
verbose,
local_rank,
color_space,
data_loader,
eval_boost,
mode,
data_format)
for split in splits}
return all_data