-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdata.py
194 lines (153 loc) · 6.59 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
import os
import re
import math
import random
import collections
from torchvision import transforms
from torch.utils.data import dataset,dataloader,sampler
from torchvision.datasets.folder import default_loader
from opt import opt
class Data:
def __init__(self):
train_transform = transforms.Compose([
transforms.Resize((384, 128), interpolation=3),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
RandomErasing(probability=opt.rep, mean=[0.0, 0.0, 0.0])])
test_transform = transforms.Compose([
transforms.Resize((384, 128), interpolation=3),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])
self.trainset = Market1501(train_transform, 'train',opt.data_path)
self.testset = Market1501(test_transform, 'test',opt.data_path)
self.queryset = Market1501(test_transform, 'query',opt.data_path)
self.train_loader = dataloader.DataLoader(self.trainset,
sampler=RandomSampler(self.trainset, batch_id=opt.batchid,
batch_image=opt.batchimage),
batch_size=opt.batchid*opt.batchimage, num_workers=8,
pin_memory=True, drop_last=True)
self.test_loader = dataloader.DataLoader(self.testset, batch_size=opt.batchtest, num_workers=8,
pin_memory=True)
self.query_loader = dataloader.DataLoader(self.queryset, batch_size=opt.batchtest, num_workers=8,
pin_memory=True)
class RandomErasing(object):
""" Randomly selects a rectangle region in an image and erases its pixels.
'Random Erasing Data Augmentation' by Zhong et al.
See https://arxiv.org/pdf/1708.04896.pdf
Args:
probability: The probability that the Random Erasing operation will be performed.
sl: Minimum proportion of erased area against input image.
sh: Maximum proportion of erased area against input image.
r1: Minimum aspect ratio of erased area.
mean: Erasing value.
"""
def __init__(self, probability=0.5, sl=0.02, sh=0.4, r1=0.3, mean=[0.4914, 0.4822, 0.4465]):
self.probability = probability
self.mean = mean
self.sl = sl
self.sh = sh
self.r1 = r1
def __call__(self, img):
if random.uniform(0, 1) > self.probability:
return img
for attempt in range(100):
area = img.size()[1] * img.size()[2]
target_area = random.uniform(self.sl, self.sh) * area
aspect_ratio = random.uniform(self.r1, 1 / self.r1)
h = int(round(math.sqrt(target_area * aspect_ratio)))
w = int(round(math.sqrt(target_area / aspect_ratio)))
if w < img.size()[2] and h < img.size()[1]:
x1 = random.randint(0, img.size()[1] - h)
y1 = random.randint(0, img.size()[2] - w)
if img.size()[0] == 3:
img[0, x1:x1 + h, y1:y1 + w] = self.mean[0]
img[1, x1:x1 + h, y1:y1 + w] = self.mean[1]
img[2, x1:x1 + h, y1:y1 + w] = self.mean[2]
else:
img[0, x1:x1 + h, y1:y1 + w] = self.mean[0]
return img
return img
def list_pictures(directory, ext='jpg|jpeg|bmp|png|ppm'):
assert os.path.isdir(directory), 'dataset is not exists!{}'.format(directory)
return sorted([os.path.join(root, f)
for root, _, files in os.walk(directory) for f in files
if re.match(r'([\w]+\.(?:' + ext + '))', f)])
class Market1501(dataset.Dataset):
def __init__(self, transform, dtype, data_path):
self.transform = transform
self.loader = default_loader
self.data_path = data_path
if dtype == 'train':
self.data_path += '/bounding_box_train'
elif dtype == 'test':
self.data_path += '/bounding_box_test'
else:
self.data_path += '/query'
self.imgs = [path for path in list_pictures(self.data_path) if self.id(path) != -1]
self._id2label = {_id: idx for idx, _id in enumerate(self.unique_ids)}
def __getitem__(self, index):
path = self.imgs[index]
target = self._id2label[self.id(path)]
img = self.loader(path)
if self.transform is not None:
img = self.transform(img)
return img, target
def __len__(self):
return len(self.imgs)
@staticmethod
def id(file_path):
"""
:param file_path: unix style file path
:return: person id
"""
return int(file_path.split('/')[-1].split('_')[0])
@staticmethod
def camera(file_path):
"""
:param file_path: unix style file path
:return: camera id
"""
return int(file_path.split('/')[-1].split('_')[1][1])
@property
def ids(self):
"""
:return: person id list corresponding to dataset image paths
"""
return [self.id(path) for path in self.imgs]
@property
def unique_ids(self):
"""
:return: unique person ids in ascending order
"""
return sorted(set(self.ids))
@property
def cameras(self):
"""
:return: camera id list corresponding to dataset image paths
"""
return [self.camera(path) for path in self.imgs]
class RandomSampler(sampler.Sampler):
def __init__(self, data_source, batch_id, batch_image):
super(RandomSampler, self).__init__(data_source)
self.data_source = data_source
self.batch_image = batch_image
self.batch_id = batch_id
self._id2index = collections.defaultdict(list)
for idx, path in enumerate(data_source.imgs):
_id = data_source.id(path)
self._id2index[_id].append(idx)
def __iter__(self):
unique_ids = self.data_source.unique_ids
random.shuffle(unique_ids)
imgs = []
for _id in unique_ids:
imgs.extend(self._sample(self._id2index[_id], self.batch_image))
return iter(imgs)
def __len__(self):
return len(self._id2index) * self.batch_image
@staticmethod
def _sample(population, k):
if len(population) < k:
population = population * k
return random.sample(population, k)