-
Notifications
You must be signed in to change notification settings - Fork 19
/
data_transforms.py
327 lines (271 loc) · 10.7 KB
/
data_transforms.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
import random
import numpy as np
from PIL import Image
import torch
class Normalize(object):
"""Given mean: (R, G, B) and std: (R, G, B),
will normalize each channel of the torch.*Tensor, i.e.
channel = (channel - mean) / std
"""
def __init__(self, mean, std):
self.mean = torch.FloatTensor(mean)
self.std = torch.FloatTensor(std)
def __call__(self, image, labels=None):
if image.device.type != 'cpu':
means = [self.mean] * image.size()[0]
stds = [self.std] * image.size()[0]
for t, m, s in zip(image, means, stds):
t.sub_(m[:, None, None].cuda()).div_(s[:, None, None].cuda())
else:
for t, m, s in zip(image, self.mean, self.std):
t.sub_(m).div_(s)
if labels is None:
return image
else:
# final return should be a tuple
return tuple([image] + list(labels))
def pad_reflection(image, top, bottom, left, right):
if top == 0 and bottom == 0 and left == 0 and right == 0:
return image
h, w = image.shape[:2]
next_top = next_bottom = next_left = next_right = 0
if top > h - 1:
next_top = top - h + 1
top = h - 1
if bottom > h - 1:
next_bottom = bottom - h + 1
bottom = h - 1
if left > w - 1:
next_left = left - w + 1
left = w - 1
if right > w - 1:
next_right = right - w + 1
right = w - 1
new_shape = list(image.shape)
new_shape[0] += top + bottom
new_shape[1] += left + right
new_image = np.empty(new_shape, dtype=image.dtype)
new_image[top:top+h, left:left+w] = image
new_image[:top, left:left+w] = image[top:0:-1, :]
new_image[top+h:, left:left+w] = image[-1:-bottom-1:-1, :]
new_image[:, :left] = new_image[:, left*2:left:-1]
new_image[:, left+w:] = new_image[:, -right-1:-right*2-1:-1]
return pad_reflection(new_image, next_top, next_bottom,
next_left, next_right)
def pad_constant(image, top, bottom, left, right, value):
if top == 0 and bottom == 0 and left == 0 and right == 0:
return image
h, w = image.shape[:2]
new_shape = list(image.shape)
new_shape[0] += top + bottom
new_shape[1] += left + right
new_image = np.empty(new_shape, dtype=image.dtype)
new_image.fill(value)
new_image[top:top + h, left:left + w] = image
return new_image
def pad_image(mode, image, top, bottom, left, right, value=0):
if mode == 'reflection':
if type(image) == np.ndarray:
return pad_reflection(np.asarray(image), top, bottom, left, right)
else:
return Image.fromarray(
pad_reflection(np.asarray(image), top, bottom, left, right))
elif mode == 'constant':
if type(image) == np.ndarray:
return pad_constant(np.asarray(image), top, bottom, left, right, value)
else:
return Image.fromarray(
pad_constant(np.asarray(image), top, bottom, left, right, value))
else:
raise ValueError('Unknown mode {}'.format(mode))
def get_random_crop(data, tw, th):
top = bottom = left = right = 0
w, h = data[0].data.size
if w < tw:
left = (tw - w) // 2
right = tw - w - left
if h < th:
top = (th - h) // 2
bottom = th - h - top
if left > 0 or right > 0 or top > 0 or bottom > 0:
data[0].data = pad_image('reflection', data[0].data, top, bottom, left, right)
for i, mode in enumerate(data[1:]):
if mode is not None:
data[i + 1].data = pad_image('constant', data[i + 1].data, top, bottom, left, right, value=0)
w, h = data[0].data.size
if w == tw and h == th:
# should happen after above when image is smaller than crop size
return data
# crop next to objects
[y_mask, x_mask] = np.where(data[1].data == 1)
right_bb = np.max(x_mask)
left_bb = np.min(x_mask)
top_bb = np.min(y_mask)
bottom_bb = np.max(y_mask)
x_c = int(0.5 * (right_bb + left_bb))
y_c = int(0.5 * (bottom_bb + top_bb))
delta_x = np.max(x_mask) - np.min(x_mask)
delta_y = np.max(y_mask) - np.min(y_mask)
x_min = max(0, x_c - int(0.5 * (delta_x + tw)))
x_max = max(0, min(w - tw, x_c + int(0.5 * (delta_x - tw))))
y_min = max(0, y_c - int(0.5 * (delta_y + th)))
y_max = max(0, min(h - th, y_c + int(0.5 * (delta_y - th))))
if x_min > x_max:
x1 = random.randint(0, x_max)
else:
x1 = random.randint(x_min, x_max)
if y_min > y_max:
y1 = random.randint(0, y_max)
else:
y1 = random.randint(y_min, y_max)
data[0].crop(x1, y1, tw, th)
for i, mode in enumerate(data[1:]):
if mode is not None:
data[i + 1].data = data[i + 1].data[y1:y1+th, x1:x1+tw]
return data
def pad_reflection(image, top, bottom, left, right):
if top == 0 and bottom == 0 and left == 0 and right == 0:
return image
h, w = image.shape[:2]
next_top = next_bottom = next_left = next_right = 0
if top > h - 1:
next_top = top - h + 1
top = h - 1
if bottom > h - 1:
next_bottom = bottom - h + 1
bottom = h - 1
if left > w - 1:
next_left = left - w + 1
left = w - 1
if right > w - 1:
next_right = right - w + 1
right = w - 1
new_shape = list(image.shape)
new_shape[0] += top + bottom
new_shape[1] += left + right
new_image = np.empty(new_shape, dtype=image.dtype)
new_image[top:top+h, left:left+w] = image
new_image[:top, left:left+w] = image[top:0:-1, :]
new_image[top+h:, left:left+w] = image[-1:-bottom-1:-1, :]
new_image[:, :left] = new_image[:, left*2:left:-1]
new_image[:, left+w:] = new_image[:, -right-1:-right*2-1:-1]
return pad_reflection(new_image, next_top, next_bottom,
next_left, next_right)
def pad_constant(image, top, bottom, left, right, value):
if top == 0 and bottom == 0 and left == 0 and right == 0:
return image
h, w = image.shape[:2]
new_shape = list(image.shape)
new_shape[0] += top + bottom
new_shape[1] += left + right
new_image = np.empty(new_shape, dtype=image.dtype)
new_image.fill(value)
new_image[top:top + h, left:left + w] = image
return new_image
def pad_image(mode, image, top, bottom, left, right, value=0):
if mode == 'reflection':
if type(image) == np.ndarray:
return pad_reflection(np.asarray(image), top, bottom, left, right)
else:
return Image.fromarray(
pad_reflection(np.asarray(image), top, bottom, left, right))
elif mode == 'constant':
if type(image) == np.ndarray:
return pad_constant(np.asarray(image), top, bottom, left, right, value)
else:
return Image.fromarray(
pad_constant(np.asarray(image), top, bottom, left, right, value))
else:
raise ValueError('Unknown mode {}'.format(mode))
def get_random_bbox(data, tw, th):
top = bottom = left = right = 0
w, h = data[0].data.size
if w < tw:
left = (tw - w) // 2
right = tw - w - left
if h < th:
top = (th - h) // 2
bottom = th - h - top
if left > 0 or right > 0 or top > 0 or bottom > 0:
data[0].data = pad_image('reflection', data[0].data, top, bottom, left, right)
for i, mode in enumerate(data[1:]):
data[i + 1].data = pad_image('constant', data[i + 1].data, top, bottom, left, right, value=0)
w, h = data[0].data.size
if w == tw and h == th:
# should happen after above when image is smaller than crop size
return (0, 0, w, h)
# crop next to objects
[y_mask, x_mask] = np.where(data[1].data == 1)
right_bb = np.max(x_mask)
left_bb = np.min(x_mask)
top_bb = np.min(y_mask)
bottom_bb = np.max(y_mask)
x_c = int(0.5 * (right_bb + left_bb))
y_c = int(0.5 * (bottom_bb + top_bb))
delta_x = np.max(x_mask) - np.min(x_mask)
delta_y = np.max(y_mask) - np.min(y_mask)
x_min = max(0, x_c - int(0.5 * (delta_x + tw)))
x_max = max(0, min(w - tw, x_c + int(0.5 * (delta_x - tw))))
y_min = max(0, y_c - int(0.5 * (delta_y + th)))
y_max = max(0, min(h - th, y_c + int(0.5 * (delta_y - th))))
if x_min > x_max:
x1 = random.randint(0, x_max)
else:
x1 = random.randint(x_min, x_max)
if y_min > y_max:
y1 = random.randint(0, y_max)
else:
y1 = random.randint(y_min, y_max)
return (x1, y1, tw, th)
class ToTensor(object):
"""Converts a PIL.Image or numpy.ndarray (H x W x C) in the range
[0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0].
"""
def __call__(self, pic, labels=None):
if isinstance(pic, np.ndarray):
# handle numpy array
img = torch.from_numpy(pic)
else:
# handle PIL Image
img = torch.ByteTensor(torch.ByteStorage.from_buffer(pic.tobytes()))
# PIL image mode: 1, L, P, I, F, RGB, YCbCr, RGBA, CMYK
if pic.mode == 'YCbCr':
nchannel = 3
else:
nchannel = len(pic.mode)
img = img.view(pic.size[1], pic.size[0], nchannel)
# put it from HWC to CHW format
# yikes, this transpose takes 80% of the loading time/CPU
img = img.transpose(0, 1).transpose(0, 2).contiguous()
img = img.float().div(255)
if labels is None:
return [img]
else:
for i, label in enumerate(labels):
# ground truth mask
if label is not None:
if i == 0:
if len(label.shape) == 3:
# case with two masks
labels[i] = torch.LongTensor(np.array(label.swapaxes(1, 2).swapaxes(0, 1), dtype=np.int))
else:
labels[i] = torch.LongTensor(np.array(label, dtype=np.int))
else:
if len(label.shape) == 3:
labels[i] = torch.FloatTensor(
np.array(label.swapaxes(1, 2).swapaxes(0, 1), dtype=np.float32))
else:
# depth, boundaries_out, orientations
labels[i] = torch.FloatTensor(np.array(label, dtype=np.float32))
labels = [label for label in labels if label is not None]
return img, labels
class Compose(object):
"""Composes several transforms together.
"""
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, *args):
for t in self.transforms:
# if not isinstance(t, RandomHorizontalFlip):
args = t(*args)
return args