-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathtransforms.py
375 lines (294 loc) · 12 KB
/
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
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
364
365
366
367
368
369
370
371
372
373
374
375
import torch
import torchvision
import numpy as np
import PIL
import collections
import random
import cv2
import os
__all__ = ['VideoFilePathToTensor', 'VideoFolderPathToTensor', 'VideoResize', 'VideoRandomCrop', 'VideoCenterCrop', 'VideoRandomHorizontalFlip',
'VideoRandomVerticalFlip', 'VideoGrayscale']
class VideoFilePathToTensor(object):
""" load video at given file path to torch.Tensor (C x L x H x W, C = 3)
It can be composed with torchvision.transforms.Compose().
Args:
max_len (int): Maximum output time depth (L <= max_len). Default is None.
If it is set to None, it will output all frames.
fps (int): sample frame per seconds. It must lower than or equal the origin video fps.
Default is None.
padding_mode (str): Type of padding. Default to None. Only available when max_len is not None.
- None: won't padding, video length is variable.
- 'zero': padding the rest empty frames to zeros.
- 'last': padding the rest empty frames to the last frame.
"""
def __init__(self, max_len=None, fps=None, padding_mode=None):
self.max_len = max_len
self.fps = fps
assert padding_mode in (None, 'zero', 'last')
self.padding_mode = padding_mode
self.channels = 3 # only available to read 3 channels video
def __call__(self, path):
"""
Args:
path (str): path of video file.
Returns:
torch.Tensor: Video Tensor (C x L x H x W)
"""
# open video file
cap = cv2.VideoCapture(path)
assert(cap.isOpened())
# calculate sample_factor to reset fps
sample_factor = 1
if self.fps:
old_fps = cap.get(cv2.CAP_PROP_FPS) # fps of video
sample_factor = int(old_fps / self.fps)
assert(sample_factor >= 1)
# init empty output frames (C x L x H x W)
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
time_len = None
if self.max_len:
# time length has upper bound
if self.padding_mode:
# padding all video to the same time length
time_len = self.max_len
else:
# video have variable time length
time_len = min(int(num_frames / sample_factor), self.max_len)
else:
# time length is unlimited
time_len = int(num_frames / sample_factor)
frames = torch.FloatTensor(self.channels, time_len, height, width)
for index in range(time_len):
frame_index = sample_factor * index
# read frame
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_index)
ret, frame = cap.read()
if ret:
# successfully read frame
# BGR to RGB
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = torch.from_numpy(frame)
# (H x W x C) to (C x H x W)
frame = frame.permute(2, 0, 1)
frames[:, index, :, :] = frame.float()
else:
# reach the end of the video
if self.padding_mode == 'zero':
# fill the rest frames with 0.0
frames[:, index:, :, :] = 0
elif self.padding_mode == 'last':
# fill the rest frames with the last frame
assert(index > 0)
frames[:, index:, :, :] = frames[:, index-1, :, :].view(self.channels, 1, height, width)
break
frames /= 255
cap.release()
return frames
class VideoFolderPathToTensor(object):
""" load video at given folder path to torch.Tensor (C x L x H x W)
It can be composed with torchvision.transforms.Compose().
Args:
max_len (int): Maximum output time depth (L <= max_len). Default is None.
If it is set to None, it will output all frames.
padding_mode (str): Type of padding. Default to None. Only available when max_len is not None.
- None: won't padding, video length is variable.
- 'zero': padding the rest empty frames to zeros.
- 'last': padding the rest empty frames to the last frame.
"""
def __init__(self, max_len=None, padding_mode=None):
self.max_len = max_len
assert padding_mode in (None, 'zero', 'last')
self.padding_mode = padding_mode
def __call__(self, path):
"""
Args:
path (str): path of video folder.
Returns:
torch.Tensor: Video Tensor (C x L x H x W)
"""
# get video properity
frames_path = sorted([os.path.join(path,f) for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))])
frame = cv2.imread(frames_path[0])
height, width, channels = frame.shape
num_frames = len(frames_path)
# init empty output frames (C x L x H x W)
time_len = None
if self.max_len:
# time length has upper bound
if self.padding_mode:
# padding all video to the same time length
time_len = self.max_len
else:
# video have variable time length
time_len = min(num_frames, self.max_len)
else:
# time length is unlimited
time_len = num_frames
frames = torch.FloatTensor(channels, time_len, height, width)
# load the video to tensor
for index in range(time_len):
if index < num_frames:
# frame exists
# read frame
frame = cv2.imread(frames_path[index])
# BGR to RGB
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = torch.from_numpy(frame)
# (H x W x C) to (C x H x W)
frame = frame.permute(2, 0, 1)
frames[:, index, :, :] = frame.float()
else:
# reach the end of the video
if self.padding_mode == 'zero':
# fill the rest frames with 0.0
frames[:, index:, :, :] = 0
elif self.padding_mode == 'last':
# fill the rest frames with the last frame
assert(index > 0)
frames[:, index:, :, :] = frames[:, index-1, :, :].view(channels, 1, height, width)
break
frames /= 255
return frames
class VideoResize(object):
""" resize video tensor (C x L x H x W) to (C x L x h x w)
Args:
size (sequence): Desired output size. size is a sequence like (H, W),
output size will matched to this.
interpolation (int, optional): Desired interpolation. Default is 'PIL.Image.BILINEAR'
"""
def __init__(self, size, interpolation=PIL.Image.BILINEAR):
assert isinstance(size, collections.Iterable) and len(size) == 2
self.size = size
self.interpolation = interpolation
def __call__(self, video):
"""
Args:
video (torch.Tensor): Video to be scaled (C x L x H x W)
Returns:
torch.Tensor: Rescaled video (C x L x h x w)
"""
h, w = self.size
C, L, H, W = video.size()
rescaled_video = torch.FloatTensor(C, L, h, w)
# use torchvision implemention to resize video frames
transform = torchvision.transforms.Compose([
torchvision.transforms.ToPILImage(),
torchvision.transforms.Resize(self.size, self.interpolation),
torchvision.transforms.ToTensor(),
])
for l in range(L):
frame = video[:, l, :, :]
frame = transform(frame)
rescaled_video[:, l, :, :] = frame
return rescaled_video
def __repr__(self):
return self.__class__.__name__ + '(size={0})'.format(self.size)
class VideoRandomCrop(object):
""" Crop the given Video Tensor (C x L x H x W) at a random location.
Args:
size (sequence): Desired output size like (h, w).
"""
def __init__(self, size):
assert len(size) == 2
self.size = size
def __call__(self, video):
"""
Args:
video (torch.Tensor): Video (C x L x H x W) to be cropped.
Returns:
torch.Tensor: Cropped video (C x L x h x w).
"""
H, W = video.size()[2:]
h, w = self.size
assert H >= h and W >= w
top = np.random.randint(0, H - h)
left = np.random.randint(0, W - w)
video = video[:, :, top : top + h, left : left + w]
return video
class VideoCenterCrop(object):
""" Crops the given video tensor (C x L x H x W) at the center.
Args:
size (sequence): Desired output size of the crop like (h, w).
"""
def __init__(self, size):
self.size = size
def __call__(self, video):
"""
Args:
video (torch.Tensor): Video (C x L x H x W) to be cropped.
Returns:
torch.Tensor: Cropped Video (C x L x h x w).
"""
H, W = video.size()[2:]
h, w = self.size
assert H >= h and W >= w
top = int((H - h) / 2)
left = int((W - w) / 2)
video = video[:, :, top : top + h, left : left + w]
return video
class VideoRandomHorizontalFlip(object):
""" Horizontal flip the given video tensor (C x L x H x W) randomly with a given probability.
Args:
p (float): probability of the video being flipped. Default value is 0.5.
"""
def __init__(self, p=0.5):
self.p = p
def __call__(self, video):
"""
Args:
video (torch.Tensor): Video to flipped.
Returns:
torch.Tensor: Randomly flipped video.
"""
if random.random() < self.p:
# horizontal flip the video
video = video.flip([3])
return video
class VideoRandomVerticalFlip(object):
""" Vertical flip the given video tensor (C x L x H x W) randomly with a given probability.
Args:
p (float): probability of the video being flipped. Default value is 0.5.
"""
def __init__(self, p=0.5):
self.p = p
def __call__(self, video):
"""
Args:
video (torch.Tensor): Video to flipped.
Returns:
torch.Tensor: Randomly flipped video.
"""
if random.random() < self.p:
# horizontal flip the video
video = video.flip([2])
return video
class VideoGrayscale(object):
""" Convert video (C x L x H x W) to grayscale (C' x L x H x W, C' = 1 or 3)
Args:
num_output_channels (int): (1 or 3) number of channels desired for output video
"""
def __init__(self, num_output_channels=1):
assert num_output_channels in (1, 3)
self.num_output_channels = num_output_channels
def __call__(self, video):
"""
Args:
video (torch.Tensor): Video (3 x L x H x W) to be converted to grayscale.
Returns:
torch.Tensor: Grayscaled video (1 x L x H x W or 3 x L x H x W)
"""
C, L, H, W = video.size()
grayscaled_video = torch.FloatTensor(self.num_output_channels, L, H, W)
# use torchvision implemention to convert video frames to gray scale
transform = torchvision.transforms.Compose([
torchvision.transforms.ToPILImage(),
torchvision.transforms.Grayscale(self.num_output_channels),
torchvision.transforms.ToTensor(),
])
for l in range(L):
frame = video[:, l, :, :]
frame = transform(frame)
grayscaled_video[:, l, :, :] = frame
return grayscaled_video