-
Notifications
You must be signed in to change notification settings - Fork 5
/
dataloader.py
363 lines (281 loc) · 12.9 KB
/
dataloader.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
import os
import glob
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
import numpy as np
import pandas as pd
import random
# 전처리를 위한 라이브러리
import cv2
from pycocotools.coco import COCO
import albumentations as A
from albumentations.pytorch import ToTensorV2
def get_classname(classID, cats):
for i in range(len(cats)):
if cats[i]['id']==classID:
return cats[i]['name']
return "None"
class CustomDataLoader(Dataset):
"""COCO format"""
def __init__(self, data_dir, mode = 'train', transform = None):
super().__init__()
self.mode = mode
self.transform = transform
self.coco = COCO(data_dir)
self.dataset_path = 'input/data/'
self.category_names = ['Backgroud', 'UNKNOWN', 'General trash', 'Paper', 'Paper pack', 'Metal', 'Glass', 'Plastic', 'Styrofoam', 'Plastic bag', 'Battery', 'Clothing']
def __getitem__(self, index: int):
### Load Imgs ###
image_id = self.coco.getImgIds(imgIds=index)
image_infos = self.coco.loadImgs(image_id)[0]
images = cv2.imread(self.dataset_path+image_infos['file_name'])
images = cv2.cvtColor(images, cv2.COLOR_BGR2RGB).astype(np.float32)
images /= 255.0
### Train Time ###
if (self.mode in ('train', 'val')):
ann_ids = self.coco.getAnnIds(imgIds=image_infos['id'])
anns = self.coco.loadAnns(ann_ids)
cat_ids = self.coco.getCatIds()
cats = self.coco.loadCats(cat_ids)
### mask 생성 ###
masks = np.zeros((image_infos["height"], image_infos["width"]))
for i in range(len(anns)):
className = get_classname(anns[i]['category_id'], cats)
pixel_value = self.category_names.index(className)
masks = np.maximum(self.coco.annToMask(anns[i])*pixel_value, masks)
masks = masks.astype(np.float32)
### augmentation ###
if self.transform is not None:
transformed = self.transform(image=images, mask=masks)
images = transformed["image"]
masks = transformed["mask"]
return images, masks #, image_infos
### Test Time ###
if self.mode == 'test':
if self.transform is not None:
transformed = self.transform(image=images)
images = transformed["image"]
return images #, image_infos
def __len__(self):
return len(self.coco.getImgIds())
class EnsembleDataset(Dataset):
"""COCO format"""
def __init__(self, data_dir, size, transform=None):
super().__init__()
self.coco = COCO(data_dir)
self.dataset_path = 'input/data/'
self.transform = transform
if size==256:
self.Resize = A.Resize(256, 256)
else:
self.Resize = None
self.Flip = A.HorizontalFlip(p=1.0)
self.ToTensor = ToTensorV2()
def __getitem__(self, index: int):
### Load Imgs ###
image_id = self.coco.getImgIds(imgIds=index)
image_infos = self.coco.loadImgs(image_id)[0]
images = cv2.imread(self.dataset_path+image_infos['file_name'])
images = cv2.cvtColor(images, cv2.COLOR_BGR2RGB).astype(np.float32)
images /= 255.0
if self.Resize is not None:
images = self.Resize(image=images)["image"]
if self.transform=='flip':
images = self.Flip(image=images)["image"]
elif self.transform=='rotate':
images = cv2.rotate(images, cv2.ROTATE_90_CLOCKWISE)
elif self.transform=='rotateR':
images = cv2.rotate(images, cv2.ROTATE_90_COUNTERCLOCKWISE)
images = self.ToTensor(image=images)["image"]
return images
def __len__(self):
return len(self.coco.getImgIds())
labels_W = [0.0,
0.00781,
0.0,
0.0,
0.00190,
0.00223,
0.00205,
0.0,
0.0,
0.0,
0.02,
0.00710]
def labelRandomChoice(labels):
labels = np.unique(labels)
choice = np.zeros(12).astype(int)
choice[labels]=[labels]
choiced_label = random.choices(choice, weights=labels_W, k=1)
return torch.LongTensor(choiced_label)
class MixDataLoader(Dataset):
"""COCO format"""
def __init__(self, data_dir, mode = 'train', transform = None):
super().__init__()
self.mode = mode
self.transform = transform
self.coco = COCO(data_dir)
self.dataset_path = 'input/data/'
self.category_names = ['Backgroud', 'UNKNOWN', 'General trash', 'Paper', 'Paper pack', 'Metal', 'Glass', 'Plastic', 'Styrofoam', 'Plastic bag', 'Battery', 'Clothing']
def __getitem__(self, index: int):
### Load Imgs ###
image_id = self.coco.getImgIds(imgIds=index)
image_infos = self.coco.loadImgs(image_id)[0]
images = cv2.imread(self.dataset_path+image_infos['file_name'])
images = cv2.cvtColor(images, cv2.COLOR_BGR2RGB).astype(np.float32)
images /= 255.0
### Train Time ###
if (self.mode in ('train', 'val')):
ann_ids = self.coco.getAnnIds(imgIds=image_infos['id'])
anns = self.coco.loadAnns(ann_ids)
cat_ids = self.coco.getCatIds()
cats = self.coco.loadCats(cat_ids)
### mask 생성 ###
labels = []
masks = np.zeros((image_infos["height"], image_infos["width"]))
for i in range(len(anns)):
className = get_classname(anns[i]['category_id'], cats)
pixel_value = self.category_names.index(className)
masks = np.maximum(self.coco.annToMask(anns[i])*pixel_value, masks)
labels.append(pixel_value)
masks = masks.astype(np.float32)
### augmentation ###
if self.transform is not None:
transformed = self.transform(image=images, mask=masks)
images = transformed["image"]
masks = transformed["mask"]
return images, masks, labelRandomChoice(labels)
### Test Time ###
if self.mode == 'test':
if self.transform is not None:
transformed = self.transform(image=images)
images = transformed["image"]
return images #, image_infos
def __len__(self):
return len(self.coco.getImgIds())
class PseudoTrainset(Dataset):
"""COCO format"""
def __init__(self, data_dir, transform = None):
super().__init__()
self.transform = transform
self.coco = COCO(data_dir)
self.dataset_path = 'input/data/'
self.category_names = ['Backgroud', 'UNKNOWN', 'General trash', 'Paper', 'Paper pack', 'Metal', 'Glass', 'Plastic', 'Styrofoam', 'Plastic bag', 'Battery', 'Clothing']
self.pseudo_imgs = np.load('input/data/pseudo_imgs_path.npy')
self.pseudo_masks = sorted(glob.glob(f'input/data/pseudo_masks/*.npy'))
def __getitem__(self, index: int):
### Train data ###
if (index < len(self.coco.getImgIds())):
image_id = self.coco.getImgIds(imgIds=index)
image_infos = self.coco.loadImgs(image_id)[0]
images = cv2.imread(self.dataset_path+image_infos['file_name'])
images = cv2.cvtColor(images, cv2.COLOR_BGR2RGB).astype(np.float32)
images /= 255.0
ann_ids = self.coco.getAnnIds(imgIds=image_infos['id'])
anns = self.coco.loadAnns(ann_ids)
cat_ids = self.coco.getCatIds()
cats = self.coco.loadCats(cat_ids)
### mask 생성 ###
masks = np.zeros((image_infos["height"], image_infos["width"]))
for i in range(len(anns)):
className = get_classname(anns[i]['category_id'], cats)
pixel_value = self.category_names.index(className)
masks = np.maximum(self.coco.annToMask(anns[i])*pixel_value, masks)
### Pseudo data ###
else:
index -= len(self.coco.getImgIds())
images = cv2.imread(self.dataset_path+self.pseudo_imgs[index])
images = cv2.cvtColor(images, cv2.COLOR_BGR2RGB).astype(np.float32)
images /= 255.0
masks = np.load(self.pseudo_masks[index])
### augmentation ###
masks = masks.astype(np.float32)
if self.transform is not None:
transformed = self.transform(image=images, mask=masks)
images = transformed["image"]
masks = transformed["mask"]
return images, masks
def __len__(self):
return len(self.coco.getImgIds())+len(self.pseudo_imgs)
class PseudoKFoldDataset(Dataset):
"""COCO format"""
def __init__(self, dataset, transform = None):
super().__init__()
self.dataset = dataset
self.transform = transform
self.coco = COCO('input/data/train_all.json')
self.dataset_path = 'input/data/'
self.category_names = ['Backgroud', 'UNKNOWN', 'General trash', 'Paper', 'Paper pack', 'Metal', 'Glass', 'Plastic', 'Styrofoam', 'Plastic bag', 'Battery', 'Clothing']
def __getitem__(self, index: int):
### load image ###
image_infos = self.dataset[index]
images = cv2.imread(self.dataset_path+image_infos['file_name'])
images = cv2.cvtColor(images, cv2.COLOR_BGR2RGB).astype(np.float32)
images /= 255.0
### Pseudo mask ###
if image_infos['pseudo']:
masks = np.load(self.dataset_path+image_infos['mask_path'])
### Train mask ###
else:
ann_ids = self.coco.getAnnIds(imgIds=image_infos['id'])
anns = self.coco.loadAnns(ann_ids)
cat_ids = self.coco.getCatIds()
cats = self.coco.loadCats(cat_ids)
masks = np.zeros((image_infos["height"], image_infos["width"]))
for i in range(len(anns)):
className = get_classname(anns[i]['category_id'], cats)
pixel_value = self.category_names.index(className)
masks = np.maximum(self.coco.annToMask(anns[i])*pixel_value, masks)
masks = masks.astype(np.float32)
### augmentation ###
if self.transform is not None:
transformed = self.transform(image=images, mask=masks)
images = transformed["image"]
masks = transformed["mask"]
return images, masks
def __len__(self):
return len(self.dataset)
class KFoldDataset(Dataset):
"""COCO format"""
def __init__(self, dataset, mode = 'train', transform = None):
super().__init__()
self.mode = mode
self.dataset = dataset
self.transform = transform
self.coco = COCO('input/data/train_all.json')
self.dataset_path = 'input/data/'
self.category_names = ['Backgroud', 'UNKNOWN', 'General trash', 'Paper', 'Paper pack', 'Metal', 'Glass', 'Plastic', 'Styrofoam', 'Plastic bag', 'Battery', 'Clothing']
def __getitem__(self, index: int):
image_infos = self.dataset[index]
### load Data ###
images = cv2.imread(self.dataset_path+image_infos['file_name'])
images = cv2.cvtColor(images, cv2.COLOR_BGR2RGB).astype(np.float32)
images /= 255.0
### Train Time ###
if (self.mode in ('train', 'val')):
ann_ids = self.coco.getAnnIds(imgIds=image_infos['id'])
anns = self.coco.loadAnns(ann_ids)
cat_ids = self.coco.getCatIds()
cats = self.coco.loadCats(cat_ids)
### mask 생성 ###
masks = np.zeros((image_infos["height"], image_infos["width"]))
for i in range(len(anns)):
className = get_classname(anns[i]['category_id'], cats)
pixel_value = self.category_names.index(className)
masks = np.maximum(self.coco.annToMask(anns[i])*pixel_value, masks)
masks = masks.astype(np.float32)
### augmentation ###
if self.transform is not None:
transformed = self.transform(image=images, mask=masks)
images = transformed["image"]
masks = transformed["mask"]
return images, masks
### Test Time ###
if self.mode == 'test':
if self.transform is not None:
transformed = self.transform(image=images)
images = transformed["image"]
return images
def __len__(self):
return len(self.dataset)