-
Notifications
You must be signed in to change notification settings - Fork 3
/
CrowdDataset.py
364 lines (320 loc) · 13.7 KB
/
CrowdDataset.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
import os, cv2
import pdb
import numpy as np
import scipy.io
from skimage import io
import skimage.transform as SkT
from PIL import Image
import torch
from torch.utils.data import Dataset, DataLoader, Subset
import torchvision.transforms as T
import np_transforms as NP_T
from utils import density_map, gaussian_filter_density
from scipy.ndimage.filters import gaussian_filter
class TestDataset(Dataset):
def __init__(self,
train,
path,
out_shape=None,
transform=None,
gamma=5,
max_len=None,
adaptive=False,
k_nearest=3,
load_all=False):
self.k = k_nearest
self.adaptive = adaptive
self.path = path
self.out_shape = np.array(out_shape)
self.transform = transform
self.gamma = gamma
self.load_all = load_all
if train:
self.img_path = os.path.join(self.path, 'train_data')
self.label_path = os.path.join(self.path, 'train_label')
else:
self.img_path = os.path.join(self.path, 'test_data')
self.label_path = os.path.join(self.path, 'test_label')
dirs = os.listdir(self.img_path)
self.image_files = []
for dir_name in dirs:
self.image_files += [
'{}&{}'.format(dir_name, f)
for f in os.listdir(os.path.join(self.img_path, dir_name))
if f.endswith('png') or f.endswith('jpg')
]
if self.load_all:
self.images, self.gts = [], []
for img_f in self.image_files:
X, gt = self.load_example(img_f)
self.images.append(X)
self.gts.append(gt)
def load_example(self, img_f):
dir_name, img_name = img_f.split('&')
# img = Image.open(os.path.join(self.img_path, dir_name, img_name)).convert('RGB')
img = cv2.imread(os.path.join(self.img_path, dir_name, img_name))
# if len(img.shape) == 2:
# print(os.path.join(self.img_path, dir_name, img_name))
points = np.load(os.path.join(self.label_path, dir_name, img_name[:-4]+ '.npy'))
H_orig, W_orig = img.shape[:2]
if H_orig != self.out_shape[0] or W_orig != self.out_shape[1]:
# img = img.resize((self.out_shape[1], self.out_shape[0]), Image.BILINEAR)
img = cv2.resize(img, (self.out_shape[1], self.out_shape[0]), cv2.INTER_LINEAR)
ratio = self.out_shape / np.array([H_orig, W_orig])
points = np.round(points*ratio)
img = np.array(img, np.float32)
points = np.array(points, np.int32)
points = np.minimum(points, self.out_shape - 1)
gt = np.zeros(self.out_shape)
gt[points[:, 0], points[:, 1]] = 1
gt = gt[:, :, np.newaxis].astype('float32')
return img, gt
def __len__(self):
return len(self.image_files)
def __getitem__(self, i):
if self.load_all:
img_f = self.image_files[i]
X = self.images[i]
gt = self.gts[i]
else:
img_f = self.image_files[i]
X, gt = self.load_example(img_f)
if self.transform:
X, gt = self.transform([X, gt])
return X, gt, img_f
class TestSeq(TestDataset):
def __init__(self,
train=True,
path='../ucsdpeds/UCSD',
out_shape=[240, 320],
transform=None,
gamma=5,
adaptive=False,
k_nearest=3,
max_len=None,
load_all=False):
super(TestSeq, self).__init__(train=train,
path=path,
out_shape=out_shape,
transform=transform,
gamma=gamma,
adaptive=adaptive,
k_nearest=k_nearest,
max_len=max_len,
load_all=load_all)
self.img2idx = {img: idx for idx, img in enumerate(self.image_files)}
self.seqs = []
prev_dir = None
cur_len = 0
for img_f in self.image_files:
dir_name, img_name = img_f.split('&')
if (dir_name == prev_dir) and ((max_len is None) or
(cur_len < max_len)):
self.seqs[-1].append(img_f)
cur_len += 1
else:
self.seqs.append([img_f])
cur_len = 1
prev_dir = dir_name
if max_len is None:
self.max_len = max([len(seq) for seq in self.seqs])
else:
self.max_len = max_len
def __len__(self):
return len(self.seqs)
def __getitem__(self, i):
seq = self.seqs[i]
seq_len = len(seq)
# randomize the (random) transformations applied to the first image of the sequence
# and then apply the same transformations to the remaining images of the sequence
if isinstance(self.transform, T.Compose):
for transf in self.transform.transforms:
if hasattr(transf, 'rand_state'):
transf.reset_rand_state()
elif hasattr(self.transform, 'rand_state'):
self.transform.reset_rand_state()
# build the sequences
X = torch.zeros(self.max_len, 3, self.out_shape[0], self.out_shape[1])
gt = torch.zeros(self.max_len, 1, self.out_shape[0], self.out_shape[1])
names = []
for j, img_f in enumerate(seq):
idx = self.img2idx[img_f]
X[j], gt[j], name = super().__getitem__(idx)
names.append(name)
return X, gt, seq_len, names
class CrowdDataset(Dataset):
def __init__(self,
train,
path,
out_shape=None,
transform=None,
gamma=5,
max_len=None,
adaptive=False,
k_nearest=3,
load_all=False):
self.k = k_nearest
self.adaptive = adaptive
self.path = path
self.out_shape = np.array(out_shape)
self.transform = transform
self.gamma = gamma
self.load_all = load_all
if train:
self.img_path = os.path.join(self.path, 'train_data')
self.label_path = os.path.join(self.path, 'train_label')
else:
self.img_path = os.path.join(self.path, 'test_data')
self.label_path = os.path.join(self.path, 'test_label')
dirs = os.listdir(self.img_path)
self.image_files = []
for dir_name in dirs:
self.image_files += [
'{}&{}'.format(dir_name, f)
for f in os.listdir(os.path.join(self.img_path, dir_name))
if f.endswith('png') or f.endswith('jpg')
]
if self.load_all:
self.images, self.gts, self.densities = [], [], []
for img_f in self.image_files:
X, density, gt = self.load_example(img_f)
self.images.append(X)
self.densities.append(density)
self.gts.append(gt)
def load_example(self, img_f):
dir_name, img_name = img_f.split('&')
# img = Image.open(os.path.join(self.img_path, dir_name, img_name)).convert('RGB')
img = cv2.imread(os.path.join(self.img_path, dir_name, img_name))
# if len(img.shape) == 2:
# print(os.path.join(self.img_path, dir_name, img_name))
points = np.load(os.path.join(self.label_path, dir_name, img_name[:-4]+ '.npy'))
H_orig, W_orig = img.shape[:2]
if H_orig != self.out_shape[0] or W_orig != self.out_shape[1]:
# img = img.resize((self.out_shape[1], self.out_shape[0]), Image.BILINEAR)
img = cv2.resize(img, (self.out_shape[1], self.out_shape[0]), cv2.INTER_LINEAR)
ratio = self.out_shape / np.array([H_orig, W_orig])
points = np.round(points*ratio)
img = np.array(img, np.float32)
points = np.array(points, np.int32)
points = np.minimum(points, self.out_shape - 1)
gt = np.zeros(self.out_shape)
gt[points[:, 0], points[:, 1]] = 1
density = gaussian_filter_density(gt, self.gamma, self.k, self.adaptive)
density = cv2.resize(density, (density.shape[1] // 8, density.shape[0] // 8),
interpolation=cv2.INTER_LINEAR) * 64
density = density[:, :, np.newaxis].astype('float32')
gt = gt[:, :, np.newaxis].astype('float32')
return img, density, gt
def __len__(self):
return len(self.image_files)
def __getitem__(self, i):
if self.load_all:
img_f = self.image_files[i]
X = self.images[i]
density = self.densities[i]
gt = self.gts[i]
else:
img_f = self.image_files[i]
X, density, gt = self.load_example(img_f)
if self.transform:
X, density, gt = self.transform([X, density, gt])
return X, density, gt
class CrowdSeq(CrowdDataset):
def __init__(self,
train=True,
path='../ucsdpeds/UCSD',
out_shape=[240, 320],
transform=None,
gamma=5,
adaptive=False,
k_nearest=3,
max_len=None,
load_all=False):
super(CrowdSeq, self).__init__(train=train,
path=path,
out_shape=out_shape,
transform=transform,
gamma=gamma,
adaptive=adaptive,
k_nearest=k_nearest,
max_len=max_len,
load_all=load_all)
self.img2idx = {img: idx for idx, img in enumerate(self.image_files)}
self.seqs = []
prev_dir = None
cur_len = 0
for img_f in self.image_files:
dir_name, img_name = img_f.split('&')
if (dir_name == prev_dir) and ((max_len is None) or
(cur_len < max_len)):
self.seqs[-1].append(img_f)
cur_len += 1
else:
self.seqs.append([img_f])
cur_len = 1
prev_dir = dir_name
if max_len is None:
self.max_len = max([len(seq) for seq in self.seqs])
else:
self.max_len = max_len
def __len__(self):
return len(self.seqs)
def __getitem__(self, i):
seq = self.seqs[i]
seq_len = len(seq)
# randomize the (random) transformations applied to the first image of the sequence
# and then apply the same transformations to the remaining images of the sequence
if isinstance(self.transform, T.Compose):
for transf in self.transform.transforms:
if hasattr(transf, 'rand_state'):
transf.reset_rand_state()
elif hasattr(self.transform, 'rand_state'):
self.transform.reset_rand_state()
# build the sequences
X = torch.zeros(self.max_len, 3, self.out_shape[0], self.out_shape[1])
density = torch.zeros(self.max_len, 1, self.out_shape[0]//8,
self.out_shape[1]//8)
gt = torch.zeros(self.max_len, 1, self.out_shape[0], self.out_shape[1])
for j, img_f in enumerate(seq):
idx = self.img2idx[img_f]
X[j], density[j], gt[j] = super().__getitem__(idx)
return X, density, gt, seq_len
if __name__ == '__main__':
train_transf = T.Compose([
NP_T.RandomHorizontalFlip(0.5, keep_state=True),
NP_T.ToTensor()
])
# data = CrowdDataset(train=False,
# path='../FDST/FDST',
# load_all=False,
# max_len=1,
# transform=train_transf,
# out_shape=[240, 320],
# adaptive=False,
# k_nearest=4,
# gamma=100)
# train_loader = DataLoader(data, batch_size=10, shuffle=True, num_workers=1)
# for i, (X, density, gt, count) in enumerate(train_loader):
# aa = 1
# print('Image {}: count={}, density_sum={:.3f}'.format(
# i, count.sum(), density.sum()))
dataset = 'UCSD'
if dataset == 'UCSD':
path = './ucsdpeds/UCSD'
elif dataset == 'Mall':
path = './mall_dataset/Mall'
elif dataset == 'FDST':
path = './FDST/FDST'
data = CrowdSeq(train=False,
path=path,
load_all=False,
max_len=1,
transform=train_transf,
out_shape=[240, 320],
adaptive=False,
k_nearest=2,
gamma=100)
train_loader = DataLoader(data, batch_size=10, shuffle=True, num_workers=4)
for i, (X, density, gt, seq_len) in enumerate(train_loader):
# print(i)
print('count={}, density_sum={:.3f}'.format(gt.sum(), density.sum()))