File size: 6,057 Bytes
f9561b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import random
import math
import numpy as np
import torch
from torch.nn import functional as F


class SceneMaskGenerator:
    def __init__(
        self,
        input_size,
        min_num_patches=16,
        max_num_patches_ratio=0.5,
        min_aspect=0.3,
    ):
        if not isinstance(input_size, tuple):
            input_size = (input_size,) * 2
        self.input_size = input_size
        self.num_patches = input_size[0] * input_size[1]

        self.min_num_patches = min_num_patches
        self.max_num_patches = max_num_patches_ratio * self.num_patches

        self.log_aspect_ratio = (math.log(min_aspect), -math.log(min_aspect))

    def _mask(self, mask, max_mask_patches):
        delta = 0
        for _ in range(4):
            target_area = random.uniform(self.min_num_patches, max_mask_patches)
            aspect_ratio = math.exp(random.uniform(*self.log_aspect_ratio))
            h = int(round(math.sqrt(target_area * aspect_ratio)))
            w = int(round(math.sqrt(target_area / aspect_ratio)))
            height, width = self.input_size
            if w < width and h < height:
                top = random.randint(0, height - h)
                left = random.randint(0, width - w)

                num_masked = mask[top : top + h, left : left + w].sum()
                # Overlap
                if 0 < h * w - num_masked <= max_mask_patches:
                    mask[top : top + h, left : left + w] = 1
                    delta = h * w - num_masked
                    break
        return delta

    def __call__(self, head_mask):
        mask = np.zeros(shape=self.input_size, dtype=bool)
        mask_count = 0
        num_masking_patches = random.uniform(self.min_num_patches, self.max_num_patches)
        while mask_count < num_masking_patches:
            max_mask_patches = num_masking_patches - mask_count
            delta = self._mask(mask, max_mask_patches)
            if delta == 0:
                break
            else:
                mask_count += delta

        mask = torch.from_numpy(mask).unsqueeze(0)
        head_mask = (
            F.interpolate(head_mask.unsqueeze(0), mask.shape[-2:]).squeeze(0) < 0.5
        )
        return torch.logical_and(mask, head_mask).squeeze(0)


class HeadMaskGenerator:
    def __init__(
        self,
        input_size,
        min_num_patches=4,
        max_num_patches_ratio=0.5,
        min_aspect=0.3,
    ):
        if not isinstance(input_size, tuple):
            input_size = (input_size,) * 2
        self.input_size = input_size
        self.num_patches = input_size[0] * input_size[1]

        self.min_num_patches = min_num_patches
        self.max_num_patches_ratio = max_num_patches_ratio

        self.log_aspect_ratio = (math.log(min_aspect), -math.log(min_aspect))

    def __call__(
        self,
        x_min,
        y_min,
        x_max,
        y_max,  # coords in [0,1]
    ):
        height = math.floor((y_max - y_min) * self.input_size[0])
        width = math.floor((x_max - x_min) * self.input_size[1])
        origin_area = width * height
        if origin_area < self.min_num_patches:
            return torch.zeros(size=self.input_size, dtype=bool)

        target_area = random.uniform(
            self.min_num_patches, self.max_num_patches_ratio * origin_area
        )
        aspect_ratio = math.exp(random.uniform(*self.log_aspect_ratio))
        h = min(int(round(math.sqrt(target_area * aspect_ratio))), height)
        w = min(int(round(math.sqrt(target_area / aspect_ratio))), width)
        top = random.randint(0, height - h) + int(y_min * self.input_size[0])
        left = random.randint(0, width - w) + int(x_min * self.input_size[1])
        mask = torch.zeros(size=self.input_size, dtype=bool)
        mask[top : top + h, left : left + w] = True
        return mask


class MaskGenerator:
    def __init__(
        self,
        input_size,
        mask_scene: bool = False,
        mask_head: bool = False,
        min_scene_patches=16,
        max_scene_patches_ratio=0.5,
        min_head_patches=4,
        max_head_patches_ratio=0.5,
        min_aspect=0.3,
        mask_prob=0.2,
        head_prob=0.2,
    ):
        if not isinstance(input_size, tuple):
            input_size = (input_size,) * 2
        self.input_size = input_size
        if mask_scene:
            self.scene_mask_generator = SceneMaskGenerator(
                input_size, min_scene_patches, max_scene_patches_ratio, min_aspect
            )
        else:
            self.scene_mask_generator = None

        if mask_head:
            self.head_mask_generator = HeadMaskGenerator(
                input_size, min_head_patches, max_head_patches_ratio, min_aspect
            )
        else:
            self.head_mask_generator = None

        self.no_mask = not (mask_scene or mask_head)
        self.mask_head = mask_head and not mask_scene
        self.mask_scene = mask_scene and not mask_head
        self.scene_prob = mask_prob
        self.head_prob = head_prob

    def __call__(
        self,
        x_min,
        y_min,
        x_max,
        y_max,
        head_mask,
    ):
        mask_scene = random.random() < self.scene_prob
        mask_head = random.random() < self.head_prob
        no_mask = (
            self.no_mask
            or (self.mask_head and not mask_head)
            or (self.mask_scene and not mask_scene)
            or not (mask_scene or mask_head)
        )
        if no_mask:
            return torch.zeros(size=self.input_size, dtype=bool)
        if self.mask_scene:
            return self.scene_mask_generator(head_mask)
        if self.mask_head:
            return self.head_mask_generator(x_min, y_min, x_max, y_max)
        if mask_head and mask_scene:
            return torch.logical_or(
                self.scene_mask_generator(head_mask),
                self.head_mask_generator(x_min, y_min, x_max, y_max),
            )
        elif mask_head:
            return self.head_mask_generator(x_min, y_min, x_max, y_max)
        return self.scene_mask_generator(head_mask)