-
Notifications
You must be signed in to change notification settings - Fork 35
/
imdbfolder_coco.py
152 lines (127 loc) · 5.33 KB
/
imdbfolder_coco.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
# imdbfolder_coco.py
# created by Sylvestre-Alvise Rebuffi [[email protected]]
# Copyright © The University of Oxford, 2017-2020
# This code is made available under the Apache v2.0 licence, see LICENSE.txt for details
import torch.utils.data as data
import torchvision
import torchvision.transforms as transforms
import torch
import numpy as np
import pickle
import config_task
from PIL import Image
from pycocotools.coco import COCO
import os
import os.path
IMG_EXTENSIONS = [
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',
]
def pil_loader(path):
return Image.open(path).convert('RGB')
class ImageFolder(data.Dataset):
def __init__(self, root, transform=None, target_transform=None, index=None,
labels=None ,imgs=None,loader=pil_loader,skip_label_indexing=0):
if len(imgs) == 0:
raise(RuntimeError("Found 0 images in subfolders of: " + root + "\n"
"Supported image extensions are: " + ",".join(IMG_EXTENSIONS)))
self.root = root
if index is not None:
imgs = [imgs[i] for i in index]
self.imgs = imgs
if index is not None:
if skip_label_indexing == 0:
labels = [labels[i] for i in index]
self.labels = labels
self.transform = transform
self.target_transform = target_transform
self.loader = loader
def __getitem__(self, index):
path = self.imgs[index][0]
target = self.labels[index]
img = self.loader(path)
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 prepare_data_loaders(dataset_names, data_dir, imdb_dir, shuffle_train=True, index=None):
train_loaders = []
val_loaders = []
num_classes = []
train = [0]
val = [1]
config_task.offset = []
imdb_names_train = [imdb_dir + '/' + dataset_names[i] + '_train.json' for i in range(len(dataset_names))]
imdb_names_val = [imdb_dir + '/' + dataset_names[i] + '_val.json' for i in range(len(dataset_names))]
imdb_names = [imdb_names_train, imdb_names_val]
with open(data_dir + 'decathlon_mean_std.pickle', 'rb') as handle:
dict_mean_std = pickle.load(handle)
for i in range(len(dataset_names)):
imgnames_train = []
imgnames_val = []
labels_train = []
labels_val = []
for itera1 in train+val:
annFile = imdb_names[itera1][i]
coco = COCO(annFile)
imgIds = coco.getImgIds()
annIds = coco.getAnnIds(imgIds=imgIds)
anno = coco.loadAnns(annIds)
images = coco.loadImgs(imgIds)
timgnames = [img['file_name'] for img in images]
timgnames_id = [img['id'] for img in images]
labels = [int(ann['category_id'])-1 for ann in anno]
min_lab = min(labels)
labels = [lab - min_lab for lab in labels]
max_lab = max(labels)
imgnames = []
for j in range(len(timgnames)):
imgnames.append((data_dir + '/' + timgnames[j],timgnames_id[j]))
if itera1 in train:
imgnames_train += imgnames
labels_train += labels
if itera1 in val:
imgnames_val += imgnames
labels_val += labels
num_classes.append(int(max_lab+1))
config_task.offset.append(min_lab)
means = dict_mean_std[dataset_names[i] + 'mean']
stds = dict_mean_std[dataset_names[i] + 'std']
if dataset_names[i] in ['gtsrb', 'omniglot','svhn']: # no horz flip
transform_train = transforms.Compose([
transforms.Resize(72),
transforms.CenterCrop(72),
transforms.ToTensor(),
transforms.Normalize(means, stds),
])
else:
transform_train = transforms.Compose([
transforms.Resize(72),
transforms.RandomCrop(64),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(means, stds),
])
if dataset_names[i] in ['gtsrb', 'omniglot','svhn']: # no horz flip
transform_test = transforms.Compose([
transforms.Resize(72),
transforms.CenterCrop(72),
transforms.ToTensor(),
transforms.Normalize(means, stds),
])
else:
transform_test = transforms.Compose([
transforms.Resize(72),
transforms.CenterCrop(64),
transforms.ToTensor(),
transforms.Normalize(means, stds),
])
img_path = data_dir
trainloader = torch.utils.data.DataLoader(ImageFolder(data_dir, transform_train, None, index, labels_train, imgnames_train), batch_size=128, shuffle=shuffle_train, num_workers=4, pin_memory=True)
valloader = torch.utils.data.DataLoader(ImageFolder(data_dir, transform_test, None, None, labels_val, imgnames_val), batch_size=100, shuffle=False, num_workers=4, pin_memory=True)
train_loaders.append(trainloader)
val_loaders.append(valloader)
return train_loaders, val_loaders, num_classes