-
Notifications
You must be signed in to change notification settings - Fork 35
/
label_mask.py
523 lines (410 loc) · 18.7 KB
/
label_mask.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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
#!/usr/bin/env python3
#
# Copyright 2021 Graviti. Licensed under MIT License.
#
"""The implementation of the TensorBay mask label."""
from typing import Any, Dict, Optional, Type, TypeVar
from tensorbay.label.basic import AttributeType, SubcatalogBase
from tensorbay.label.supports import AttributesMixin, IsTrackingMixin, MaskCategoriesMixin
from tensorbay.utility import URL, FileMixin, RemoteFileMixin, ReprMixin
class SemanticMaskSubcatalog(SubcatalogBase, MaskCategoriesMixin, AttributesMixin):
"""This class defines the subcatalog for semantic mask type of labels.
Attributes:
description: The description of the entire semantic mask subcatalog.
categories: All the possible categories in the corresponding dataset
stored in a :class:`~tensorbay.utility.name.NameList`
with the category names as keys
and the :class:`~tensorbay.label.supports.CategoryInfo` as values.
category_delimiter: The delimiter in category values indicating parent-child relationship.
attributes: All the possible attributes in the corresponding dataset
stored in a :class:`~tensorbay.utility.name.NameList`
with the attribute names as keys
and the :class:`~tensorbay.label.attribute.AttributeInfo` as values.
is_tracking: Whether the Subcatalog contains tracking information.
Examples:
*Initialization Method 1:* Init from ``SemanticMaskSubcatalog.loads()`` method.
>>> catalog = {
... "SEMANTIC_MASK": {
... "categories": [
... {'name': 'cat', "categoryId": 1},
... {'name': 'dog', "categoryId": 2}
... ],
... "attributes": [{'name': 'occluded', 'type': 'boolean'}],
... }
... }
>>> SemanticMaskSubcatalog.loads(catalog["SEMANTIC_MASK"])
SemanticMaskSubcatalog(
(categories): NameList [...],
(attributes): NameList [...]
)
*Initialization Method 2:* Init an empty SemanticMaskSubcatalog and then add the attributes.
>>> semantic_mask_subcatalog = SemanticMaskSubcatalog()
>>> semantic_mask_subcatalog.add_category("cat", 1)
>>> semantic_mask_subcatalog.add_category("dog", 2)
>>> semantic_mask_subcatalog.add_attribute("occluded", type_="boolean")
>>> semantic_mask_subcatalog
SemanticMaskSubcatalog(
(categories): NameList [...],
(attributes): NameList [...]
)
"""
class InstanceMaskSubcatalog(SubcatalogBase, MaskCategoriesMixin, IsTrackingMixin, AttributesMixin):
"""This class defines the subcatalog for instance mask type of labels.
Attributes:
description: The description of the entire instance mask subcatalog.
categories: All the possible categories in the corresponding dataset
stored in a :class:`~tensorbay.utility.name.NameList`
with the category names as keys
and the :class:`~tensorbay.label.supports.CategoryInfo` as values.
category_delimiter: The delimiter in category values indicating parent-child relationship.
attributes: All the possible attributes in the corresponding dataset
stored in a :class:`~tensorbay.utility.name.NameList`
with the attribute names as keys
and the :class:`~tensorbay.label.attribute.AttributeInfo` as values.
is_tracking: Whether the Subcatalog contains tracking information.
Examples:
*Initialization Method 1:* Init from ``InstanceMaskSubcatalog.loads()`` method.
>>> catalog = {
... "INSTANCE_MASK": {
... "categories": [
... {'name': 'background', "categoryId": 0}
... ],
... "attributes": [{'name': 'occluded', 'type': 'boolean'}],
... }
... }
>>> InstanceMaskSubcatalog.loads(catalog["INSTANCE_MASK"])
InstanceMaskSubcatalog(
(is_tracking): False,
(categories): NameList [...],
(attributes): NameList [...]
)
*Initialization Method 2:* Init an empty InstanceMaskSubcatalog and then add the attributes.
>>> instance_mask_subcatalog = InstanceMaskSubcatalog()
>>> instance_mask_subcatalog.add_category("background", 0)
>>> instance_mask_subcatalog.add_attribute("occluded", type_="boolean")
>>> instance_mask_subcatalog
InstanceMaskSubcatalog(
(categories): NameList [...],
(attributes): NameList [...]
)
"""
class PanopticMaskSubcatalog(SubcatalogBase, MaskCategoriesMixin, AttributesMixin):
"""This class defines the subcatalog for panoptic mask type of labels.
Attributes:
description: The description of the entire panoptic mask subcatalog.
categories: All the possible categories in the corresponding dataset
stored in a :class:`~tensorbay.utility.name.NameList`
with the category names as keys
and the :class:`~tensorbay.label.supports.CategoryInfo` as values.
category_delimiter: The delimiter in category values indicating parent-child relationship.
attributes: All the possible attributes in the corresponding dataset
stored in a :class:`~tensorbay.utility.name.NameList`
with the attribute names as keys
and the :class:`~tensorbay.label.attribute.AttributeInfo` as values.
is_tracking: Whether the Subcatalog contains tracking information.
Examples:
*Initialization Method 1:* Init from ``PanopticMaskSubcatalog.loads()`` method.
>>> catalog = {
... "PANOPTIC_MASK": {
... "categories": [
... {'name': 'cat', "categoryId": 1},
... {'name': 'dog', "categoryId": 2}
... ],
... "attributes": [{'name': 'occluded', 'type': 'boolean'}],
... }
... }
>>> PanopticMaskSubcatalog.loads(catalog["PANOPTIC_MASK"])
PanopticMaskSubcatalog(
(categories): NameList [...],
(attributes): NameList [...]
)
*Initialization Method 2:* Init an empty PanopticMaskSubcatalog and then add the attributes.
>>> panoptic_mask_subcatalog = PanopticMaskSubcatalog()
>>> panoptic_mask_subcatalog.add_category("cat", 1)
>>> panoptic_mask_subcatalog.add_category("dog", 2)
>>> panoptic_mask_subcatalog.add_attribute("occluded", type_="boolean")
>>> panoptic_mask_subcatalog
PanopticMaskSubcatalog(
(categories): NameList [...],
(attributes): NameList [...]
)
"""
class SemanticMaskBase(ReprMixin):
"""SemanticMaskBase is a base class for the semantic mask label.
Attributes:
all_attributes: The dict of the attributes in this mask, which key is the category id,
and the value is the corresponding attributes.
"""
_repr_attrs = ("all_attributes",)
all_attributes: Dict[int, AttributeType]
class InstanceMaskBase(ReprMixin):
"""InstanceMaskBase is a base class for the instance mask label.
Attributes:
all_attributes: The dict of the attributes in this mask, which key is the instance id,
and the value is the corresponding attributes.
"""
_repr_attrs = ("all_attributes",)
all_attributes: Dict[int, AttributeType]
class PanopticMaskBase(ReprMixin):
"""PanopticMaskBase is a base class for the panoptic mask label.
Attributes:
all_attributes: The dict of the attributes in this mask, which key is the instance id,
and the value is the corresponding attributes.
all_category_ids: The dict of the category id in this mask, which key is the instance id,
and the value is the corresponding category id.
"""
_repr_attrs = ("all_category_ids", "all_attributes")
all_attributes: Dict[int, AttributeType]
def __init__(self) -> None:
self.all_category_ids: Dict[int, int] = {}
class SemanticMask(SemanticMaskBase, FileMixin):
"""SemanticMask is a class for the local semantic mask label.
Attributes:
all_attributes: The dict of the attributes in this mask, which key is the category id,
and the value is the corresponding attributes.
"""
def __init__(self, local_path: str) -> None:
FileMixin.__init__(self, local_path)
def get_callback_body(self) -> Dict[str, Any]:
"""Get the callback request body for uploading.
Returns:
The callback request body, which looks like::
{
"checksum": <str>,
"fileSize": <int>,
"info": [
{
"categoryId": 0,
"attributes": {
"occluded": True
}
},
{
"categoryId": 1,
"attributes": {
"occluded": False
}
}
]
}
"""
body = super()._get_callback_body()
if hasattr(self, "all_attributes"):
body["info"] = [
{"categoryId": i, "attributes": attributes}
for i, attributes in self.all_attributes.items()
]
return body
class InstanceMask(InstanceMaskBase, FileMixin):
"""InstanceMask is a class for the local instance mask label.
Attributes:
all_attributes: The dict of the attributes in this mask, which key is the instance id,
and the value is the corresponding attributes.
"""
def __init__(self, local_path: str) -> None:
FileMixin.__init__(self, local_path)
def get_callback_body(self) -> Dict[str, Any]:
"""Get the callback request body for uploading.
Returns:
The callback request body, which looks like::
{
"checksum": <str>,
"fileSize": <int>,
"info": [
{
"instanceId": 0,
"attributes": {
"occluded": True
}
},
{
"instanceId": 1,
"attributes": {
"occluded": False
}
}
]
}
"""
body = super()._get_callback_body()
if hasattr(self, "all_attributes"):
body["info"] = [
{"instanceId": i, "attributes": attributes}
for i, attributes in self.all_attributes.items()
]
return body
class PanopticMask(PanopticMaskBase, FileMixin):
"""PanopticMask is a class for the local panoptic mask label.
Attributes:
all_attributes: The dict of the attributes in this mask, which key is the instance id,
and the value is the corresponding attributes.
all_category_ids: The dict of the category id in this mask, which key is the instance id,
and the value is the corresponding category id.
"""
def __init__(self, local_path: str) -> None:
PanopticMaskBase.__init__(self)
FileMixin.__init__(self, local_path)
def get_callback_body(self) -> Dict[str, Any]:
"""Get the callback request body for uploading.
Returns:
The callback request body, which looks like::
{
"checksum": <str>,
"fileSize": <int>,
"info": [
{
"instanceId": 0,
"categoryId": 100,
"attributes": {
"occluded": True
}
},
{
"instanceId": 1,
"categoryId": 101,
"attributes": {
"occluded": False
}
}
]
}
"""
body = super()._get_callback_body()
all_attributes = getattr(self, "all_attributes", None)
info = []
for i, category_id in self.all_category_ids.items():
item = {"instanceId": i, "categoryId": category_id}
if all_attributes:
item["attributes"] = all_attributes[i] # pylint: disable=unsubscriptable-object
info.append(item)
body["info"] = info
return body
class RemoteMaskErrorMixin: # pylint: disable=too-few-public-methods
"""RemoteMaskErrorMixin provid more accurate error information when calling ``dumps()``."""
def get_callback_body(self) -> None:
"""``dumps`` function is not support for remote mask label.
Raises:
AttributeError: when calling the ``dumps()``.
"""
raise AttributeError(f"'{self.__class__.__name__}' object has no function 'dumps()'")
class RemoteSemanticMask(SemanticMaskBase, RemoteFileMixin, RemoteMaskErrorMixin):
"""RemoteSemanticMask is a class for the remote semantic mask label.
Attributes:
all_attributes: The dict of the attributes in this mask, which key is the category id,
and the value is the corresponding attributes.
"""
_T = TypeVar("_T", bound="RemoteSemanticMask")
@classmethod
def from_response_body(cls: Type[_T], body: Dict[str, Any]) -> _T:
"""Loads a :class:`RemoteSemanticMask` object from a response body.
Arguments:
body: The response body which contains the information of a remote semantic mask,
whose format should be like::
{
"remotePath": <str>,
"info": [
{
"categoryId": 0,
"attributes": {
"occluded": True
}
},
{
"categoryId": 1,
"attributes": {
"occluded": False
}
}
]
}
Returns:
The loaded :class:`RemoteSemanticMask` object.
"""
mask = cls(body["remotePath"])
if "info" in body:
mask.all_attributes = {item["categoryId"]: item["attributes"] for item in body["info"]}
return mask
class RemoteInstanceMask(InstanceMaskBase, RemoteFileMixin, RemoteMaskErrorMixin):
"""RemoteInstanceMask is a class for the remote instance mask label.
Attributes:
all_attributes: The dict of the attributes in this mask, which key is the instance id,
and the value is the corresponding attributes.
"""
_T = TypeVar("_T", bound="RemoteInstanceMask")
@classmethod
def from_response_body(cls: Type[_T], body: Dict[str, Any]) -> _T:
"""Loads a :class:`RemoteInstanceMask` object from a response body.
Arguments:
body: The response body which contains the information of a remote instance mask,
whose format should be like::
{
"remotePath": <str>,
"info": [
{
"instanceId": 0,
"attributes": {
"occluded": True
}
},
{
"instanceId": 1,
"attributes": {
"occluded": False
}
}
]
}
Returns:
The loaded :class:`RemoteInstanceMask` object.
"""
mask = cls(body["remotePath"])
if "info" in body:
mask.all_attributes = {item["instanceId"]: item["attributes"] for item in body["info"]}
return mask
class RemotePanopticMask(PanopticMaskBase, RemoteFileMixin, RemoteMaskErrorMixin):
"""RemotePanoticMask is a class for the remote panotic mask label.
Attributes:
all_attributes: The dict of the attributes in this mask, which key is the instance id,
and the value is the corresponding attributes.
"""
_T = TypeVar("_T", bound="RemotePanopticMask")
def __init__(self, remote_path: str, *, url: Optional[URL] = None) -> None:
PanopticMaskBase.__init__(self)
RemoteFileMixin.__init__(self, remote_path, url=url)
@classmethod
def from_response_body(cls: Type[_T], body: Dict[str, Any]) -> _T:
"""Loads a :class:`RemotePanopticMask` object from a response body.
Arguments:
body: The response body which contains the information of a remote panoptic mask,
whose format should be like::
{
"remotePath": <str>,
"info": [
{
"instanceId": 0,
"categoryId": 100,
"attributes": {
"occluded": True
}
},
{
"instanceId": 1,
"categoryId": 101,
"attributes": {
"occluded": False
}
}
]
}
Returns:
The loaded :class:`RemotePanopticMask` object.
"""
mask = cls(body["remotePath"])
info = body["info"]
# Workaround for panoptic masks with empty info.
# TODO: Remove this check after reuploading COCO mask labels or changing standards.
if info:
mask.all_category_ids = {item["instanceId"]: item["categoryId"] for item in info}
if "attributes" in info[0]:
mask.all_attributes = {item["instanceId"]: item["attributes"] for item in info}
return mask