[d9566e]: / sybil / augmentations.py

Download this file

232 lines (182 with data), 6.8 kB

  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
import cv2
import torch
import torchvision
from typing import Literal
from abc import ABCMeta, abstractmethod
import numpy as np
import random
try:
import albumentations as A
except ImportError:
# albumentations is not installed, training with augmentations will not be possible
A = None
def get_augmentations(split: Literal["train", "dev", "test"], args):
if split == "train":
augmentations = [
Scale_2d(args, {}),
Rotate_Range(args, {"deg": 20}),
ToTensor(),
Force_Num_Chan_Tensor_2d(args, {}),
Normalize_Tensor_2d(args, {}),
]
else:
augmentations = [
Scale_2d(args, {}),
ToTensor(),
Force_Num_Chan_Tensor_2d(args, {}),
Normalize_Tensor_2d(args, {}),
]
return augmentations
class Abstract_augmentation(object):
"""
Abstract-transformer.
Default - non cachable
"""
__metaclass__ = ABCMeta
def __init__(self):
self._is_cachable = False
self._trans_sep = "@"
self._attr_sep = "#"
self.name = (
self.__str__().split("sybil.augmentations.")[-1].split(" ")[0].lower()
)
@abstractmethod
def __call__(self, input_dict):
pass
def set_seed(self, seed):
random.seed(seed)
np.random.seed(seed)
torch.random.manual_seed(seed)
def cachable(self):
return self._is_cachable
def set_cachable(self, *keys):
"""
Sets the transformer as cachable
and sets the _caching_keys according to the input variables.
"""
self._is_cachable = True
name_str = "{}{}".format(self._trans_sep, self.name)
keys_str = "".join(self._attr_sep + str(k) for k in keys)
self._caching_keys = "{}{}".format(name_str, keys_str)
return
def caching_keys(self):
return self._caching_keys
class ComposeAug(Abstract_augmentation):
"""
Composes multiple augmentations
"""
def __init__(self, augmentations):
super(ComposeAug, self).__init__()
self.augmentations = augmentations
def __call__(self, input_dict, sample=None):
for transformer in self.augmentations:
input_dict = transformer(input_dict, sample)
return input_dict
class ToTensor(Abstract_augmentation):
"""
torchvision.transforms.ToTensor wrapper.
"""
def __init__(self):
super(ToTensor, self).__init__()
self.name = "totensor"
def __call__(self, input_dict, sample=None):
input_dict["input"] = torch.from_numpy(input_dict["input"]).float()
if input_dict.get("mask", None) is not None:
input_dict["mask"] = torch.from_numpy(input_dict["mask"]).float()
return input_dict
class ResizeTransform:
def __init__(self, width, height):
self.width = width
self.height = height
def __call__(self, image=None, mask=None):
out = {"image": None, "mask": None}
if image is not None:
out["image"] = cv2.resize(image, dsize=(self.width, self.height), interpolation=cv2.INTER_LINEAR)
if mask is not None:
out["mask"] = cv2.resize(mask, dsize=(self.width, self.height), interpolation=cv2.INTER_NEAREST)
return out
class Scale_2d(Abstract_augmentation):
"""
Given PIL image, enforce its some set size
(can use for down sampling / keep full res)
"""
def __init__(self, args, kwargs):
super(Scale_2d, self).__init__()
assert len(kwargs.keys()) == 0
width, height = args.img_size
self.set_cachable(width, height)
self.transform = ResizeTransform(width, height)
def __call__(self, input_dict, sample=None):
out = self.transform(
image=input_dict["input"], mask=input_dict.get("mask", None)
)
input_dict["input"] = out["image"]
input_dict["mask"] = out["mask"]
return input_dict
class Rotate_Range(Abstract_augmentation):
"""
Rotate image counter clockwise by random degree https://albumentations.ai/docs/api_reference/augmentations/geometric/rotate/#albumentations.augmentations.geometric.rotate.Rotate
kwargs
deg: max degrees to rotate
"""
def __init__(self, args, kwargs):
super(Rotate_Range, self).__init__()
assert len(kwargs.keys()) == 1
self.max_angle = int(kwargs["deg"])
assert A is not None, "albumentations is not installed"
self.transform = A.Rotate(limit=self.max_angle, p=0.5)
def __call__(self, input_dict, sample=None):
if sample and "seed" in sample:
self.set_seed(sample["seed"])
out = self.transform(
image=input_dict["input"], mask=input_dict.get("mask", None)
)
input_dict["input"] = out["image"]
input_dict["mask"] = out["mask"]
return input_dict
class Normalize_Tensor_2d(Abstract_augmentation):
"""
Normalizes input by channel
wrapper for torchvision.transforms.Normalize wrapper.
"""
def __init__(self, args, kwargs):
super(Normalize_Tensor_2d, self).__init__()
assert len(kwargs) == 0
channel_means = [args.img_mean] if len(args.img_mean) == 1 else args.img_mean
channel_stds = [args.img_std] if len(args.img_std) == 1 else args.img_std
self.transform = torchvision.transforms.Normalize(
torch.Tensor(channel_means), torch.Tensor(channel_stds)
)
self.permute = args.img_file_type in [
"png",
]
def __call__(self, input_dict, sample=None):
img = input_dict["input"]
if len(img.size()) == 2:
img = img.unsqueeze(0)
if self.permute:
img = img.permute(2, 0, 1)
input_dict["input"] = self.transform(img).permute(1, 2, 0)
else:
input_dict["input"] = self.transform(img)
return input_dict
class Force_Num_Chan_Tensor_2d(Abstract_augmentation):
"""
Convert gray scale images to image with args.num_chan num channels.
"""
def __init__(self, args, kwargs):
super(Force_Num_Chan_Tensor_2d, self).__init__()
assert len(kwargs) == 0
self.args = args
def __call__(self, input_dict, sample=None):
img = input_dict["input"]
mask = input_dict.get("mask", None)
if mask is not None:
input_dict["mask"] = mask.unsqueeze(0)
num_dims = len(img.shape)
if num_dims == 2:
img = img.unsqueeze(0)
existing_chan = img.size()[0]
if not existing_chan == self.args.num_chan:
input_dict["input"] = img.expand(self.args.num_chan, *img.size()[1:])
return input_dict