File size: 2,233 Bytes
54d2b91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Video-level transforms. Apply per-clip, consistent across frames."""
from __future__ import annotations

import random

import torch
import torch.nn.functional as F


_IMAGENET_MEAN = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
_IMAGENET_STD = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)


class VideoTransform:
    """All ops act on a (T, 3, H, W) float tensor in [0,1]."""

    def __init__(self, aug_cfg, training: bool):
        self.training = training
        self.flip_p = aug_cfg.horizontal_flip if training else 0.0
        self.cj_b = aug_cfg.color_jitter.brightness if training else 0.0
        self.cj_c = aug_cfg.color_jitter.contrast if training else 0.0
        self.cj_s = aug_cfg.color_jitter.saturation if training else 0.0
        self.crop_scale = tuple(aug_cfg.random_crop_scale) if training else (1.0, 1.0)

    def __call__(self, video: torch.Tensor) -> torch.Tensor:
        T, C, H, W = video.shape

        # horizontal flip (consistent)
        if random.random() < self.flip_p:
            video = torch.flip(video, dims=[-1])

        # random crop then resize
        sc = random.uniform(*self.crop_scale)
        if sc < 1.0:
            ch, cw = int(H * sc), int(W * sc)
            top = random.randint(0, H - ch)
            left = random.randint(0, W - cw)
            video = video[..., top:top + ch, left:left + cw]
            video = F.interpolate(video, size=(H, W), mode="bilinear", align_corners=False)

        # color jitter (consistent)
        if self.cj_b > 0:
            video = video * (1.0 + (random.random() * 2 - 1) * self.cj_b)
        if self.cj_c > 0:
            mean = video.mean(dim=[-1, -2], keepdim=True)
            video = mean + (video - mean) * (1.0 + (random.random() * 2 - 1) * self.cj_c)
        if self.cj_s > 0:
            gray = video.mean(dim=1, keepdim=True)
            video = gray + (video - gray) * (1.0 + (random.random() * 2 - 1) * self.cj_s)

        video = video.clamp(0, 1)

        # imagenet normalize
        video = (video - _IMAGENET_MEAN.to(video)) / _IMAGENET_STD.to(video)
        return video


def build_video_transform(aug_cfg, training: bool) -> VideoTransform:
    return VideoTransform(aug_cfg, training=training)