-
Notifications
You must be signed in to change notification settings - Fork 1
/
image_folder.py
407 lines (367 loc) · 16.1 KB
/
image_folder.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
import torch.utils.data as Data
from torchvision.datasets.folder import default_loader
from torchvision import transforms
from os.path import join as ospj
from PIL import Image
import os
import numpy as np
from collections import defaultdict
import random
def has_file_allowed_extension(filename, extensions):
"""Checks if a file is an allowed extension.
Args:
filename (string): path to a file
Returns:
bool: True if the filename ends with a known image extension
"""
filename_lower = filename.lower()
return any(filename_lower.endswith(ext) for ext in extensions)
def find_classes(dir):
classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]
classes.sort()
class_to_idx = {classes[i]: i for i in range(len(classes))}
return classes, class_to_idx
def make_dataset(dir, class_to_idx, extensions):
images = []
dir = os.path.expanduser(dir)
for target in sorted(os.listdir(dir)):
d = os.path.join(dir, target)
if not os.path.isdir(d):
continue
for root, _, fnames in sorted(os.walk(d)):
for fname in sorted(fnames):
if has_file_allowed_extension(fname, extensions):
path = os.path.join(root, fname)
item = (path, class_to_idx[target])
images.append(item)
return images
#getting one image of a folder.
def make_dataset_one(dir, class_to_idx, extensions, reverse=False):
images = []
dir = os.path.expanduser(dir)
for target in sorted(os.listdir(dir)):
d = os.path.join(dir, target)
if not os.path.isdir(d):
continue
for root, _, fnames in sorted(os.walk(d)):
index = 0
for fname in sorted(fnames, reverse=reverse):
index += 1
if has_file_allowed_extension(fname, extensions) and index == 36:
path = os.path.join(root, fname)
item = (path, class_to_idx[target])
images.append(item)
break
return images
def pil_loader(path):
# 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)
return img.convert('RGB')
def accimage_loader(path):
import accimage
try:
return accimage.Image(path)
except IOError:
# Potentially a decoding problem, fall back to PIL.Image
return pil_loader(path)
def default_loader(path):
from torchvision import get_image_backend
if get_image_backend() == 'accimage':
return accimage_loader(path)
else:
return pil_loader(path)
class customData(Data.Dataset):
def __init__(self, root, transform = None, target_transform = None, loader = default_loader, rotate = 0, pad = 0):
classes, class_to_idx = find_classes(root)
IMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif']
imgs = make_dataset(root, class_to_idx, IMG_EXTENSIONS)
if len(imgs) == 0:
raise(RuntimeError("Found 0 images in subfolders of: " + root + "\n"
"Supported image extensions are: " + ",".join(IMG_EXTENSIONS)))
self.root = root
self.imgs = imgs
self.classes = classes
self.class_to_idx = class_to_idx
self.transform = transform
self.target_transform = target_transform
self.loader = loader
self.rotate = rotate
self.pad = pad
def __getitem__(self, index):
"""
index (int): Index
Returns:tuple: (image, target) where target is class_index of the target class.
"""
path, target = self.imgs[index]
img = self.loader(path)
img = transforms.functional.rotate(img,self.rotate)
if self.pad > 0:
img = transforms.functional.resize(img,(256,256),interpolation=3)
img = transforms.functional.pad(img,(self.pad,0,0,0))
img = transforms.functional.five_crop(img,(256,256))[0]
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
return img, target
def __len__(self):
return len(self.imgs)
class customData_one(Data.Dataset):
def __init__(self, root, transform = None, target_transform = None, loader = default_loader, rotate = 0, pad = 0, reverse=False):
classes, class_to_idx = find_classes(root)
IMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif']
imgs = make_dataset_one(root, class_to_idx, IMG_EXTENSIONS, reverse)
if len(imgs) == 0:
raise(RuntimeError("Found 0 images in subfolders of: " + root + "\n"
"Supported image extensions are: " + ",".join(IMG_EXTENSIONS)))
self.root = root
self.imgs = imgs
self.classes = classes
self.class_to_idx = class_to_idx
self.transform = transform
self.target_transform = target_transform
self.loader = loader
self.rotate = rotate
self.pad = pad
def __getitem__(self, index):
"""
index (int): Index
Returns:tuple: (image, target) where target is class_index of the target class.
"""
path, target = self.imgs[index]
img = self.loader(path)
img = transforms.functional.rotate(img,self.rotate)
if self.pad > 0:
img = transforms.functional.resize(img,(256,256),interpolation=3)
img = transforms.functional.pad(img,(self.pad,0,0,0))
img = transforms.functional.five_crop(img,(256,256))[0]
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
return img, target
def __len__(self):
return len(self.imgs)
def make_dataset_style(dir, class_to_idx, extensions, style='all'):
images = []
dir = os.path.expanduser(dir)
for target in sorted(os.listdir(dir)):
d = os.path.join(dir, target)
if not os.path.isdir(d):
continue
for root, _, fnames in sorted(os.walk(d)):
for fname in sorted(fnames):
if has_file_allowed_extension(fname, extensions):
if style == 'all':
path = os.path.join(root, fname)
item = (path, class_to_idx[target])
images.append(item)
else:
fstyle = fname.split('_')[2].split('.')[0]
if fstyle == style:
path = os.path.join(root, fname)
item = (path, class_to_idx[target])
images.append(item)
return images
class customData_style(Data.Dataset):
def __init__(self, root, transform = None, target_transform = None, loader = default_loader, rotate = 0, pad = 0, style = 'all'):
classes, class_to_idx = find_classes(root)
IMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif']
imgs = make_dataset_style(root, class_to_idx, IMG_EXTENSIONS, style=style)
if len(imgs) == 0:
raise(RuntimeError("Found 0 images in subfolders of: " + root + "\n"
"Supported image extensions are: " + ",".join(IMG_EXTENSIONS)))
self.root = root
self.imgs = imgs
self.classes = classes
self.class_to_idx = class_to_idx
self.transform = transform
self.target_transform = target_transform
self.loader = loader
self.rotate = rotate
self.pad = pad
def __getitem__(self, index):
"""
index (int): Index
Returns:tuple: (image, target) where target is class_index of the target class.
"""
path, target = self.imgs[index]
img = self.loader(path)
img = transforms.functional.rotate(img,self.rotate)
if self.pad > 0:
img = transforms.functional.resize(img,(256,256),interpolation=3)
img = transforms.functional.pad(img,(self.pad,0,0,0))
img = transforms.functional.five_crop(img,(256,256))[0]
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
return img, target
def __len__(self):
return len(self.imgs)
class ImageFolder_iaa(Data.Dataset):
def __init__(self, root, transform = None, target_transform = None, loader = default_loader, iaa_transform = None):
classes, class_to_idx = find_classes(root)
IMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif']
imgs = make_dataset(root, class_to_idx, IMG_EXTENSIONS)
if len(imgs) == 0:
raise(RuntimeError("Found 0 images in subfolders of: " + root + "\n"
"Supported image extensions are: " + ",".join(IMG_EXTENSIONS)))
self.root = root
self.imgs = imgs
self.classes = classes
self.class_to_idx = class_to_idx
self.transform = transform
self.target_transform = target_transform
self.loader = loader
self.iaa_trans = iaa_transform
def __getitem__(self, index):
"""
index (int): Index
Returns:tuple: (image, target) where target is class_index of the target class.
"""
path, target = self.imgs[index]
img = self.loader(path)
if self.iaa_trans is not None:
img = np.array(img)
img = self.iaa_trans(image = img)
# img = Image.fromarray(img)
# img_aug.save('/home/wangtingyu/%s'%path.split('/')[-1])
# else:
# img = np.array(img)
# # img = Image.fromarray(img)
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
return img, target
def __len__(self):
return len(self.imgs)
def make_dataset_selectID(dir, class_to_idx, extensions):
images = defaultdict(list)
dir = os.path.expanduser(dir)
for target in sorted(os.listdir(dir)):
d = os.path.join(dir, target)
if not os.path.isdir(d):
continue
for root, _, fnames in sorted(os.walk(d)):
for fname in sorted(fnames):
if has_file_allowed_extension(fname, extensions):
path = os.path.join(root, fname)
item = (path, class_to_idx[target])
images[class_to_idx[target]].append(item)
return images
class ImageFolder_iaa_selectID(Data.Dataset):
def __init__(self, root, transform = None, target_transform = None, loader = default_loader, iaa_transform = None, norm='bn'):
classes, class_to_idx = find_classes(root)
IMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif']
imgs = make_dataset_selectID(root, class_to_idx, IMG_EXTENSIONS)
if len(imgs.keys()) == 0:
raise(RuntimeError("Found 0 images in subfolders of: " + root + "\n"
"Supported image extensions are: " + ",".join(IMG_EXTENSIONS)))
self.root = root
self.imgs = imgs
self.classes = classes
self.class_to_idx = class_to_idx
self.transform = transform
self.target_transform = target_transform
self.loader = loader
self.iaa_trans = iaa_transform
self.norm = norm
def __getitem__(self, index):
"""
index (int): Index
Returns:tuple: (image, target) where target is class_index of the target class.
"""
path, target = random.choice(self.imgs[index])
img = self.loader(path)
if self.iaa_trans is not None:
img = np.array(img)
img = self.iaa_trans(image = img)
# img_aug = Image.fromarray(img)
# img_aug.save('/home/wangtyu/test_img/%s'%path.split('/')[-1])
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
if self.norm == 'ada-ibn' or self.norm == 'spade':
return img, target, 1
else:
return img, target
def __len__(self):
return len(self.imgs)
class ImageFolder_iaa_multi_weather(Data.Dataset):
def __init__(self, root, transform = None, target_transform = None, loader = default_loader, iaa_transform = None, iaa_weather_list=[], batchsize=8, shuffle=False, norm='bn', select=False):
classes, class_to_idx = find_classes(root)
IMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif']
if select:
imgs = make_dataset_selectID(root, class_to_idx, IMG_EXTENSIONS)
else:
imgs = make_dataset(root, class_to_idx, IMG_EXTENSIONS)
if len(imgs) == 0:
raise(RuntimeError("Found 0 images in subfolders of: " + root + "\n"
"Supported image extensions are: " + ",".join(IMG_EXTENSIONS)))
self.root = root
self.imgs = imgs
self.classes = classes
self.class_to_idx = class_to_idx
self.transform = transform
self.target_transform = target_transform
self.loader = loader
self.iaa_trans = iaa_transform
self.iaa_weather_list = iaa_weather_list
self.batch = batchsize
self.img_num = 0
self.shuffle = shuffle
self.norm = norm
self.select = select
# random.seed(1)
def __getitem__(self, index):
"""
index (int): Index
Returns:tuple: (image, target) where target is class_index of the target class.
"""
if self.select:
path, target = random.choice(self.imgs[index])
else:
path, target = self.imgs[index]
img = self.loader(path)
# if self.iaa_trans is not None:
# img = np.array(img)
# img = self.iaa_trans(image = img)
if self.iaa_weather_list:
img = np.array(img)
if self.shuffle:
idx = random.choice(range(len(self.iaa_weather_list)))
if idx == 0:
img = img
else:
img = self.iaa_weather_list[idx](image=img)
# img_aug = Image.fromarray(img)
# img_aug.save('/home/wangtyu/test_img/%s'%path.split('/')[-1])
else:
idx = self.img_num // self.batch % (len(self.iaa_weather_list)+1)
if idx == 0:
img = img
# img_aug = Image.fromarray(img)
# img_aug.save('/Users/wongtyu/Downloads/University-Release/train/%s'%path.split('/')[-1])
else:
img = self.iaa_weather_list[idx-1](image = img)
# img_aug = Image.fromarray(img)
# img_aug.save('/Users/wongtyu/Downloads/University-Release/train/%s'%path.split('/')[-1])
self.img_num += 1
if self.img_num == len(self):
self.img_num = 0
if self.iaa_trans is not None:
img = self.iaa_trans(image = img)
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
if self.norm == 'ada-ibn' or self.norm == 'spade':
return img, target, idx+1
else:
return img, target
def __len__(self):
return len(self.imgs)