-
Notifications
You must be signed in to change notification settings - Fork 71
/
TransformLayer.py
200 lines (172 loc) · 7.48 KB
/
TransformLayer.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
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
import numbers
import random
import time
def rgb2hsv(rgb, eps=1e-8):
# Reference: https://www.rapidtables.com/convert/color/rgb-to-hsv.html
# Reference: https://github.com/scikit-image/scikit-image/blob/master/skimage/color/colorconv.py#L287
_device = rgb.device
r, g, b = rgb[:, 0, :, :], rgb[:, 1, :, :], rgb[:, 2, :, :]
Cmax = rgb.max(1)[0]
Cmin = rgb.min(1)[0]
delta = Cmax - Cmin
hue = torch.zeros((rgb.shape[0], rgb.shape[2], rgb.shape[3])).to(_device)
hue[Cmax== r] = (((g - b)/(delta + eps)) % 6)[Cmax == r]
hue[Cmax == g] = ((b - r)/(delta + eps) + 2)[Cmax == g]
hue[Cmax == b] = ((r - g)/(delta + eps) + 4)[Cmax == b]
hue[Cmax == 0] = 0.0
hue = hue / 6. # making hue range as [0, 1.0)
hue = hue.unsqueeze(dim=1)
saturation = (delta) / (Cmax + eps)
saturation[Cmax == 0.] = 0.
saturation = saturation.to(_device)
saturation = saturation.unsqueeze(dim=1)
value = Cmax
value = value.to(_device)
value = value.unsqueeze(dim=1)
return torch.cat((hue, saturation, value), dim=1)#.type(torch.FloatTensor).to(_device)
# return hue, saturation, value
def hsv2rgb(hsv):
# Reference: https://www.rapidtables.com/convert/color/hsv-to-rgb.html
# Reference: https://github.com/scikit-image/scikit-image/blob/master/skimage/color/colorconv.py#L287
_device = hsv.device
hsv = torch.clamp(hsv, 0, 1)
hue = hsv[:, 0, :, :] * 360.
saturation = hsv[:, 1, :, :]
value = hsv[:, 2, :, :]
c = value * saturation
x = - c * (torch.abs((hue / 60.) % 2 - 1) - 1)
m = (value - c).unsqueeze(dim=1)
rgb_prime = torch.zeros_like(hsv).to(_device)
inds = (hue < 60) * (hue >= 0)
rgb_prime[:, 0, :, :][inds] = c[inds]
rgb_prime[:, 1, :, :][inds] = x[inds]
inds = (hue < 120) * (hue >= 60)
rgb_prime[:, 0, :, :][inds] = x[inds]
rgb_prime[:, 1, :, :][inds] = c[inds]
inds = (hue < 180) * (hue >= 120)
rgb_prime[:, 1, :, :][inds] = c[inds]
rgb_prime[:, 2, :, :][inds] = x[inds]
inds = (hue < 240) * (hue >= 180)
rgb_prime[:, 1, :, :][inds] = x[inds]
rgb_prime[:, 2, :, :][inds] = c[inds]
inds = (hue < 300) * (hue >= 240)
rgb_prime[:, 2, :, :][inds] = c[inds]
rgb_prime[:, 0, :, :][inds] = x[inds]
inds = (hue < 360) * (hue >= 300)
rgb_prime[:, 2, :, :][inds] = x[inds]
rgb_prime[:, 0, :, :][inds] = c[inds]
rgb = rgb_prime + torch.cat((m, m, m), dim=1)
rgb = rgb.to(_device)
return torch.clamp(rgb, 0, 1)
class ColorJitterLayer(nn.Module):
def __init__(self, brightness=0, contrast=0, saturation=0, hue=0, p=0, batch_size=128, stack_size=3):
super(ColorJitterLayer, self).__init__()
self.brightness = self._check_input(brightness, 'brightness')
self.contrast = self._check_input(contrast, 'contrast')
self.saturation = self._check_input(saturation, 'saturation')
self.hue = self._check_input(hue, 'hue', center=0, bound=(-0.5, 0.5),
clip_first_on_zero=False)
self.prob = p
self.batch_size = batch_size
self.stack_size = stack_size
def _check_input(self, value, name, center=1, bound=(0, float('inf')), clip_first_on_zero=True):
if isinstance(value, numbers.Number):
if value < 0:
raise ValueError("If {} is a single number, it must be non negative.".format(name))
value = [center - value, center + value]
if clip_first_on_zero:
value[0] = max(value[0], 0)
elif isinstance(value, (tuple, list)) and len(value) == 2:
if not bound[0] <= value[0] <= value[1] <= bound[1]:
raise ValueError("{} values should be between {}".format(name, bound))
else:
raise TypeError("{} should be a single number or a list/tuple with lenght 2.".format(name))
# if value is 0 or (1., 1.) for brightness/contrast/saturation
# or (0., 0.) for hue, do nothing
if value[0] == value[1] == center:
value = None
return value
def adjust_contrast(self, x):
"""
Args:
x: torch tensor img (rgb type)
Factor: torch tensor with same length as x
0 gives gray solid image, 1 gives original image,
Returns:
torch tensor image: Brightness adjusted
"""
_device = x.device
factor = torch.empty(self.batch_size, device=_device).uniform_(*self.contrast)
factor = factor.reshape(-1,1).repeat(1, self.stack_size).reshape(-1)
means = torch.mean(x, dim=(2, 3), keepdim=True)
return torch.clamp((x - means)
* factor.view(len(x), 1, 1, 1) + means, 0, 1)
def adjust_hue(self, x):
_device = x.device
factor = torch.empty(self.batch_size, device=_device).uniform_(*self.hue)
factor = factor.reshape(-1,1).repeat(1, self.stack_size).reshape(-1)
h = x[:, 0, :, :]
h += (factor.view(len(x), 1, 1) * 255. / 360.)
h = (h % 1)
x[:, 0, :, :] = h
return x
def adjust_brightness(self, x):
"""
Args:
x: torch tensor img (hsv type)
Factor:
torch tensor with same length as x
0 gives black image, 1 gives original image,
2 gives the brightness factor of 2.
Returns:
torch tensor image: Brightness adjusted
"""
_device = x.device
factor = torch.empty(self.batch_size, device=_device).uniform_(*self.brightness)
factor = factor.reshape(-1,1).repeat(1, self.stack_size).reshape(-1)
x[:, 2, :, :] = torch.clamp(x[:, 2, :, :]
* factor.view(len(x), 1, 1), 0, 1)
return torch.clamp(x, 0, 1)
def adjust_saturate(self, x):
"""
Args:
x: torch tensor img (hsv type)
Factor:
torch tensor with same length as x
0 gives black image and white, 1 gives original image,
2 gives the brightness factor of 2.
Returns:
torch tensor image: Brightness adjusted
"""
_device = x.device
factor = torch.empty(self.batch_size, device=_device).uniform_(*self.saturation)
factor = factor.reshape(-1,1).repeat(1, self.stack_size).reshape(-1)
x[:, 1, :, :] = torch.clamp(x[:, 1, :, :]
* factor.view(len(x), 1, 1), 0, 1)
return torch.clamp(x, 0, 1)
def transform(self, inputs):
hsv_transform_list = [rgb2hsv, self.adjust_brightness,
self.adjust_hue, self.adjust_saturate,
hsv2rgb]
rgb_transform_list = [self.adjust_contrast]
# Shuffle transform
if random.uniform(0,1) >= 0.5:
transform_list = rgb_transform_list + hsv_transform_list
else:
transform_list = hsv_transform_list + rgb_transform_list
for t in transform_list:
inputs = t(inputs)
return inputs
def forward(self, inputs):
_device = inputs.device
random_inds = np.random.choice(
[True, False], len(inputs), p=[self.prob, 1 - self.prob])
inds = torch.tensor(random_inds).to(_device)
if random_inds.sum() > 0:
inputs[inds] = self.transform(inputs[inds])
return inputs