faster-coco-eval 1.6.4__cp39-cp39-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- faster_coco_eval/__init__.py +28 -0
- faster_coco_eval/core/__init__.py +4 -0
- faster_coco_eval/core/coco.py +645 -0
- faster_coco_eval/core/cocoeval.py +645 -0
- faster_coco_eval/core/faster_eval_api.py +258 -0
- faster_coco_eval/core/mask.py +240 -0
- faster_coco_eval/extra/__init__.py +4 -0
- faster_coco_eval/extra/curves.py +196 -0
- faster_coco_eval/extra/display.py +166 -0
- faster_coco_eval/extra/draw.py +595 -0
- faster_coco_eval/extra/extra.py +129 -0
- faster_coco_eval/extra/utils.py +87 -0
- faster_coco_eval/faster_eval_api_cpp.cp39-win_amd64.pyd +0 -0
- faster_coco_eval/mask_api_new_cpp.cp39-win_amd64.pyd +0 -0
- faster_coco_eval/version.py +2 -0
- faster_coco_eval-1.6.4.data/data/extra.txt +1 -0
- faster_coco_eval-1.6.4.data/data/runtime.txt +4 -0
- faster_coco_eval-1.6.4.data/data/tests.txt +5 -0
- faster_coco_eval-1.6.4.dist-info/LICENSE +201 -0
- faster_coco_eval-1.6.4.dist-info/METADATA +160 -0
- faster_coco_eval-1.6.4.dist-info/RECORD +23 -0
- faster_coco_eval-1.6.4.dist-info/WHEEL +5 -0
- faster_coco_eval-1.6.4.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
|
|
3
|
+
import faster_coco_eval.core.coco as coco
|
|
4
|
+
import faster_coco_eval.core.faster_eval_api as cocoeval
|
|
5
|
+
import faster_coco_eval.core.mask as mask
|
|
6
|
+
from faster_coco_eval.core import COCO, COCOeval_faster
|
|
7
|
+
from faster_coco_eval.version import __author__, __version__
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def init_as_pycocotools():
|
|
11
|
+
import faster_coco_eval
|
|
12
|
+
|
|
13
|
+
sys.modules["pycocotools"] = faster_coco_eval
|
|
14
|
+
sys.modules["pycocotools.coco"] = coco
|
|
15
|
+
sys.modules["pycocotools.cocoeval"] = cocoeval
|
|
16
|
+
sys.modules["pycocotools.mask"] = mask
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"init_as_pycocotools",
|
|
21
|
+
"mask",
|
|
22
|
+
"coco",
|
|
23
|
+
"cocoeval",
|
|
24
|
+
"COCO",
|
|
25
|
+
"COCOeval_faster",
|
|
26
|
+
"__author__",
|
|
27
|
+
"__version__",
|
|
28
|
+
]
|
|
@@ -0,0 +1,645 @@
|
|
|
1
|
+
# Original work Copyright (c) Piotr Dollar and Tsung-Yi Lin, 2014.
|
|
2
|
+
# Modified work Copyright (c) 2024 MiXaiLL76
|
|
3
|
+
|
|
4
|
+
import copy
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import pathlib
|
|
9
|
+
import time
|
|
10
|
+
import warnings
|
|
11
|
+
from collections import defaultdict
|
|
12
|
+
from typing import List, Optional, Union
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from faster_coco_eval.core import mask as maskUtils
|
|
17
|
+
from faster_coco_eval.version import __author__, __version__
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _isArrayLike(obj):
|
|
23
|
+
return hasattr(obj, "__iter__") and hasattr(obj, "__len__")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class COCO:
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
annotation_file: Optional[Union[str, dict, os.PathLike, pathlib.PosixPath]] = None,
|
|
30
|
+
use_deepcopy: bool = False,
|
|
31
|
+
):
|
|
32
|
+
"""Constructor of Microsoft COCO helper class.
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
annotation_file (str or dict or PathLike): path to annotation file
|
|
36
|
+
use_deepcopy (bool, optional):
|
|
37
|
+
whether to copy the dict annotations. Defaults to False.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
# load dataset
|
|
41
|
+
self.dataset, self.anns, self.cats, self.imgs = (
|
|
42
|
+
{},
|
|
43
|
+
{},
|
|
44
|
+
{},
|
|
45
|
+
{},
|
|
46
|
+
)
|
|
47
|
+
self.imgToAnns, self.catToImgs = defaultdict(list), defaultdict(list)
|
|
48
|
+
self.print_function = logger.debug
|
|
49
|
+
self.use_deepcopy = use_deepcopy
|
|
50
|
+
|
|
51
|
+
if annotation_file is not None:
|
|
52
|
+
self._print_function("loading annotations into memory...")
|
|
53
|
+
tic = time.time()
|
|
54
|
+
if type(annotation_file) in [str, os.PathLike, pathlib.PosixPath]:
|
|
55
|
+
self.dataset = self.load_json(annotation_file)
|
|
56
|
+
elif type(annotation_file) is dict:
|
|
57
|
+
if self.use_deepcopy:
|
|
58
|
+
self.dataset = copy.deepcopy(annotation_file)
|
|
59
|
+
else:
|
|
60
|
+
self.dataset = annotation_file.copy()
|
|
61
|
+
else:
|
|
62
|
+
self.dataset = None
|
|
63
|
+
|
|
64
|
+
assert type(self.dataset) is dict, f"annotation file format {type(self.dataset)} not supported"
|
|
65
|
+
self.print_function(f"Done (t={time.time() - tic:0.2f}s)")
|
|
66
|
+
self.createIndex()
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def print_function(self):
|
|
70
|
+
return self._print_function
|
|
71
|
+
|
|
72
|
+
@print_function.setter
|
|
73
|
+
def print_function(self, value):
|
|
74
|
+
self._print_function = value
|
|
75
|
+
|
|
76
|
+
def createIndex(self):
|
|
77
|
+
"""Create index for coco annotation data."""
|
|
78
|
+
tic = time.time()
|
|
79
|
+
# create index
|
|
80
|
+
self.print_function("creating index...")
|
|
81
|
+
anns, cats, imgs = {}, {}, {}
|
|
82
|
+
imgToAnns, catToImgs = defaultdict(list), defaultdict(list)
|
|
83
|
+
|
|
84
|
+
annsImgIds_dict = set()
|
|
85
|
+
if "images" in self.dataset:
|
|
86
|
+
for img in self.dataset["images"]:
|
|
87
|
+
if type(img["id"]) is not int:
|
|
88
|
+
img["id"] = int(img["id"])
|
|
89
|
+
|
|
90
|
+
imgs[img["id"]] = img
|
|
91
|
+
annsImgIds_dict.add(img["id"])
|
|
92
|
+
|
|
93
|
+
if "annotations" in self.dataset:
|
|
94
|
+
for ann in self.dataset["annotations"]:
|
|
95
|
+
if type(ann["image_id"]) is not int:
|
|
96
|
+
ann["image_id"] = int(ann["image_id"])
|
|
97
|
+
|
|
98
|
+
if ann["image_id"] in annsImgIds_dict:
|
|
99
|
+
imgToAnns[ann["image_id"]].append(ann)
|
|
100
|
+
anns[ann["id"]] = ann
|
|
101
|
+
|
|
102
|
+
if "categories" in self.dataset:
|
|
103
|
+
for cat in self.dataset["categories"]:
|
|
104
|
+
cats[cat["id"]] = cat
|
|
105
|
+
|
|
106
|
+
if "annotations" in self.dataset and "categories" in self.dataset:
|
|
107
|
+
for ann in self.dataset["annotations"]:
|
|
108
|
+
catToImgs[ann["category_id"]].append(ann["image_id"])
|
|
109
|
+
|
|
110
|
+
self.print_function("index created!")
|
|
111
|
+
self.print_function(f"Done (t={time.time() - tic:0.2f}s)")
|
|
112
|
+
|
|
113
|
+
# create class members
|
|
114
|
+
self.anns = anns
|
|
115
|
+
self.imgToAnns = imgToAnns
|
|
116
|
+
self.catToImgs = catToImgs
|
|
117
|
+
self.imgs = imgs
|
|
118
|
+
self.cats = cats
|
|
119
|
+
|
|
120
|
+
def info(self):
|
|
121
|
+
"""Print information about the annotation file."""
|
|
122
|
+
for key, value in self.dataset["info"].items():
|
|
123
|
+
self.print_function(f"{key}: {value}")
|
|
124
|
+
|
|
125
|
+
def getAnnIds(
|
|
126
|
+
self,
|
|
127
|
+
imgIds: List[int] = [],
|
|
128
|
+
catIds: List[int] = [],
|
|
129
|
+
areaRng: List[float] = [],
|
|
130
|
+
iscrowd: bool = None,
|
|
131
|
+
) -> List[int]:
|
|
132
|
+
"""Get ann ids that satisfy given filter conditions.
|
|
133
|
+
|
|
134
|
+
Args:
|
|
135
|
+
imgIds (int array) : get anns for given imgs
|
|
136
|
+
catIds (int array) : get anns for given cats
|
|
137
|
+
areaRng (float array) : get anns for given area range
|
|
138
|
+
(e.g. [0 inf])
|
|
139
|
+
iscrowd (boolean) : get anns for given crowd label
|
|
140
|
+
(False or True)
|
|
141
|
+
|
|
142
|
+
Returns:
|
|
143
|
+
ids (int array) : integer array of ann ids that satisfy the criteria
|
|
144
|
+
"""
|
|
145
|
+
imgIds = set(imgIds if _isArrayLike(imgIds) else [imgIds])
|
|
146
|
+
catIds = set(catIds if _isArrayLike(catIds) else [catIds])
|
|
147
|
+
|
|
148
|
+
check_area = len(areaRng) == 2
|
|
149
|
+
check_crowd = iscrowd is not None
|
|
150
|
+
check_cat = len(catIds) > 0
|
|
151
|
+
check_img = len(imgIds) > 0
|
|
152
|
+
|
|
153
|
+
if not (check_area or check_crowd or check_cat or check_img):
|
|
154
|
+
anns = self.dataset["annotations"]
|
|
155
|
+
else:
|
|
156
|
+
anns = []
|
|
157
|
+
|
|
158
|
+
if check_img:
|
|
159
|
+
for img_id in imgIds:
|
|
160
|
+
anns.extend(self.img_ann_map[img_id])
|
|
161
|
+
else:
|
|
162
|
+
anns = self.dataset["annotations"]
|
|
163
|
+
|
|
164
|
+
if check_cat:
|
|
165
|
+
anns = list(filter(lambda ann: ann["category_id"] in catIds, anns))
|
|
166
|
+
|
|
167
|
+
if check_area:
|
|
168
|
+
anns = list(
|
|
169
|
+
filter(
|
|
170
|
+
lambda ann: (ann["area"] > areaRng[0] and ann["area"] < areaRng[1]),
|
|
171
|
+
anns,
|
|
172
|
+
)
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
if check_crowd:
|
|
176
|
+
anns = list(
|
|
177
|
+
filter(
|
|
178
|
+
lambda ann: (int(ann.get("iscrowd", 0)) == int(iscrowd)),
|
|
179
|
+
anns,
|
|
180
|
+
)
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
ids = list(map(lambda ann: ann["id"], anns))
|
|
184
|
+
return ids
|
|
185
|
+
|
|
186
|
+
def getCatIds(
|
|
187
|
+
self,
|
|
188
|
+
catNms: List[str] = [],
|
|
189
|
+
supNms: List[str] = [],
|
|
190
|
+
catIds: List[int] = [],
|
|
191
|
+
) -> List[int]:
|
|
192
|
+
"""Get category ids that satisfy given filter conditions.
|
|
193
|
+
|
|
194
|
+
Args:
|
|
195
|
+
catNms (str array) : get cats for given cat names
|
|
196
|
+
supNms (str array) : get cats for given supercategory names
|
|
197
|
+
catIds (int array) : get cats for given ids
|
|
198
|
+
|
|
199
|
+
Returns:
|
|
200
|
+
ids (int array) : integer array of cat ids
|
|
201
|
+
"""
|
|
202
|
+
|
|
203
|
+
catNms = set(catNms if _isArrayLike(catNms) else [catNms])
|
|
204
|
+
supNms = set(supNms if _isArrayLike(supNms) else [supNms])
|
|
205
|
+
catIds = set(catIds if _isArrayLike(catIds) else [catIds])
|
|
206
|
+
|
|
207
|
+
if len(catNms) == len(supNms) == len(catIds) == 0:
|
|
208
|
+
cats = self.dataset["categories"]
|
|
209
|
+
else:
|
|
210
|
+
cats = self.dataset["categories"]
|
|
211
|
+
|
|
212
|
+
if len(catNms) > 0:
|
|
213
|
+
cats = list(filter(lambda cat: cat.get("name") in catNms, cats))
|
|
214
|
+
|
|
215
|
+
if len(supNms) > 0:
|
|
216
|
+
cats = list(filter(lambda cat: cat.get("supercategory") in supNms, cats))
|
|
217
|
+
|
|
218
|
+
if len(catIds) > 0:
|
|
219
|
+
cats = list(filter(lambda cat: cat.get("id") in catIds, cats))
|
|
220
|
+
|
|
221
|
+
ids = [cat["id"] for cat in cats]
|
|
222
|
+
return ids
|
|
223
|
+
|
|
224
|
+
def getImgIds(self, imgIds: List[int] = [], catIds: List[int] = []) -> List[int]:
|
|
225
|
+
"""Get image ids that satisfy given filter conditions.
|
|
226
|
+
|
|
227
|
+
Args:
|
|
228
|
+
imgIds (int array) : get imgs for given ids
|
|
229
|
+
catIds (int array) : get imgs with all given cats
|
|
230
|
+
|
|
231
|
+
Return:
|
|
232
|
+
ids (int array) : integer array of img ids
|
|
233
|
+
"""
|
|
234
|
+
|
|
235
|
+
imgIds = imgIds if _isArrayLike(imgIds) else [imgIds]
|
|
236
|
+
catIds = catIds if _isArrayLike(catIds) else [catIds]
|
|
237
|
+
|
|
238
|
+
if len(imgIds) == len(catIds) == 0:
|
|
239
|
+
ids = self.imgs.keys()
|
|
240
|
+
else:
|
|
241
|
+
ids = set(imgIds)
|
|
242
|
+
for i, catId in enumerate(catIds):
|
|
243
|
+
if i == 0 and len(ids) == 0:
|
|
244
|
+
ids = set(self.catToImgs[catId])
|
|
245
|
+
else:
|
|
246
|
+
ids &= set(self.catToImgs[catId])
|
|
247
|
+
return list(ids)
|
|
248
|
+
|
|
249
|
+
def loadAnns(self, ids: Union[List[int], int] = []) -> List[dict]:
|
|
250
|
+
"""Load anns with the specified ids.
|
|
251
|
+
|
|
252
|
+
Args:
|
|
253
|
+
ids (int array) : integer ids specifying anns.
|
|
254
|
+
|
|
255
|
+
Return:
|
|
256
|
+
anns (object array) : loaded ann objects
|
|
257
|
+
"""
|
|
258
|
+
|
|
259
|
+
if _isArrayLike(ids):
|
|
260
|
+
return [self.anns[i] for i in ids]
|
|
261
|
+
elif type(ids) is int:
|
|
262
|
+
return [self.anns[ids]]
|
|
263
|
+
|
|
264
|
+
def loadCats(self, ids: Union[List[int], int] = []) -> List[dict]:
|
|
265
|
+
"""Load categories with the specified ids.
|
|
266
|
+
|
|
267
|
+
Args:
|
|
268
|
+
ids (int array) : integer ids specifying cats.
|
|
269
|
+
|
|
270
|
+
Return:
|
|
271
|
+
cats (object array) : loaded cat objects
|
|
272
|
+
"""
|
|
273
|
+
if _isArrayLike(ids):
|
|
274
|
+
return [self.cats[i] for i in ids]
|
|
275
|
+
elif type(ids) is int:
|
|
276
|
+
return [self.cats[ids]]
|
|
277
|
+
|
|
278
|
+
def loadImgs(self, ids: Union[List[int], int] = []) -> List[dict]:
|
|
279
|
+
"""Load images with the specified ids.
|
|
280
|
+
|
|
281
|
+
Args:
|
|
282
|
+
ids (int array) : integer ids specifying img.
|
|
283
|
+
|
|
284
|
+
Return:
|
|
285
|
+
imgs (object array) : loaded img objects
|
|
286
|
+
"""
|
|
287
|
+
if _isArrayLike(ids):
|
|
288
|
+
return [self.imgs[i] for i in ids]
|
|
289
|
+
elif type(ids) is int:
|
|
290
|
+
return [self.imgs[ids]]
|
|
291
|
+
|
|
292
|
+
@staticmethod
|
|
293
|
+
def load_json(json_file: Optional[Union[str, os.PathLike]]) -> dict:
|
|
294
|
+
"""Load a json file.
|
|
295
|
+
|
|
296
|
+
Args:
|
|
297
|
+
json_file (str or os.PathLike): Path to the json file
|
|
298
|
+
|
|
299
|
+
Return:
|
|
300
|
+
data (dict): Loaded json data
|
|
301
|
+
"""
|
|
302
|
+
|
|
303
|
+
with open(json_file) as io:
|
|
304
|
+
_data = json.load(io)
|
|
305
|
+
return _data
|
|
306
|
+
|
|
307
|
+
def loadRes(
|
|
308
|
+
self,
|
|
309
|
+
resFile: Union[str, os.PathLike, np.ndarray],
|
|
310
|
+
min_score: float = 0.0,
|
|
311
|
+
) -> "COCO":
|
|
312
|
+
"""Load result file and return a result api object.
|
|
313
|
+
|
|
314
|
+
Args:
|
|
315
|
+
resFile (str) : file name of result file
|
|
316
|
+
min_score (float) : minimum score to consider a result
|
|
317
|
+
|
|
318
|
+
Return:
|
|
319
|
+
res (obj) : result api object
|
|
320
|
+
"""
|
|
321
|
+
res = COCO()
|
|
322
|
+
res.dataset["info"] = copy.deepcopy(self.dataset.get("info", {}))
|
|
323
|
+
res.dataset["images"] = [img for img in self.dataset["images"]]
|
|
324
|
+
|
|
325
|
+
self.print_function("Loading and preparing results...")
|
|
326
|
+
tic = time.time()
|
|
327
|
+
if type(resFile) in [str, os.PathLike]:
|
|
328
|
+
anns = self.load_json(resFile)
|
|
329
|
+
elif type(resFile) is np.ndarray:
|
|
330
|
+
anns = self.loadNumpyAnnotations(resFile)
|
|
331
|
+
else:
|
|
332
|
+
if self.use_deepcopy:
|
|
333
|
+
anns = copy.deepcopy(resFile)
|
|
334
|
+
else:
|
|
335
|
+
anns = resFile.copy()
|
|
336
|
+
|
|
337
|
+
assert type(anns) is list, "results in not an array of objects"
|
|
338
|
+
|
|
339
|
+
if min_score != 0.0:
|
|
340
|
+
anns = [ann for ann in anns if ann.get("score", 1) >= min_score]
|
|
341
|
+
|
|
342
|
+
annsImgIds = [ann["image_id"] for ann in anns]
|
|
343
|
+
assert set(annsImgIds) == (
|
|
344
|
+
set(annsImgIds) & set(self.getImgIds())
|
|
345
|
+
), "Results do not correspond to current coco set"
|
|
346
|
+
if "caption" in anns[0]:
|
|
347
|
+
imgIds = set([img["id"] for img in res.dataset["images"]]) & set([ann["image_id"] for ann in anns])
|
|
348
|
+
res.dataset["images"] = [img for img in res.dataset["images"] if img["id"] in imgIds]
|
|
349
|
+
for index, ann in enumerate(anns):
|
|
350
|
+
ann["id"] = index + 1
|
|
351
|
+
elif "bbox" in anns[0] and not anns[0]["bbox"] == []:
|
|
352
|
+
res.dataset["categories"] = copy.deepcopy(self.dataset["categories"])
|
|
353
|
+
for index, ann in enumerate(anns):
|
|
354
|
+
bb = ann["bbox"]
|
|
355
|
+
x1, x2, y1, y2 = [bb[0], bb[0] + bb[2], bb[1], bb[1] + bb[3]]
|
|
356
|
+
if "segmentation" not in ann:
|
|
357
|
+
ann["segmentation"] = [[x1, y1, x1, y2, x2, y2, x2, y1]]
|
|
358
|
+
ann["area"] = bb[2] * bb[3]
|
|
359
|
+
ann["id"] = index + 1
|
|
360
|
+
ann["iscrowd"] = 0
|
|
361
|
+
elif "segmentation" in anns[0]:
|
|
362
|
+
res.dataset["categories"] = copy.deepcopy(self.dataset["categories"])
|
|
363
|
+
for index, ann in enumerate(anns):
|
|
364
|
+
# now only support compressed RLE format as segmentation results
|
|
365
|
+
ann["area"] = maskUtils.area(ann["segmentation"])
|
|
366
|
+
if "bbox" not in ann:
|
|
367
|
+
ann["bbox"] = maskUtils.toBbox(ann["segmentation"])
|
|
368
|
+
ann["id"] = index + 1
|
|
369
|
+
ann["iscrowd"] = 0
|
|
370
|
+
elif "keypoints" in anns[0]:
|
|
371
|
+
res.dataset["categories"] = copy.deepcopy(self.dataset["categories"])
|
|
372
|
+
for index, ann in enumerate(anns):
|
|
373
|
+
s = ann["keypoints"]
|
|
374
|
+
x = s[0::3]
|
|
375
|
+
y = s[1::3]
|
|
376
|
+
x0, x1, y0, y1 = np.min(x), np.max(x), np.min(y), np.max(y)
|
|
377
|
+
ann["area"] = (x1 - x0) * (y1 - y0)
|
|
378
|
+
ann["id"] = index + 1
|
|
379
|
+
ann["bbox"] = [x0, y0, x1 - x0, y1 - y0]
|
|
380
|
+
self.print_function(f"DONE (t={time.time() - tic:0.2f}s)")
|
|
381
|
+
|
|
382
|
+
res.dataset["annotations"] = anns
|
|
383
|
+
res.createIndex()
|
|
384
|
+
return res
|
|
385
|
+
|
|
386
|
+
def showAnns(self, anns, draw_bbox=False):
|
|
387
|
+
warnings.warn("showAnns deprecated in 1.3.0", DeprecationWarning)
|
|
388
|
+
|
|
389
|
+
def download(self, tarDir=None, imgIds=[]):
|
|
390
|
+
warnings.warn("download deprecated in 1.3.0", DeprecationWarning)
|
|
391
|
+
|
|
392
|
+
def loadNumpyAnnotations(self, data: np.ndarray) -> List[dict]:
|
|
393
|
+
"""Convert result data from array to anns.
|
|
394
|
+
|
|
395
|
+
Args:
|
|
396
|
+
data (numpy.ndarray): 2d array where each row contains
|
|
397
|
+
[imageID, x1, y1, w, h, score, class]
|
|
398
|
+
|
|
399
|
+
Return:
|
|
400
|
+
anns (python nested list): converted annotations
|
|
401
|
+
"""
|
|
402
|
+
|
|
403
|
+
self.print_function("Converting ndarray to lists...")
|
|
404
|
+
assert type(data) is np.ndarray
|
|
405
|
+
self.print_function(data.shape)
|
|
406
|
+
assert data.shape[1] == 7
|
|
407
|
+
N = data.shape[0]
|
|
408
|
+
ann = []
|
|
409
|
+
for i in range(N):
|
|
410
|
+
if i % 1000000 == 0:
|
|
411
|
+
self.print_function(f"{i}/{N}")
|
|
412
|
+
ann += [
|
|
413
|
+
{
|
|
414
|
+
"image_id": int(data[i, 0]),
|
|
415
|
+
"bbox": [data[i, 1], data[i, 2], data[i, 3], data[i, 4]],
|
|
416
|
+
"score": data[i, 5],
|
|
417
|
+
"category_id": int(data[i, 6]),
|
|
418
|
+
}
|
|
419
|
+
]
|
|
420
|
+
return ann
|
|
421
|
+
|
|
422
|
+
def annToRLE(self, ann: dict) -> dict:
|
|
423
|
+
"""Convert annotation which can be polygons, uncompressed RLE to RLE.
|
|
424
|
+
|
|
425
|
+
Args:
|
|
426
|
+
ann (dict): annotation information
|
|
427
|
+
|
|
428
|
+
Return:
|
|
429
|
+
rle (dict): run-length encoding of the annotation
|
|
430
|
+
"""
|
|
431
|
+
|
|
432
|
+
t = self.imgs[ann["image_id"]]
|
|
433
|
+
h, w = t["height"], t["width"]
|
|
434
|
+
segm = ann["segmentation"]
|
|
435
|
+
if type(segm) is list:
|
|
436
|
+
# polygon -- a single object might consist of multiple parts
|
|
437
|
+
# we merge all parts into one mask rle code
|
|
438
|
+
rles = maskUtils.frPyObjects(segm, h, w)
|
|
439
|
+
rle = maskUtils.merge(rles)
|
|
440
|
+
elif type(segm["counts"]) is list:
|
|
441
|
+
# uncompressed RLE
|
|
442
|
+
rle = maskUtils.frPyObjects(segm, h, w)
|
|
443
|
+
else:
|
|
444
|
+
# rle
|
|
445
|
+
rle = ann["segmentation"]
|
|
446
|
+
return rle
|
|
447
|
+
|
|
448
|
+
def annToMask(self, ann: dict) -> np.ndarray:
|
|
449
|
+
"""Convert annotation which can be polygons, uncompressed RLE, or RLE
|
|
450
|
+
to binary mask.
|
|
451
|
+
|
|
452
|
+
Args:
|
|
453
|
+
ann (dict): annotation information
|
|
454
|
+
|
|
455
|
+
Return:
|
|
456
|
+
mask (binary mask): mask of the annotation
|
|
457
|
+
"""
|
|
458
|
+
rle = self.annToRLE(ann)
|
|
459
|
+
mask = maskUtils.decode(rle)
|
|
460
|
+
return mask
|
|
461
|
+
|
|
462
|
+
def get_ann_ids(
|
|
463
|
+
self,
|
|
464
|
+
img_ids: List[int] = [],
|
|
465
|
+
cat_ids: List[int] = [],
|
|
466
|
+
area_rng: List[float] = [],
|
|
467
|
+
iscrowd: bool = None,
|
|
468
|
+
) -> List[int]:
|
|
469
|
+
"""Get ann ids that satisfy given filter conditions.
|
|
470
|
+
|
|
471
|
+
Args:
|
|
472
|
+
img_ids (int array) : get anns for given imgs
|
|
473
|
+
cat_ids (int array) : get anns for given cats
|
|
474
|
+
area_rng (float array) : get anns with area less than this
|
|
475
|
+
iscrowd (boolean) : get anns for given crowd label
|
|
476
|
+
|
|
477
|
+
Returns:
|
|
478
|
+
ids (int array) : integer array of ann ids
|
|
479
|
+
"""
|
|
480
|
+
return self.getAnnIds(img_ids, cat_ids, area_rng, iscrowd)
|
|
481
|
+
|
|
482
|
+
def get_cat_ids(
|
|
483
|
+
self,
|
|
484
|
+
cat_names: List[str] = [],
|
|
485
|
+
sup_names: List[str] = [],
|
|
486
|
+
cat_ids: List[int] = [],
|
|
487
|
+
) -> List[int]:
|
|
488
|
+
"""Get cat ids that satisfy given filter conditions.
|
|
489
|
+
|
|
490
|
+
Args:
|
|
491
|
+
cat_names (str array) : get cats for given names
|
|
492
|
+
sup_names (str array) : get cats for given supercategory names
|
|
493
|
+
cat_ids (int array) : get cats for given ids
|
|
494
|
+
|
|
495
|
+
Returns:
|
|
496
|
+
ids (int array) : integer array of cat ids
|
|
497
|
+
"""
|
|
498
|
+
return self.getCatIds(cat_names, sup_names, cat_ids)
|
|
499
|
+
|
|
500
|
+
def get_img_ids(self, img_ids: List[int] = [], cat_ids: List[int] = []) -> List[int]:
|
|
501
|
+
"""Get img ids that satisfy given filter conditions.
|
|
502
|
+
|
|
503
|
+
Args:
|
|
504
|
+
img_ids (int array) : get imgs for given ids
|
|
505
|
+
cat_ids (int array) : get imgs with all given cats
|
|
506
|
+
|
|
507
|
+
Returns:
|
|
508
|
+
ids (int array) : integer array of img ids
|
|
509
|
+
"""
|
|
510
|
+
return self.getImgIds(img_ids, cat_ids)
|
|
511
|
+
|
|
512
|
+
def load_anns(self, ids: List[int]) -> List[dict]:
|
|
513
|
+
"""Load anns with the specified ids.
|
|
514
|
+
|
|
515
|
+
Args:
|
|
516
|
+
ids (int array) : integer ids specifying ann
|
|
517
|
+
|
|
518
|
+
Returns:
|
|
519
|
+
anns (dict array) : loaded ann objects
|
|
520
|
+
"""
|
|
521
|
+
return self.loadAnns(ids)
|
|
522
|
+
|
|
523
|
+
def load_cats(self, ids: List[int]) -> List[dict]:
|
|
524
|
+
"""Load cats with the specified ids.
|
|
525
|
+
|
|
526
|
+
Args:
|
|
527
|
+
ids (int array) : integer ids specifying cat
|
|
528
|
+
|
|
529
|
+
Returns:
|
|
530
|
+
cats (dict array) : loaded cat objects
|
|
531
|
+
"""
|
|
532
|
+
return self.loadCats(ids)
|
|
533
|
+
|
|
534
|
+
def load_imgs(self, ids: List[int]) -> List[dict]:
|
|
535
|
+
"""Load imgs with the specified ids.
|
|
536
|
+
|
|
537
|
+
Args:
|
|
538
|
+
ids (int array) : integer ids specifying img
|
|
539
|
+
|
|
540
|
+
Returns:
|
|
541
|
+
imgs (dict array) : loaded img objects
|
|
542
|
+
"""
|
|
543
|
+
return self.loadImgs(ids)
|
|
544
|
+
|
|
545
|
+
@property
|
|
546
|
+
def img_ann_map(self) -> dict:
|
|
547
|
+
"""Return a mapping from image ids to annotation ids.
|
|
548
|
+
|
|
549
|
+
Returns:
|
|
550
|
+
imgToAnns (dict): mapping from image ids to annotation ids
|
|
551
|
+
"""
|
|
552
|
+
return self.imgToAnns
|
|
553
|
+
|
|
554
|
+
@img_ann_map.setter
|
|
555
|
+
def img_ann_map(self, value: dict):
|
|
556
|
+
"""Set the mapping from image ids to annotation ids.
|
|
557
|
+
|
|
558
|
+
Args:
|
|
559
|
+
value (dict): mapping from image ids to annotation ids
|
|
560
|
+
"""
|
|
561
|
+
self.imgToAnns = value
|
|
562
|
+
|
|
563
|
+
@property
|
|
564
|
+
def cat_img_map(self) -> dict:
|
|
565
|
+
"""Return a mapping from category ids to image ids.
|
|
566
|
+
|
|
567
|
+
Returns:
|
|
568
|
+
catToImgs (dict): mapping from category ids to image ids
|
|
569
|
+
"""
|
|
570
|
+
return self.catToImgs
|
|
571
|
+
|
|
572
|
+
@cat_img_map.setter
|
|
573
|
+
def cat_img_map(self, value: dict):
|
|
574
|
+
"""Set the mapping from category ids to image ids.
|
|
575
|
+
|
|
576
|
+
Args:
|
|
577
|
+
value (dict): mapping from category ids to image ids
|
|
578
|
+
"""
|
|
579
|
+
self.catToImgs = value
|
|
580
|
+
|
|
581
|
+
def __repr__(self):
|
|
582
|
+
s = self.__class__.__name__ + "(annotation_file) # "
|
|
583
|
+
s += f"__author__='{__author__}'; "
|
|
584
|
+
s += f"__version__='{__version__}';"
|
|
585
|
+
return s
|
|
586
|
+
|
|
587
|
+
def to_dict(self, separate_fn: bool = False) -> dict:
|
|
588
|
+
"""Convert to a standard python dictionary.
|
|
589
|
+
|
|
590
|
+
Args:
|
|
591
|
+
separate_fn (bool): whether to separate the fn category
|
|
592
|
+
|
|
593
|
+
Returns:
|
|
594
|
+
dict: a standard python dictionary
|
|
595
|
+
"""
|
|
596
|
+
|
|
597
|
+
cats = list(self.cats.values())
|
|
598
|
+
anns = list(self.anns.values())
|
|
599
|
+
|
|
600
|
+
if separate_fn:
|
|
601
|
+
max_category_id = max(cats, key=lambda x: x["id"])["id"]
|
|
602
|
+
fn_cats = [
|
|
603
|
+
dict(
|
|
604
|
+
category,
|
|
605
|
+
**{
|
|
606
|
+
"id": (category["id"] + max_category_id),
|
|
607
|
+
"name": (category["name"] + "_fn"),
|
|
608
|
+
},
|
|
609
|
+
)
|
|
610
|
+
for category in cats
|
|
611
|
+
]
|
|
612
|
+
|
|
613
|
+
for ann in anns:
|
|
614
|
+
if ann.get("fn"):
|
|
615
|
+
ann["category_id"] = ann["category_id"] + max_category_id
|
|
616
|
+
|
|
617
|
+
cats += fn_cats
|
|
618
|
+
|
|
619
|
+
return {
|
|
620
|
+
"info": {"description": "Created from faster-coco-eval"},
|
|
621
|
+
"images": list(self.imgs.values()),
|
|
622
|
+
"annotations": anns,
|
|
623
|
+
"categories": cats,
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
def __iter__(self):
|
|
627
|
+
"""Iterate over the annotations.
|
|
628
|
+
|
|
629
|
+
Args:
|
|
630
|
+
separate_fn (bool): whether to separate the fn category
|
|
631
|
+
|
|
632
|
+
Yields:
|
|
633
|
+
key, val: the key-value pair of the annotation
|
|
634
|
+
"""
|
|
635
|
+
for key, val in self.to_dict().items(): # noqa: UP028
|
|
636
|
+
yield key, val
|
|
637
|
+
|
|
638
|
+
def dump(self, output_file: Union[str, os.PathLike]):
|
|
639
|
+
"""Dump annotations to a json file.
|
|
640
|
+
|
|
641
|
+
Args:
|
|
642
|
+
output_file (str or PathLike): Path to the output json file
|
|
643
|
+
"""
|
|
644
|
+
with open(output_file, "w") as io:
|
|
645
|
+
json.dump(dict(self), io, ensure_ascii=False, indent=4)
|