-
Notifications
You must be signed in to change notification settings - Fork 0
/
data.py
131 lines (99 loc) · 4.18 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
import os
import cv2
import torch
import numpy as np
from eval import CocoTypeEvaluator, get_coco_api_from_dataset
from torch.utils.data import DataLoader
from albumentations.pytorch import ToTensorV2
from image_handler import get_bb_list, visualize
import albumentations as A
labels_to_id = {'killer': 1, 'surv': 2}
def collate_fn(batch):
return tuple(zip(*batch))
class UnNormalize(object):
def __init__(self, mean, std):
self.mean = np.array(mean, dtype=np.float32)*255.0
self.std = np.array(std, dtype=np.float32)*255.0
def __call__(self, tensor):
"""
Args:
tensor (Tensor): Tensor image of size (C, H, W) to be normalized.
Returns:
Tensor: Normalized image.
"""
img = tensor.cpu().numpy()
img *= self.std
img += self.mean
return img
def get_transform(train):
if train:
transform = A.Compose([
A.RandomSizedBBoxSafeCrop(width=525, height=600),
A.HorizontalFlip(p=0.5),
A.OneOf([
A.HueSaturationValue(hue_shift_limit=10, sat_shift_limit=30, val_shift_limit=20, p=1),
A.RandomBrightnessContrast(brightness_limit=0.2, contrast_limit=0.2, p=1),
], p=1),
A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
A.Resize(height=512, width=512, p=1.0),
ToTensorV2()],
bbox_params=A.BboxParams(format='pascal_voc', min_area=0, min_visibility=0, label_fields=['class_labels']))
return transform
else:
transform = A.Compose([
A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
A.Resize(height=512, width=512, p=1.0),
ToTensorV2()],
bbox_params=A.BboxParams(format='pascal_voc', min_area=0, min_visibility=0,
label_fields=['class_labels']))
return transform
class DbdImageDataset(object):
def __init__(self, root, transforms):
self.root = root
self.transforms = transforms
self.imgs = list(sorted(os.listdir(os.path.join(root, "resize_data"))))
self.boxes = list(sorted(os.listdir(os.path.join(root, "boxes"))))
def __getitem__(self, idx):
img_path = os.path.join(self.root, "resize_data/", self.imgs[idx])
box_path = os.path.join(self.root, "boxes/", self.boxes[idx])
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
bb, class_labels = get_bb_list(box_path)
class_labels = [labels_to_id[label] for label in class_labels]
if self.transforms is not None:
transformed = self.transforms(image=img, bboxes=bb, class_labels=class_labels)
img = transformed['image']
bb = transformed['bboxes']
class_labels = transformed['class_labels']
# TRANSFORM TO TENSORS
class_labels = torch.as_tensor(class_labels, dtype=torch.int64)
bb = torch.as_tensor(bb, dtype=torch.float32)
image_id = torch.tensor([idx])
area = (bb[:, 3] - bb[:, 1]) * (bb[:, 2] - bb[:, 0])
iscrowd = torch.zeros_like(area, dtype=torch.int64)
target = {
"boxes": bb,
"labels": class_labels,
"image_id": image_id,
"area": area,
'iscrowd': iscrowd
}
return img, target
def __len__(self):
return len(self.imgs)
if __name__ == '__main__':
unnorm = UnNormalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))
transform = get_transform(train=True)
dataset = DbdImageDataset('data/', transform)
# img = image_0.permute(1, 2, 0)
# visualize(unnorm(img), target_0['boxes'], target_0['labels'].tolist())
data_loader = DataLoader(
dataset, batch_size=1, shuffle=True, num_workers=4,
collate_fn=collate_fn)
for image, target in data_loader:
images = list(image for image in image)
targets = [{k: v for k, v in t.items()} for t in target]
print(targets)
image_0, target_0 = images[0], targets[0]
image_0 = image_0.permute(1, 2, 0)
visualize(unnorm(image_0), target_0['boxes'], target_0['labels'].tolist())