-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata.py
557 lines (498 loc) · 19.7 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
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
from __future__ import division, print_function, absolute_import
import torch
from sampler import build_train_sampler
from datasets import init_image_dataset, init_video_dataset
from transforms import build_transforms
class DataManager(object):
r"""Base data manager.
Args:
sources (str or list): source dataset(s).
targets (str or list, optional): target dataset(s). If not given,
it equals to ``sources``.
height (int, optional): target image height. Default is 256.
width (int, optional): target image width. Default is 128.
transforms (str or list of str, optional): transformations applied to model training.
Default is 'random_flip'.
norm_mean (list or None, optional): data mean. Default is None (use imagenet mean).
norm_std (list or None, optional): data std. Default is None (use imagenet std).
use_gpu (bool, optional): use gpu. Default is True.
"""
def __init__(
self,
sources=None,
targets=None,
height=256,
width=128,
transforms='random_flip',
norm_mean=None,
norm_std=None,
use_gpu=False
):
self.sources = sources
self.targets = targets
self.height = height
self.width = width
if self.sources is None:
raise ValueError('sources must not be None')
if isinstance(self.sources, str):
self.sources = [self.sources]
if self.targets is None:
self.targets = self.sources
if isinstance(self.targets, str):
self.targets = [self.targets]
self.transform_tr, self.transform_te = build_transforms(
self.height,
self.width,
transforms=transforms,
norm_mean=norm_mean,
norm_std=norm_std
)
self.use_gpu = (torch.cuda.is_available() and use_gpu)
@property
def num_train_pids(self):
"""Returns the number of training person identities."""
return self._num_train_pids
@property
def num_train_cams(self):
"""Returns the number of training cameras."""
return self._num_train_cams
def fetch_test_loaders(self, name):
"""Returns query and gallery of a test dataset, each containing
tuples of (img_path(s), pid, camid).
Args:
name (str): dataset name.
"""
query_loader = self.test_dataset[name]['query']
gallery_loader = self.test_dataset[name]['gallery']
return query_loader, gallery_loader
def preprocess_pil_img(self, img):
"""Transforms a PIL image to torch tensor for testing."""
return self.transform_te(img)
class ImageDataManager(DataManager):
r"""Image data manager.
Args:
root (str): root path to datasets.
sources (str or list): source dataset(s).
targets (str or list, optional): target dataset(s). If not given,
it equals to ``sources``.
height (int, optional): target image height. Default is 256.
width (int, optional): target image width. Default is 128.
transforms (str or list of str, optional): transformations applied to model training.
Default is 'random_flip'.
k_tfm (int): number of times to apply augmentation to an image
independently. If k_tfm > 1, the transform function will be
applied k_tfm times to an image. This variable will only be
useful for training and is currently valid for image datasets only.
norm_mean (list or None, optional): data mean. Default is None (use imagenet mean).
norm_std (list or None, optional): data std. Default is None (use imagenet std).
use_gpu (bool, optional): use gpu. Default is True.
split_id (int, optional): split id (*0-based*). Default is 0.
combineall (bool, optional): combine train, query and gallery in a dataset for
training. Default is False.
load_train_targets (bool, optional): construct train-loader for target datasets.
Default is False. This is useful for domain adaptation research.
batch_size_train (int, optional): number of images in a training batch. Default is 32.
batch_size_test (int, optional): number of images in a test batch. Default is 32.
workers (int, optional): number of workers. Default is 4.
num_instances (int, optional): number of instances per identity in a batch.
Default is 4.
num_cams (int, optional): number of cameras to sample in a batch (when using
``RandomDomainSampler``). Default is 1.
num_datasets (int, optional): number of datasets to sample in a batch (when
using ``RandomDatasetSampler``). Default is 1.
train_sampler (str, optional): sampler. Default is RandomSampler.
train_sampler_t (str, optional): sampler for target train loader. Default is RandomSampler.
cuhk03_labeled (bool, optional): use cuhk03 labeled images.
Default is False (defaul is to use detected images).
cuhk03_classic_split (bool, optional): use the classic split in cuhk03.
Default is False.
market1501_500k (bool, optional): add 500K distractors to the gallery
set in market1501. Default is False.
Examples::
datamanager = torchreid.data.ImageDataManager(
root='path/to/reid-data',
sources='market1501',
height=256,
width=128,
batch_size_train=32,
batch_size_test=100
)
# return train loader of source data
train_loader = datamanager.train_loader
# return test loader of target data
test_loader = datamanager.test_loader
# return train loader of target data
train_loader_t = datamanager.train_loader_t
"""
data_type = 'image'
def __init__(
self,
root='',
sources=None,
targets=None,
height=256,
width=128,
transforms='random_flip',
k_tfm=1,
norm_mean=None,
norm_std=None,
use_gpu=True,
split_id=0,
combineall=False,
load_train_targets=False,
batch_size_train=32,
batch_size_test=32,
workers=4,
num_instances=4,
num_cams=1,
num_datasets=1,
train_sampler='RandomSampler',
train_sampler_t='RandomSampler',
cuhk03_labeled=False,
cuhk03_classic_split=False,
market1501_500k=False
):
super(ImageDataManager, self).__init__(
sources=sources,
targets=targets,
height=height,
width=width,
transforms=transforms,
norm_mean=norm_mean,
norm_std=norm_std,
use_gpu=use_gpu
)
print('=> Loading train (source) dataset')
trainset = []
for name in self.sources:
trainset_ = init_image_dataset(
name,
transform=self.transform_tr,
k_tfm=k_tfm,
mode='train',
combineall=combineall,
root=root,
split_id=split_id,
cuhk03_labeled=cuhk03_labeled,
cuhk03_classic_split=cuhk03_classic_split,
market1501_500k=market1501_500k
)
trainset.append(trainset_)
trainset = sum(trainset)
self._num_train_pids = trainset.num_train_pids
self._num_train_cams = trainset.num_train_cams
self.train_loader = torch.utils.data.DataLoader(
trainset,
sampler=build_train_sampler(
trainset.train,
train_sampler,
batch_size=batch_size_train,
num_instances=num_instances,
num_cams=num_cams,
num_datasets=num_datasets
),
batch_size=batch_size_train,
shuffle=False,
num_workers=workers,
pin_memory=self.use_gpu,
drop_last=True
)
self.train_loader_t = None
if load_train_targets:
# check if sources and targets are identical
assert len(set(self.sources) & set(self.targets)) == 0, \
'sources={} and targets={} must not have overlap'.format(self.sources, self.targets)
print('=> Loading train (target) dataset')
trainset_t = []
for name in self.targets:
trainset_t_ = init_image_dataset(
name,
transform=self.transform_tr,
k_tfm=k_tfm,
mode='train',
combineall=False, # only use the training data
root=root,
split_id=split_id,
cuhk03_labeled=cuhk03_labeled,
cuhk03_classic_split=cuhk03_classic_split,
market1501_500k=market1501_500k
)
trainset_t.append(trainset_t_)
trainset_t = sum(trainset_t)
self.train_loader_t = torch.utils.data.DataLoader(
trainset_t,
sampler=build_train_sampler(
trainset_t.train,
train_sampler_t,
batch_size=batch_size_train,
num_instances=num_instances,
num_cams=num_cams,
num_datasets=num_datasets
),
batch_size=batch_size_train,
shuffle=False,
num_workers=workers,
pin_memory=self.use_gpu,
drop_last=True
)
print('=> Loading test (target) dataset')
self.test_loader = {
name: {
'query': None,
'gallery': None
}
for name in self.targets
}
self.test_dataset = {
name: {
'query': None,
'gallery': None
}
for name in self.targets
}
for name in self.targets:
# build query loader
queryset = init_image_dataset(
name,
transform=self.transform_te,
mode='query',
combineall=combineall,
root=root,
split_id=split_id,
cuhk03_labeled=cuhk03_labeled,
cuhk03_classic_split=cuhk03_classic_split,
market1501_500k=market1501_500k
)
self.test_loader[name]['query'] = torch.utils.data.DataLoader(
queryset,
batch_size=batch_size_test,
shuffle=False,
num_workers=workers,
pin_memory=self.use_gpu,
drop_last=False
)
# build gallery loader
galleryset = init_image_dataset(
name,
transform=self.transform_te,
mode='gallery',
combineall=combineall,
verbose=False,
root=root,
split_id=split_id,
cuhk03_labeled=cuhk03_labeled,
cuhk03_classic_split=cuhk03_classic_split,
market1501_500k=market1501_500k
)
self.test_loader[name]['gallery'] = torch.utils.data.DataLoader(
galleryset,
batch_size=batch_size_test,
shuffle=False,
num_workers=workers,
pin_memory=self.use_gpu,
drop_last=False
)
self.test_dataset[name]['query'] = queryset.query
self.test_dataset[name]['gallery'] = galleryset.gallery
print('\n')
print(' **************** Summary ****************')
print(' source : {}'.format(self.sources))
print(' # source datasets : {}'.format(len(self.sources)))
print(' # source ids : {}'.format(self.num_train_pids))
print(' # source images : {}'.format(len(trainset)))
print(' # source cameras : {}'.format(self.num_train_cams))
if load_train_targets:
print(
' # target images : {} (unlabeled)'.format(len(trainset_t))
)
print(' target : {}'.format(self.targets))
print(' *****************************************')
print('\n')
class VideoDataManager(DataManager):
r"""Video data manager.
Args:
root (str): root path to datasets.
sources (str or list): source dataset(s).
targets (str or list, optional): target dataset(s). If not given,
it equals to ``sources``.
height (int, optional): target image height. Default is 256.
width (int, optional): target image width. Default is 128.
transforms (str or list of str, optional): transformations applied to model training.
Default is 'random_flip'.
norm_mean (list or None, optional): data mean. Default is None (use imagenet mean).
norm_std (list or None, optional): data std. Default is None (use imagenet std).
use_gpu (bool, optional): use gpu. Default is True.
split_id (int, optional): split id (*0-based*). Default is 0.
combineall (bool, optional): combine train, query and gallery in a dataset for
training. Default is False.
batch_size_train (int, optional): number of tracklets in a training batch. Default is 3.
batch_size_test (int, optional): number of tracklets in a test batch. Default is 3.
workers (int, optional): number of workers. Default is 4.
num_instances (int, optional): number of instances per identity in a batch.
Default is 4.
num_cams (int, optional): number of cameras to sample in a batch (when using
``RandomDomainSampler``). Default is 1.
num_datasets (int, optional): number of datasets to sample in a batch (when
using ``RandomDatasetSampler``). Default is 1.
train_sampler (str, optional): sampler. Default is RandomSampler.
seq_len (int, optional): how many images to sample in a tracklet. Default is 15.
sample_method (str, optional): how to sample images in a tracklet. Default is "evenly".
Choices are ["evenly", "random", "all"]. "evenly" and "random" will sample ``seq_len``
images in a tracklet while "all" samples all images in a tracklet, where the batch size
needs to be set to 1.
Examples::
datamanager = torchreid.data.VideoDataManager(
root='path/to/reid-data',
sources='mars',
height=256,
width=128,
batch_size_train=3,
batch_size_test=3,
seq_len=15,
sample_method='evenly'
)
# return train loader of source data
train_loader = datamanager.train_loader
# return test loader of target data
test_loader = datamanager.test_loader
.. note::
The current implementation only supports image-like training. Therefore, each image in a
sampled tracklet will undergo independent transformation functions. To achieve tracklet-aware
training, you need to modify the transformation functions for video reid such that each function
applies the same operation to all images in a tracklet to keep consistency.
"""
data_type = 'video'
def __init__(
self,
root='',
sources=None,
targets=None,
height=256,
width=128,
transforms='random_flip',
norm_mean=None,
norm_std=None,
use_gpu=True,
split_id=0,
combineall=False,
batch_size_train=3,
batch_size_test=3,
workers=4,
num_instances=4,
num_cams=1,
num_datasets=1,
train_sampler='RandomSampler',
seq_len=15,
sample_method='evenly'
):
super(VideoDataManager, self).__init__(
sources=sources,
targets=targets,
height=height,
width=width,
transforms=transforms,
norm_mean=norm_mean,
norm_std=norm_std,
use_gpu=use_gpu
)
print('=> Loading train (source) dataset')
trainset = []
for name in self.sources:
trainset_ = init_video_dataset(
name,
transform=self.transform_tr,
mode='train',
combineall=combineall,
root=root,
split_id=split_id,
seq_len=seq_len,
sample_method=sample_method
)
trainset.append(trainset_)
trainset = sum(trainset)
self._num_train_pids = trainset.num_train_pids
self._num_train_cams = trainset.num_train_cams
train_sampler = build_train_sampler(
trainset.train,
train_sampler,
batch_size=batch_size_train,
num_instances=num_instances,
num_cams=num_cams,
num_datasets=num_datasets
)
self.train_loader = torch.utils.data.DataLoader(
trainset,
sampler=train_sampler,
batch_size=batch_size_train,
shuffle=False,
num_workers=workers,
pin_memory=self.use_gpu,
drop_last=True
)
print('=> Loading test (target) dataset')
self.test_loader = {
name: {
'query': None,
'gallery': None
}
for name in self.targets
}
self.test_dataset = {
name: {
'query': None,
'gallery': None
}
for name in self.targets
}
for name in self.targets:
# build query loader
queryset = init_video_dataset(
name,
transform=self.transform_te,
mode='query',
combineall=combineall,
root=root,
split_id=split_id,
seq_len=seq_len,
sample_method=sample_method
)
self.test_loader[name]['query'] = torch.utils.data.DataLoader(
queryset,
batch_size=batch_size_test,
shuffle=False,
num_workers=workers,
pin_memory=self.use_gpu,
drop_last=False
)
# build gallery loader
galleryset = init_video_dataset(
name,
transform=self.transform_te,
mode='gallery',
combineall=combineall,
verbose=False,
root=root,
split_id=split_id,
seq_len=seq_len,
sample_method=sample_method
)
self.test_loader[name]['gallery'] = torch.utils.data.DataLoader(
galleryset,
batch_size=batch_size_test,
shuffle=False,
num_workers=workers,
pin_memory=self.use_gpu,
drop_last=False
)
self.test_dataset[name]['query'] = queryset.query
self.test_dataset[name]['gallery'] = galleryset.gallery
print('\n')
print(' **************** Summary ****************')
print(' source : {}'.format(self.sources))
print(' # source datasets : {}'.format(len(self.sources)))
print(' # source ids : {}'.format(self.num_train_pids))
print(' # source tracklets : {}'.format(len(trainset)))
print(' # source cameras : {}'.format(self.num_train_cams))
print(' target : {}'.format(self.targets))
print(' *****************************************')
print('\n')