File size: 10,685 Bytes
b82b0e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d3adef
b82b0e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from typing import List, Union
from abc import ABC, abstractmethod

import numpy as np
from PIL import Image
from sklearn.datasets import make_s_curve, make_swiss_roll


class DataExpander(ABC):
    """Abstract class for data expander with different distribution."""
        
    @abstractmethod
    def expand_data(self, data: np.ndarray, size: int, **kwargs) -> np.ndarray:
        """Return the expanded data to size."""
        raise NotImplementedError
    
    @abstractmethod
    def available_data(self, data: np.ndarray, **kwargs) -> np.ndarray:
        """Return the available data."""
        raise NotImplementedError


class AnchorExpander(DataExpander):
    """Class for anchor expander with different distribution.
    
    Args:
        expand_type (str): expand type of the anchor distribution. Options include `duplicate` or `uniform` or `gauss`. Default: 'duplicate'.
    """
    
    def __init__(self, expand_type: str = 'duplicate'):
        self.expand_type = expand_type
        self.type_map = {
            'duplicate': self.duplicate,
            'uniform': self.uniform,
            'gauss': self.gauss,
        }

    def _get_anchor_number(self, anchors: np.ndarray):
        """Return the number of anchors."""
        assert anchors.ndim == 2 , "anchors should be 2D array."
        assert anchors.shape[1] == 2 or anchors.shape[1] == 4, "each anchor shaped as (cx, cy) or (cx, cy, w, h)."
        return anchors.shape[0]
    
    def expand_data(self, data: np.ndarray, size: int, **kwargs) -> np.ndarray:
        """Return the expanded data to size."""
        anchor_num = self._get_anchor_number(data) + 1
        expand_space = np.linspace(0, size, anchor_num).astype(int)
        expand_num = expand_space[1:] - expand_space[:-1]
        
        return self.type_map[self.expand_type](data, expand_num)
    
    def available_data(self, data: np.ndarray, type=np.float32, **kwargs) -> np.ndarray:
        """Return the available anchors ranged [0, 1] with type."""
        data[:, 0::2] = np.clip(data[:, 0::2], 0, 1)
        data[:, 1::2] = np.clip(data[:, 1::2], 0, 1)
        if data.dtype != type:
            data = data.astype(type)
        return data
    
    def duplicate(self, anchors: np.ndarray, expand_num: np.ndarray):
        """Duplicate each anchor form anchors to expand_num."""
        return anchors.repeat(expand_num, axis=0)
        
    def uniform(self, anchors: np.ndarray, expand_num: np.ndarray):
        """Uniformly expand each anchor form anchors to expand_num in anchor region."""
        assert anchors.shape[1] == 4, "Uniformly expand only support anchors shaped as (cx, cy, w, h)."
        new_anchors = []
        for n, (cx, cy, w, h) in zip(expand_num, anchors):
            lt = [cx - w / 2, cy - h / 2]
            rb = [cx + w / 2, cy + h / 2]
            new_anchors.append(np.random.uniform(lt, rb, (n, 2)))
        return np.concatenate(new_anchors, axis=0)
        
    def gauss(self, anchors: np.ndarray, expand_num: np.ndarray):
        """Gaussian expand each anchor form anchors to expand_num in anchor region."""
        assert anchors.shape[1] == 4, "Gaussian expand only support anchors shaped as (cx, cy, w, h)."
        new_anchors = []
        for n, (cx, cy, w, h) in zip(expand_num, anchors):
            new_anchors.append(np.random.multivariate_normal([cx, cy], [[w, 0], [0, h]], n))
        return np.concatenate(new_anchors, axis=0)


class DataDistributor(ABC):
    """Abstract class for data distributor."""
    
    @abstractmethod
    def get_distribution(self, data: np.ndarray, **kwargs):
        """Return the data distribution."""
        raise NotImplementedError


class AnchorDistributor(DataDistributor, AnchorExpander):
    """Abstract class for anchor distributor.
    
    Args:
        width (int): width of the distribution.
        height (int): height of the distribution.
        depth (int): depth of the distribution. Default: 1.
        expand_type (str): type of the anchor distribution. Options include `duplicate` or `uniform` or `gauss`. Default: 'duplicate'.
    """
    
    def __init__(self, width: int, height: int, depth: int = 1, 
                 expand_type: str = 'duplicate'):
        self.width = width
        self.height = height
        self.depth = depth
        AnchorExpander.__init__(self, expand_type)
    
    @property
    def dis_point_num(self):
        """Return the number of expanded distribution points."""
        return int(self.width * self.height)
    
    def get_distribution(self, data: np.ndarray, type: str = '1d',  **kwargs):
        """Return the anchor distribution."""
        if type == '1d':
            return self.to_1d_distribution(data)
        elif type == 'img':
            return self.to_img_distribution(data)
        else:
            raise ValueError(f"Unsupported distribute type {type}.")
    
    def to_1d_distribution(self, anchors: np.ndarray):
        """Return the 1D distribution of anchors shaped [NxD, *]."""
        anchors = np.repeat(anchors, self.depth, axis=0)
        return anchors
    
    def to_img_distribution(self, anchors: np.ndarray) -> Image.Image:
        """Return the Image filled distribution of anchors."""
        assert self.depth == 1 or self.depth == 3, "Only support depth 1 (GRAY) or 3(RGB)."
        img = filled_anchors(anchors, self.width, self.height)
        gray_img = Image.fromarray(img, mode='L')
        if self.depth == 1:
            return gray_img
        else:
            return gray_img.convert('RGB')


def filled_anchors(anchors: np.ndarray, width: int, height: int) -> np.ndarray:
    """Return the hist filled in distributed anchors' c_xy along (x,y) shaped [W, H]."""
    assert anchors.ndim == 2, "anchors should be 2D array."
    assert anchors.max() <= 1 and anchors.min() >= 0, "anchors should be ranged [0, 1]."
    
    anchor_cxcy = (anchors[:, :2] * np.array([width-1, height-1])).astype(int)
    anchor_unique, anchor_counts = np.unique(anchor_cxcy, axis=0, return_counts=True)
    anchor_counts = anchor_counts * 255.0 / anchor_counts.max()
    anchor_counts = anchor_counts.astype(int).clip(0, 255)
    anchor_index = anchor_unique[:, 1], anchor_unique[:, 0]
    hist = np.zeros((width, height), dtype=np.uint8)
    hist[anchor_index] = anchor_counts
    return hist


class CustomAnchorShape(AnchorDistributor):
    """Custom anchor shape distributor.
    
    Args:
        width (int): width of the distribution.
        height (int): height of the distribution.
        depth (int): depth of the distribution. Default: 1.
        custom_data (List[Union[np.ndarray, str]]): custom data to be added to the sample. Include `s_curve`, `swiss_roll` and `custom_anchor`.
        custom_anchor_combination (bool): whether to combine custom anchors.
        custom_anchor_relative_coord (bool): whether the custom anchor is relative coordinate.
        expand_type (str): how to expand the anchor. Options include `duplicate` or `uniform` or `gauss`. Default: 'duplicate'.
    """

    def __init__(self, width: int, height: int, 
                 depth: int = 1, 
                 custom_data: List[Union[np.ndarray, str]] = [],
                 custom_anchor_combination: bool = False,
                 custom_anchor_relative_coord: bool = True,
                 expand_type: str = 'duplicate',):
        AnchorDistributor.__init__(self, width, height, depth, expand_type)
        self.custom_anchor_combination = custom_anchor_combination
        self.custom_anchor_relative_coord = custom_anchor_relative_coord
        self.custom_shapes = [data for data in custom_data if isinstance(data, str)]
        self.custom_anchors = [data for data in custom_data if isinstance(data, (np.ndarray, list, tuple))]
        
    @property
    def custom_shapes(self):
        return self._custom_shapes
    
    @custom_shapes.setter
    def custom_shapes(self, value: List[str]):
        shapes = []
        for shape in value:
            assert isinstance(shape, str), "Custom shape must be str."
            shapes.append(self._get_spical_shape(shape))
        self._custom_shapes = shapes
        
    @property
    def custom_anchors(self):
        return self._custom_anchors
    
    @custom_anchors.setter
    def custom_anchors(self, value: List[np.ndarray]):
        anchors = []
        for anchor in value:
            if isinstance(anchor, (list, tuple)):
                if not isinstance(anchor[0], (list, tuple)):
                    anchor = [anchor]
                anchor = np.array(anchor)
            assert isinstance(anchor, np.ndarray), "Custom anchor must be np.ndarray."
            anchors.append(anchor)
        self._custom_anchors = self._get_anchor_combinations(anchors)
        
    @property
    def custom_data(self):
        return self.custom_shapes + self.custom_anchors
        
    def _get_spical_shape(self, shape_name: str, type=np.float32) -> np.ndarray:
        """Get special shape data shaped [N, 2]. Range [0, 1]"""
        if shape_name == 's_curve':
            shape = make_s_curve(self.dis_point_num, noise=0.1)[0]
            shape = shape[:, [0, 2]]
        elif shape_name == 'swiss_roll':
            shape = make_swiss_roll(self.dis_point_num, noise=0.5)[0]
            shape = shape[:, [0, 2]]
        else:
            raise ValueError(f"Not supported shape {shape_name}. Only support 's_curve' or 'swiss_roll'.")
        shape[:, 0] = (shape[:, 0] - shape[:, 0].min())  / (shape[:, 0].max() - shape[:, 0].min())
        shape[:, 1] = (shape[:, 1] - shape[:, 1].min()) / (shape[:, 1].max() - shape[:, 1].min())
        return shape.astype(type)
    
    def _pad_custom_anchor(self, anchor:np.ndarray):
        """Pad custom anchor num to `self.dis_point_num`."""
        if not self.custom_anchor_relative_coord:
            anchor = anchor / np.array([self.width, self.height])
        anchor = self.expand_data(anchor, self.dis_point_num)
        return self.available_data(anchor)
    
    def _get_anchor_combinations(self, anchors: np.ndarray) -> np.ndarray:
        """Get combinations of anchors shaped [C(N, 1)+...+C(N, N), N, 2]."""
        comb_anchors = []
        if self.custom_anchor_combination:
            from itertools import combinations
            index = np.arange(len(anchors))
            for r in index:
                for comb_i in combinations(index, r+1):
                    comb = np.concatenate([anchors[i] for i in comb_i], axis=0)
                    comb_anchors.append(self._pad_custom_anchor(comb))
        else:
            for anchor in anchors:
                comb_anchors.append(self._pad_custom_anchor(anchor))
        return comb_anchors