JadeRay-42 commited on
Commit
b82b0e2
·
1 Parent(s): 996d82f

First version of the Custom Anchor Shape dataset.

Browse files
Files changed (3) hide show
  1. CustomAnchorShape.py +147 -0
  2. CustomAnchorShapeGenerator.py +245 -0
  3. README.md +0 -0
CustomAnchorShape.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hugging Face Loading script
2
+
3
+ from typing import List, Union
4
+ import numpy as np
5
+
6
+ import datasets
7
+ from .CustomAnchorShapeGenerator import CustomAnchorShape
8
+
9
+
10
+ # TODO: Add BibTeX citation
11
+ # Find for instance the citation on arxiv or on the dataset repo/website
12
+ _CITATION = """\
13
+ @InProceedings{huggingface:dataset,
14
+ title = {A great new dataset},
15
+ author={huggingface, Inc.
16
+ },
17
+ year={2020}
18
+ }
19
+ """
20
+
21
+ # You can copy an official description
22
+ _DESCRIPTION = """\
23
+ This is Custom Anchor shape dataset.
24
+ """
25
+
26
+ # TODO: Add a link to an official homepage for the dataset here
27
+ _HOMEPAGE = ""
28
+
29
+ # TODO: Add the licence for the dataset here if you can find it
30
+ _LICENSE = ""
31
+
32
+
33
+ class CustomAnchorShapeConfig(datasets.BuilderConfig):
34
+ """Builder Config for CustomShape."""
35
+
36
+ def __init__(self, size, custom_data, **kwargs):
37
+ """BuilderConfig for CustomShape.
38
+
39
+ Args:
40
+ **kwargs: keyword arguments forwarded to super.
41
+ """
42
+ super(CustomAnchorShapeConfig, self).__init__(version=datasets.Version("1.0.0"),**kwargs)
43
+ self.size = size
44
+ self.custom_data = custom_data
45
+
46
+
47
+ class CustomAnchorShapeDataset(datasets.GeneratorBasedBuilder):
48
+ """CustomShape dataset."""
49
+
50
+ BUILDER_CONFIGS = [
51
+ CustomAnchorShapeConfig(
52
+ name='64size',
53
+ description='64x64 size custom shape dataset.',
54
+ size=64,
55
+ custom_data={
56
+ "train": ['s_curve',
57
+ 'swiss_roll',
58
+ [0.5, 0.5],
59
+ [[0.25, 0.25], [0.75, 0.75]],],
60
+ "validation": ['s_curve',
61
+ 'swiss_roll',
62
+ [0.5, 0.5],
63
+ [0.25, 0.25],
64
+ [0.25, 0.75],
65
+ [0.75, 0.75],
66
+ [0.75, 0.25],
67
+ [[0.25, 0.25], [0.75, 0.75]],
68
+ [[0.25, 0.75], [0.75, 0.25]],],
69
+ }
70
+ ),
71
+ CustomAnchorShapeConfig(
72
+ name='224size',
73
+ description='224x224 size custom shape dataset.',
74
+ size=224,
75
+ custom_data={
76
+ "train": ['s_curve',
77
+ 'swiss_roll',
78
+ [0.5, 0.5],
79
+ [[0.25, 0.25], [0.75, 0.75]],],
80
+ "validation": ['s_curve',
81
+ 'swiss_roll',
82
+ [0.5, 0.5],
83
+ [0.25, 0.25],
84
+ [0.25, 0.75],
85
+ [0.75, 0.75],
86
+ [0.75, 0.25],
87
+ [[0.25, 0.25], [0.75, 0.75]],
88
+ [[0.25, 0.75], [0.75, 0.25]],],
89
+ }
90
+ ),
91
+ ]
92
+
93
+ def _info(self):
94
+ features = datasets.Features(
95
+ {
96
+ 'image_id': datasets.Value('int64'),
97
+ 'image': datasets.Image(),
98
+ 'width': datasets.Value('int64'),
99
+ 'height': datasets.Value('int64'),
100
+ 'object': datasets.features.Sequence({
101
+ 'bbox': datasets.features.Sequence(datasets.Value('float64')),
102
+ })
103
+ }
104
+ )
105
+ return datasets.DatasetInfo(
106
+ description=_DESCRIPTION,
107
+ features=features,
108
+ )
109
+
110
+ def _split_generators(self, dl_manager):
111
+ return [
112
+ datasets.SplitGenerator(
113
+ name=datasets.Split.TRAIN,
114
+ gen_kwargs={
115
+ "width": self.config.size,
116
+ "height": self.config.size,
117
+ "custom_data": self.config.custom_data['train'],
118
+ },
119
+ ),
120
+ ]
121
+
122
+ def _generate_examples(
123
+ self,
124
+ size: Union[int, tuple],
125
+ custom_data: List[Union[np.ndarray, str]],
126
+ ):
127
+ if isinstance(size, int):
128
+ width, height = size, size
129
+ else:
130
+ width, height = size
131
+
132
+ custom_shape = CustomAnchorShape(
133
+ width,
134
+ height,
135
+ custom_data=custom_data,
136
+ )
137
+
138
+ for i, data in enumerate(custom_shape.custom_data):
139
+ yield {
140
+ 'image_id': i,
141
+ 'image': custom_shape.get_distribution(data, type='img'),
142
+ 'width': width,
143
+ 'height': height,
144
+ 'object': {
145
+ 'bbox': custom_shape.get_distribution(data, type='1d'),
146
+ }
147
+ }
CustomAnchorShapeGenerator.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Union
2
+ from abc import ABC, abstractmethod
3
+
4
+ import numpy as np
5
+ from PIL import Image
6
+ from sklearn.datasets import make_s_curve, make_swiss_roll
7
+
8
+
9
+ class DataExpander(ABC):
10
+ """Abstract class for data expander with different distribution."""
11
+
12
+ @abstractmethod
13
+ def expand_data(self, data: np.ndarray, size: int, **kwargs) -> np.ndarray:
14
+ """Return the expanded data to size."""
15
+ raise NotImplementedError
16
+
17
+ @abstractmethod
18
+ def available_data(self, data: np.ndarray, **kwargs) -> np.ndarray:
19
+ """Return the available data."""
20
+ raise NotImplementedError
21
+
22
+
23
+ class AnchorExpander(DataExpander):
24
+ """Class for anchor expander with different distribution.
25
+
26
+ Args:
27
+ expand_type (str): expand type of the anchor distribution. Options include `duplicate` or `uniform` or `gauss`. Default: 'duplicate'.
28
+ """
29
+
30
+ def __init__(self, expand_type: str = 'duplicate'):
31
+ self.expand_type = expand_type
32
+ self.type_map = {
33
+ 'duplicate': self.duplicate,
34
+ 'uniform': self.uniform,
35
+ 'gauss': self.gauss,
36
+ }
37
+
38
+ def _get_anchor_number(self, anchors: np.ndarray):
39
+ """Return the number of anchors."""
40
+ assert anchors.ndim == 2 , "anchors should be 2D array."
41
+ assert anchors.shape[1] == 2 or anchors.shape[1] == 4, "each anchor shaped as (cx, cy) or (cx, cy, w, h)."
42
+ return anchors.shape[0]
43
+
44
+ def expand_data(self, data: np.ndarray, size: int, **kwargs) -> np.ndarray:
45
+ """Return the expanded data to size."""
46
+ anchor_num = self._get_anchor_number(data) + 1
47
+ expand_space = np.linspace(0, size, anchor_num).astype(int)
48
+ expand_num = expand_space[1:] - expand_space[:-1]
49
+
50
+ return self.type_map[self.expand_type](data, expand_num)
51
+
52
+ def available_data(self, data: np.ndarray, type=np.float32, **kwargs) -> np.ndarray:
53
+ """Return the available anchors ranged [0, 1] with type."""
54
+ data[:, 0::2] = np.clip(data[:, 0::2], 0, 1)
55
+ data[:, 1::2] = np.clip(data[:, 1::2], 0, 1)
56
+ if data.dtype != type:
57
+ data = data.astype(type)
58
+ return data
59
+
60
+ def duplicate(self, anchors: np.ndarray, expand_num: np.ndarray):
61
+ """Duplicate each anchor form anchors to expand_num."""
62
+ return anchors.repeat(expand_num, axis=0)
63
+
64
+ def uniform(self, anchors: np.ndarray, expand_num: np.ndarray):
65
+ """Uniformly expand each anchor form anchors to expand_num in anchor region."""
66
+ assert anchors.shape[1] == 4, "Uniformly expand only support anchors shaped as (cx, cy, w, h)."
67
+ new_anchors = []
68
+ for n, (cx, cy, w, h) in zip(expand_num, anchors):
69
+ lt = [cx - w / 2, cy - h / 2]
70
+ rb = [cx + w / 2, cy + h / 2]
71
+ new_anchors.append(np.random.uniform(lt, rb, (n, 2)))
72
+ return np.concatenate(new_anchors, axis=0)
73
+
74
+ def gauss(self, anchors: np.ndarray, expand_num: np.ndarray):
75
+ """Gaussian expand each anchor form anchors to expand_num in anchor region."""
76
+ assert anchors.shape[1] == 4, "Gaussian expand only support anchors shaped as (cx, cy, w, h)."
77
+ new_anchors = []
78
+ for n, (cx, cy, w, h) in zip(expand_num, anchors):
79
+ new_anchors.append(np.random.multivariate_normal([cx, cy], [[w, 0], [0, h]], n))
80
+ return np.concatenate(new_anchors, axis=0)
81
+
82
+
83
+ class DataDistributor(ABC):
84
+ """Abstract class for data distributor."""
85
+
86
+ @abstractmethod
87
+ def get_distribution(self, data: np.ndarray, **kwargs):
88
+ """Return the data distribution."""
89
+ raise NotImplementedError
90
+
91
+
92
+ class AnchorDistributor(DataDistributor, AnchorExpander):
93
+ """Abstract class for anchor distributor.
94
+
95
+ Args:
96
+ width (int): width of the distribution.
97
+ height (int): height of the distribution.
98
+ depth (int): depth of the distribution. Default: 1.
99
+ expand_type (str): type of the anchor distribution. Options include `duplicate` or `uniform` or `gauss`. Default: 'duplicate'.
100
+ """
101
+
102
+ def __init__(self, width: int, height: int, depth: int = 1,
103
+ expand_type: str = 'duplicate'):
104
+ self.width = width
105
+ self.height = height
106
+ self.depth = depth
107
+ AnchorExpander.__init__(self, expand_type)
108
+
109
+ @property
110
+ def dis_point_num(self):
111
+ """Return the number of expanded distribution points."""
112
+ return int(self.width * self.height)
113
+
114
+ def get_distribution(self, data: np.ndarray, type: str = '1d', **kwargs):
115
+ """Return the anchor distribution."""
116
+ if type == '1d':
117
+ return self.to_1d_distribution(data)
118
+ elif type == 'img':
119
+ return self.to_img_distribution(data)
120
+ else:
121
+ raise ValueError(f"Unsupported distribute type {type}.")
122
+
123
+ def to_1d_distribution(self, anchors: np.ndarray):
124
+ """Return the 1D distribution of anchors shaped [NxD, *]."""
125
+ anchors = np.repeat(anchors, self.depth, axis=0)
126
+ return anchors
127
+
128
+ def to_img_distribution(self, anchors: np.ndarray) -> Image.Image:
129
+ """Return the Image filled distribution of anchors."""
130
+ assert self.depth == 1 or self.depth == 3, "Only support depth 1 (GRAY) or 3(RGB)."
131
+ img = filled_anchors(anchors, self.width, self.height)
132
+ gray_img = Image.fromarray(img)
133
+ if self.depth == 1:
134
+ return gray_img
135
+ else:
136
+ return gray_img.convert('RGB')
137
+
138
+
139
+ def filled_anchors(anchors: np.ndarray, width: int, height: int) -> np.ndarray:
140
+ """Return the hist filled in distributed anchors' c_xy along (x,y) shaped [W, H]."""
141
+ assert anchors.ndim == 2, "anchors should be 2D array."
142
+ assert anchors.max() <= 1 and anchors.min() >= 0, "anchors should be ranged [0, 1]."
143
+
144
+ anchor_cxcy = (anchors[:, :2] * np.array([width-1, height-1])).astype(int)
145
+ anchor_unique, anchor_counts = np.unique(anchor_cxcy, axis=0, return_counts=True)
146
+ anchor_counts = anchor_counts * 255.0 / anchor_counts.max()
147
+ anchor_counts = anchor_counts.astype(int).clip(0, 255)
148
+ anchor_index = anchor_unique[:, 1], anchor_unique[:, 0]
149
+ hist = np.zeros((width, height), dtype=np.uint8)
150
+ hist[anchor_index] = anchor_counts
151
+ return hist
152
+
153
+
154
+ class CustomAnchorShape(AnchorDistributor):
155
+ """Custom anchor shape distributor.
156
+
157
+ Args:
158
+ width (int): width of the distribution.
159
+ height (int): height of the distribution.
160
+ depth (int): depth of the distribution. Default: 1.
161
+ custom_data (List[Union[np.ndarray, str]]): custom data to be added to the sample. Include `s_curve`, `swiss_roll` and `custom_anchor`.
162
+ custom_anchor_combination (bool): whether to combine custom anchors.
163
+ custom_anchor_relative_coord (bool): whether the custom anchor is relative coordinate.
164
+ expand_type (str): how to expand the anchor. Options include `duplicate` or `uniform` or `gauss`. Default: 'duplicate'.
165
+ """
166
+
167
+ def __init__(self, width: int, height: int,
168
+ depth: int = 1,
169
+ custom_data: List[Union[np.ndarray, str]] = [],
170
+ custom_anchor_combination: bool = False,
171
+ custom_anchor_relative_coord: bool = True,
172
+ expand_type: str = 'duplicate',):
173
+ AnchorDistributor.__init__(self, width, height, depth, expand_type)
174
+ self.custom_anchor_combination = custom_anchor_combination
175
+ self.custom_anchor_relative_coord = custom_anchor_relative_coord
176
+ self.custom_shapes = [data for data in custom_data if isinstance(data, str)]
177
+ self.custom_anchors = [data for data in custom_data if isinstance(data, (np.ndarray, list, tuple))]
178
+
179
+ @property
180
+ def custom_shapes(self):
181
+ return self._custom_shapes
182
+
183
+ @custom_shapes.setter
184
+ def custom_shapes(self, value: List[str]):
185
+ shapes = []
186
+ for shape in value:
187
+ assert isinstance(shape, str), "Custom shape must be str."
188
+ shapes.append(self._get_spical_shape(shape))
189
+ self._custom_shapes = shapes
190
+
191
+ @property
192
+ def custom_anchors(self):
193
+ return self._custom_anchors
194
+
195
+ @custom_anchors.setter
196
+ def custom_anchors(self, value: List[np.ndarray]):
197
+ anchors = []
198
+ for anchor in value:
199
+ if isinstance(anchor, (list, tuple)):
200
+ if not isinstance(anchor[0], (list, tuple)):
201
+ anchor = [anchor]
202
+ anchor = np.array(anchor)
203
+ assert isinstance(anchor, np.ndarray), "Custom anchor must be np.ndarray."
204
+ anchors.append(anchor)
205
+ self._custom_anchors = self._get_anchor_combinations(anchors)
206
+
207
+ @property
208
+ def custom_data(self):
209
+ return self.custom_shapes + self.custom_anchors
210
+
211
+ def _get_spical_shape(self, shape_name: str, type=np.float32) -> np.ndarray:
212
+ """Get special shape data shaped [N, 2]. Range [0, 1]"""
213
+ if shape_name == 's_curve':
214
+ shape = make_s_curve(self.dis_point_num, noise=0.1)[0]
215
+ shape = shape[:, [0, 2]]
216
+ elif shape_name == 'swiss_roll':
217
+ shape = make_swiss_roll(self.dis_point_num, noise=0.5)[0]
218
+ shape = shape[:, [0, 2]]
219
+ else:
220
+ raise ValueError(f"Not supported shape {shape_name}. Only support 's_curve' or 'swiss_roll'.")
221
+ shape[:, 0] = (shape[:, 0] - shape[:, 0].min()) / (shape[:, 0].max() - shape[:, 0].min())
222
+ shape[:, 1] = (shape[:, 1] - shape[:, 1].min()) / (shape[:, 1].max() - shape[:, 1].min())
223
+ return shape.astype(type)
224
+
225
+ def _pad_custom_anchor(self, anchor:np.ndarray):
226
+ """Pad custom anchor num to `self.dis_point_num`."""
227
+ if not self.custom_anchor_relative_coord:
228
+ anchor = anchor / np.array([self.width, self.height])
229
+ anchor = self.expand_data(anchor, self.dis_point_num)
230
+ return self.available_data(anchor)
231
+
232
+ def _get_anchor_combinations(self, anchors: np.ndarray) -> np.ndarray:
233
+ """Get combinations of anchors shaped [C(N, 1)+...+C(N, N), N, 2]."""
234
+ comb_anchors = []
235
+ if self.custom_anchor_combination:
236
+ from itertools import combinations
237
+ index = np.arange(len(anchors))
238
+ for r in index:
239
+ for comb_i in combinations(index, r+1):
240
+ comb = np.concatenate([anchors[i] for i in comb_i], axis=0)
241
+ comb_anchors.append(self._pad_custom_anchor(comb))
242
+ else:
243
+ for anchor in anchors:
244
+ comb_anchors.append(self._pad_custom_anchor(anchor))
245
+ return comb_anchors
README.md ADDED
File without changes