halpecocotools 0.0.0__cp312-cp312-macosx_14_0_arm64.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.
@@ -0,0 +1 @@
1
+ __author__ = 'tylin'
halpecocotools/coco.py ADDED
@@ -0,0 +1,456 @@
1
+ __author__ = 'tylin'
2
+ __version__ = '2.0'
3
+ # Interface for accessing the Microsoft COCO dataset.
4
+
5
+ # Microsoft COCO is a large image dataset designed for object detection,
6
+ # segmentation, and caption generation. pycocotools is a Python API that
7
+ # assists in loading, parsing and visualizing the annotations in COCO.
8
+ # Please visit http://mscoco.org/ for more information on COCO, including
9
+ # for the data, paper, and tutorials. The exact format of the annotations
10
+ # is also described on the COCO website. For example usage of the pycocotools
11
+ # please see pycocotools_demo.ipynb. In addition to this API, please download both
12
+ # the COCO images and annotations in order to run the demo.
13
+
14
+ # An alternative to using the API is to load the annotations directly
15
+ # into Python dictionary
16
+ # Using the API provides additional utility functions. Note that this API
17
+ # supports both *instance* and *caption* annotations. In the case of
18
+ # captions not all functions are defined (e.g. categories are undefined).
19
+
20
+ # The following API functions are defined:
21
+ # COCO - COCO api class that loads COCO annotation file and prepare data structures.
22
+ # decodeMask - Decode binary mask M encoded via run-length encoding.
23
+ # encodeMask - Encode binary mask M using run-length encoding.
24
+ # getAnnIds - Get ann ids that satisfy given filter conditions.
25
+ # getCatIds - Get cat ids that satisfy given filter conditions.
26
+ # getImgIds - Get img ids that satisfy given filter conditions.
27
+ # loadAnns - Load anns with the specified ids.
28
+ # loadCats - Load cats with the specified ids.
29
+ # loadImgs - Load imgs with the specified ids.
30
+ # annToMask - Convert segmentation in an annotation to binary mask.
31
+ # showAnns - Display the specified annotations.
32
+ # loadRes - Load algorithm results and create API for accessing them.
33
+ # download - Download COCO images from mscoco.org server.
34
+ # Throughout the API "ann"=annotation, "cat"=category, and "img"=image.
35
+ # Help on each functions can be accessed by: "help COCO>function".
36
+
37
+ # See also COCO>decodeMask,
38
+ # COCO>encodeMask, COCO>getAnnIds, COCO>getCatIds,
39
+ # COCO>getImgIds, COCO>loadAnns, COCO>loadCats,
40
+ # COCO>loadImgs, COCO>annToMask, COCO>showAnns
41
+
42
+ # The original Microsoft COCO Toolbox is written
43
+ # by Piotr Dollar and Tsung-Yi Lin, 2015.
44
+ # Licensed under the Simplified BSD License [see coco/license.txt]
45
+ #
46
+ # Updated and renamed to Halpe COCO Toolbox (halpecocotools) \
47
+ # by Haoyi Zhu in 2021. The Halpe COCO Toolbox is
48
+ # developed to support Halpe Full-body dataset.
49
+
50
+ import json
51
+ import time
52
+ import matplotlib.pyplot as plt
53
+ from matplotlib.collections import PatchCollection
54
+ from matplotlib.patches import Polygon
55
+ import numpy as np
56
+ import copy
57
+ import itertools
58
+ from . import mask as maskUtils
59
+ import os
60
+ from collections import defaultdict
61
+ import sys
62
+ PYTHON_VERSION = sys.version_info[0]
63
+ if PYTHON_VERSION == 2:
64
+ from urllib import urlretrieve
65
+ elif PYTHON_VERSION == 3:
66
+ from urllib.request import urlretrieve
67
+
68
+
69
+ def _isArrayLike(obj):
70
+ return hasattr(obj, '__iter__') and hasattr(obj, '__len__')
71
+
72
+
73
+ class COCO:
74
+ def __init__(self, annotation_file=None):
75
+ """
76
+ Constructor of Microsoft COCO helper class for reading and visualizing annotations.
77
+ :param annotation_file (str): location of annotation file
78
+ :param image_folder (str): location to the folder that hosts images.
79
+ :return:
80
+ """
81
+ # load dataset
82
+ self.dataset,self.anns,self.cats,self.imgs = dict(),dict(),dict(),dict()
83
+ self.imgToAnns, self.catToImgs = defaultdict(list), defaultdict(list)
84
+ if not annotation_file == None:
85
+ print('loading annotations into memory...')
86
+ tic = time.time()
87
+ dataset = json.load(open(annotation_file, 'r'))
88
+ assert type(dataset)==dict, 'annotation file format {} not supported'.format(type(dataset))
89
+ print('Done (t={:0.2f}s)'.format(time.time()- tic))
90
+ self.dataset = dataset
91
+ self.createIndex()
92
+
93
+ def createIndex(self):
94
+ # create index
95
+ print('creating index...')
96
+ anns, cats, imgs = {}, {}, {}
97
+ imgToAnns,catToImgs = defaultdict(list),defaultdict(list)
98
+ if 'annotations' in self.dataset:
99
+ for ann in self.dataset['annotations']:
100
+ imgToAnns[ann['image_id']].append(ann)
101
+ anns[ann['id']] = ann
102
+
103
+ if 'images' in self.dataset:
104
+ for img in self.dataset['images']:
105
+ imgs[img['id']] = img
106
+
107
+ if 'categories' in self.dataset:
108
+ for cat in self.dataset['categories']:
109
+ cats[cat['id']] = cat
110
+
111
+ if 'annotations' in self.dataset and 'categories' in self.dataset:
112
+ for ann in self.dataset['annotations']:
113
+ catToImgs[ann['category_id']].append(ann['image_id'])
114
+
115
+ print('index created!')
116
+
117
+ # create class members
118
+ self.anns = anns
119
+ self.imgToAnns = imgToAnns
120
+ self.catToImgs = catToImgs
121
+ self.imgs = imgs
122
+ self.cats = cats
123
+
124
+ def info(self):
125
+ """
126
+ Print information about the annotation file.
127
+ :return:
128
+ """
129
+ for key, value in self.dataset['info'].items():
130
+ print('{}: {}'.format(key, value))
131
+
132
+ def getAnnIds(self, imgIds=[], catIds=[], areaRng=[], iscrowd=None):
133
+ """
134
+ Get ann ids that satisfy given filter conditions. default skips that filter
135
+ :param 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 (e.g. [0 inf])
138
+ iscrowd (boolean) : get anns for given crowd label (False or True)
139
+ :return: ids (int array) : integer array of ann ids
140
+ """
141
+ imgIds = imgIds if _isArrayLike(imgIds) else [imgIds]
142
+ catIds = catIds if _isArrayLike(catIds) else [catIds]
143
+
144
+ if len(imgIds) == len(catIds) == len(areaRng) == 0:
145
+ anns = self.dataset['annotations']
146
+ else:
147
+ if not len(imgIds) == 0:
148
+ lists = [self.imgToAnns[imgId] for imgId in imgIds if imgId in self.imgToAnns]
149
+ anns = list(itertools.chain.from_iterable(lists))
150
+ else:
151
+ anns = self.dataset['annotations']
152
+ anns = anns if len(catIds) == 0 else [ann for ann in anns if ann['category_id'] in catIds]
153
+ anns = anns if len(areaRng) == 0 else [ann for ann in anns if ann['area'] > areaRng[0] and ann['area'] < areaRng[1]]
154
+ if not iscrowd == None:
155
+ ids = [ann['id'] for ann in anns if ann['iscrowd'] == iscrowd]
156
+ else:
157
+ ids = [ann['id'] for ann in anns]
158
+ return ids
159
+
160
+ def getCatIds(self, catNms=[], supNms=[], catIds=[]):
161
+ """
162
+ filtering parameters. default skips that filter.
163
+ :param catNms (str array) : get cats for given cat names
164
+ :param supNms (str array) : get cats for given supercategory names
165
+ :param catIds (int array) : get cats for given cat ids
166
+ :return: ids (int array) : integer array of cat ids
167
+ """
168
+ catNms = catNms if _isArrayLike(catNms) else [catNms]
169
+ supNms = supNms if _isArrayLike(supNms) else [supNms]
170
+ catIds = catIds if _isArrayLike(catIds) else [catIds]
171
+
172
+ if len(catNms) == len(supNms) == len(catIds) == 0:
173
+ cats = self.dataset['categories']
174
+ else:
175
+ cats = self.dataset['categories']
176
+ cats = cats if len(catNms) == 0 else [cat for cat in cats if cat['name'] in catNms]
177
+ cats = cats if len(supNms) == 0 else [cat for cat in cats if cat['supercategory'] in supNms]
178
+ cats = cats if len(catIds) == 0 else [cat for cat in cats if cat['id'] in catIds]
179
+ ids = [cat['id'] for cat in cats]
180
+ return ids
181
+
182
+ def getImgIds(self, imgIds=[], catIds=[]):
183
+ '''
184
+ Get img ids that satisfy given filter conditions.
185
+ :param imgIds (int array) : get imgs for given ids
186
+ :param catIds (int array) : get imgs with all given cats
187
+ :return: ids (int array) : integer array of img ids
188
+ '''
189
+ imgIds = imgIds if _isArrayLike(imgIds) else [imgIds]
190
+ catIds = catIds if _isArrayLike(catIds) else [catIds]
191
+
192
+ if len(imgIds) == len(catIds) == 0:
193
+ ids = self.imgs.keys()
194
+ else:
195
+ ids = set(imgIds)
196
+ for i, catId in enumerate(catIds):
197
+ if i == 0 and len(ids) == 0:
198
+ ids = set(self.catToImgs[catId])
199
+ else:
200
+ ids &= set(self.catToImgs[catId])
201
+ return list(ids)
202
+
203
+ def loadAnns(self, ids=[]):
204
+ """
205
+ Load anns with the specified ids.
206
+ :param ids (int array) : integer ids specifying anns
207
+ :return: anns (object array) : loaded ann objects
208
+ """
209
+ if _isArrayLike(ids):
210
+ return [self.anns[id] for id in ids]
211
+ elif type(ids) == int:
212
+ return [self.anns[ids]]
213
+
214
+ def loadCats(self, ids=[]):
215
+ """
216
+ Load cats with the specified ids.
217
+ :param ids (int array) : integer ids specifying cats
218
+ :return: cats (object array) : loaded cat objects
219
+ """
220
+ if _isArrayLike(ids):
221
+ return [self.cats[id] for id in ids]
222
+ elif type(ids) == int:
223
+ return [self.cats[ids]]
224
+
225
+ def loadImgs(self, ids=[]):
226
+ """
227
+ Load anns with the specified ids.
228
+ :param ids (int array) : integer ids specifying img
229
+ :return: imgs (object array) : loaded img objects
230
+ """
231
+ if _isArrayLike(ids):
232
+ return [self.imgs[id] for id in ids]
233
+ elif type(ids) == int:
234
+ return [self.imgs[ids]]
235
+
236
+ def showAnns(self, anns):
237
+ """
238
+ Display the specified annotations.
239
+ :param anns (array of object): annotations to display
240
+ :return: None
241
+ """
242
+ if len(anns) == 0:
243
+ return 0
244
+ if 'segmentation' in anns[0] or 'keypoints' in anns[0]:
245
+ datasetType = 'instances'
246
+ elif 'caption' in anns[0]:
247
+ datasetType = 'captions'
248
+ else:
249
+ raise Exception('datasetType not supported')
250
+ if datasetType == 'instances':
251
+ ax = plt.gca()
252
+ ax.set_autoscale_on(False)
253
+ polygons = []
254
+ color = []
255
+ for ann in anns:
256
+ c = (np.random.random((1, 3))*0.6+0.4).tolist()[0]
257
+ if 'segmentation' in ann:
258
+ if type(ann['segmentation']) == list:
259
+ # polygon
260
+ for seg in ann['segmentation']:
261
+ poly = np.array(seg).reshape((int(len(seg)/2), 2))
262
+ polygons.append(Polygon(poly))
263
+ color.append(c)
264
+ else:
265
+ # mask
266
+ t = self.imgs[ann['image_id']]
267
+ if type(ann['segmentation']['counts']) == list:
268
+ rle = maskUtils.frPyObjects([ann['segmentation']], t['height'], t['width'])
269
+ else:
270
+ rle = [ann['segmentation']]
271
+ m = maskUtils.decode(rle)
272
+ img = np.ones( (m.shape[0], m.shape[1], 3) )
273
+ if ann['iscrowd'] == 1:
274
+ color_mask = np.array([2.0,166.0,101.0])/255
275
+ if ann['iscrowd'] == 0:
276
+ color_mask = np.random.random((1, 3)).tolist()[0]
277
+ for i in range(3):
278
+ img[:,:,i] = color_mask[i]
279
+ ax.imshow(np.dstack( (img, m*0.5) ))
280
+ if 'keypoints' in ann and type(ann['keypoints']) == list:
281
+ # skeleton
282
+ sks = np.array([(0, 1), (0, 2), (1, 3), (2, 4), # Head
283
+ (5, 18), (6, 18), (5, 7), (7, 9), (6, 8), (8, 10),# Body
284
+ (17, 18), (18, 19), (19, 11), (19, 12),
285
+ (11, 13), (12, 14), (13, 15), (14, 16),
286
+ (20, 24), (21, 25), (23, 25), (22, 24), (15, 24), (16, 25),# Foot
287
+ (26, 27),(27, 28),(28, 29),(29, 30),(30, 31),(31, 32),(32, 33),(33, 34),(34, 35),(35, 36),(36, 37),(37, 38),#Face
288
+ (38, 39),(39, 40),(40, 41),(41, 42),(43, 44),(44, 45),(45, 46),(46, 47),(48, 49),(49, 50),(50, 51),(51, 52),#Face
289
+ (53, 54),(54, 55),(55, 56),(57, 58),(58, 59),(59, 60),(60, 61),(62, 63),(63, 64),(64, 65),(65, 66),(66, 67),#Face
290
+ (68, 69),(69, 70),(70, 71),(71, 72),(72, 73),(74, 75),(75, 76),(76, 77),(77, 78),(78, 79),(79, 80),(80, 81),#Face
291
+ (81, 82),(82, 83),(83, 84),(84, 85),(85, 86),(86, 87),(87, 88),(88, 89),(89, 90),(90, 91),(91, 92),(92, 93),#Face
292
+ (94,95),(95,96),(96,97),(97,98),(94,99),(99,100),(100,101),(101,102),(94,103),(103,104),(104,105),#LeftHand
293
+ (105,106),(94,107),(107,108),(108,109),(109,110),(94,111),(111,112),(112,113),(113,114),#LeftHand
294
+ (115,116),(116,117),(117,118),(118,119),(115,120),(120,121),(121,122),(122,123),(115,124),(124,125),#RightHand
295
+ (125,126),(126,127),(115,128),(128,129),(129,130),(130,131),(115,132),(132,133),(133,134),(134,135)#RightHand
296
+ ])
297
+ kp = np.array(ann['keypoints'])
298
+ x = kp[0::3]
299
+ y = kp[1::3]
300
+ v = kp[2::3]
301
+ for i, sk in enumerate(sks):
302
+ if np.all(v[sk]>0):
303
+ if i < 24:
304
+ plt.plot(x[sk],y[sk], linewidth=3, color=c)
305
+ else:
306
+ plt.plot(x[sk],y[sk], linewidth=1, color='w')
307
+ plt.plot(x[0:26][v[0:26]>0], y[0:26][v[0:26]>0],'o',markersize=8, markerfacecolor=c, markeredgecolor='k',markeredgewidth=2)
308
+ plt.plot(x[0:26][v[0:26]>1], y[0:26][v[0:26]>1],'o',markersize=8, markerfacecolor=c, markeredgecolor=c, markeredgewidth=2)
309
+
310
+ plt.plot(x[26:][v[26:]>0], y[26:][v[26:]>0],'o',markersize=1, markerfacecolor='w', markeredgecolor='w',markeredgewidth=-1)
311
+ plt.plot(x[26:][v[26:]>1], y[26:][v[26:]>1],'o',markersize=2, markerfacecolor='w', markeredgecolor='w', markeredgewidth=-1)
312
+ p = PatchCollection(polygons, facecolor=color, linewidths=0, alpha=0.4)
313
+ ax.add_collection(p)
314
+ p = PatchCollection(polygons, facecolor='none', edgecolors=color, linewidths=2)
315
+ ax.add_collection(p)
316
+ elif datasetType == 'captions':
317
+ for ann in anns:
318
+ print(ann['caption'])
319
+
320
+ def loadRes(self, resFile):
321
+ """
322
+ Load result file and return a result api object.
323
+ :param resFile (str) : file name of result file
324
+ :return: res (obj) : result api object
325
+ """
326
+ res = COCO()
327
+ res.dataset['images'] = [img for img in self.dataset['images']]
328
+
329
+ print('Loading and preparing results...')
330
+ tic = time.time()
331
+ if type(resFile) == str or type(resFile) == unicode:
332
+ anns = json.load(open(resFile))
333
+ elif type(resFile) == np.ndarray:
334
+ anns = self.loadNumpyAnnotations(resFile)
335
+ else:
336
+ anns = resFile
337
+ assert type(anns) == list, 'results in not an array of objects'
338
+ annsImgIds = [ann['image_id'] for ann in anns]
339
+ assert set(annsImgIds) == (set(annsImgIds) & set(self.getImgIds())), \
340
+ 'Results do not correspond to current coco set'
341
+ if 'caption' in anns[0]:
342
+ imgIds = set([img['id'] for img in res.dataset['images']]) & set([ann['image_id'] for ann in anns])
343
+ res.dataset['images'] = [img for img in res.dataset['images'] if img['id'] in imgIds]
344
+ for id, ann in enumerate(anns):
345
+ ann['id'] = id+1
346
+ elif 'bbox' in anns[0] and not anns[0]['bbox'] == []:
347
+ res.dataset['categories'] = copy.deepcopy(self.dataset['categories'])
348
+ for id, ann in enumerate(anns):
349
+ bb = ann['bbox']
350
+ x1, x2, y1, y2 = [bb[0], bb[0]+bb[2], bb[1], bb[1]+bb[3]]
351
+ if not 'segmentation' in ann:
352
+ ann['segmentation'] = [[x1, y1, x1, y2, x2, y2, x2, y1]]
353
+ ann['area'] = bb[2]*bb[3]
354
+ ann['id'] = id+1
355
+ ann['iscrowd'] = 0
356
+ elif 'segmentation' in anns[0]:
357
+ res.dataset['categories'] = copy.deepcopy(self.dataset['categories'])
358
+ for id, ann in enumerate(anns):
359
+ # now only support compressed RLE format as segmentation results
360
+ ann['area'] = maskUtils.area(ann['segmentation'])
361
+ if not 'bbox' in ann:
362
+ ann['bbox'] = maskUtils.toBbox(ann['segmentation'])
363
+ ann['id'] = id+1
364
+ ann['iscrowd'] = 0
365
+ elif 'keypoints' in anns[0]:
366
+ res.dataset['categories'] = copy.deepcopy(self.dataset['categories'])
367
+ for id, ann in enumerate(anns):
368
+ s = ann['keypoints']
369
+ x = s[0::3]
370
+ y = s[1::3]
371
+ x0,x1,y0,y1 = np.min(x), np.max(x), np.min(y), np.max(y)
372
+ ann['area'] = (x1-x0)*(y1-y0)
373
+ ann['id'] = id + 1
374
+ ann['bbox'] = [x0,y0,x1-x0,y1-y0]
375
+ print('DONE (t={:0.2f}s)'.format(time.time()- tic))
376
+
377
+ res.dataset['annotations'] = anns
378
+ res.createIndex()
379
+ return res
380
+
381
+ def download(self, tarDir = None, imgIds = [] ):
382
+ '''
383
+ Download COCO images from mscoco.org server.
384
+ :param tarDir (str): COCO results directory name
385
+ imgIds (list): images to be downloaded
386
+ :return:
387
+ '''
388
+ if tarDir is None:
389
+ print('Please specify target directory')
390
+ return -1
391
+ if len(imgIds) == 0:
392
+ imgs = self.imgs.values()
393
+ else:
394
+ imgs = self.loadImgs(imgIds)
395
+ N = len(imgs)
396
+ if not os.path.exists(tarDir):
397
+ os.makedirs(tarDir)
398
+ for i, img in enumerate(imgs):
399
+ tic = time.time()
400
+ fname = os.path.join(tarDir, img['file_name'])
401
+ if not os.path.exists(fname):
402
+ urlretrieve(img['coco_url'], fname)
403
+ print('downloaded {}/{} images (t={:0.1f}s)'.format(i, N, time.time()- tic))
404
+
405
+ def loadNumpyAnnotations(self, data):
406
+ """
407
+ Convert result data from a numpy array [Nx7] where each row contains {imageID,x1,y1,w,h,score,class}
408
+ :param data (numpy.ndarray)
409
+ :return: annotations (python nested list)
410
+ """
411
+ print('Converting ndarray to lists...')
412
+ assert(type(data) == np.ndarray)
413
+ print(data.shape)
414
+ assert(data.shape[1] == 7)
415
+ N = data.shape[0]
416
+ ann = []
417
+ for i in range(N):
418
+ if i % 1000000 == 0:
419
+ print('{}/{}'.format(i,N))
420
+ ann += [{
421
+ 'image_id' : int(data[i, 0]),
422
+ 'bbox' : [ data[i, 1], data[i, 2], data[i, 3], data[i, 4] ],
423
+ 'score' : data[i, 5],
424
+ 'category_id': int(data[i, 6]),
425
+ }]
426
+ return ann
427
+
428
+ def annToRLE(self, ann):
429
+ """
430
+ Convert annotation which can be polygons, uncompressed RLE to RLE.
431
+ :return: binary mask (numpy 2D array)
432
+ """
433
+ t = self.imgs[ann['image_id']]
434
+ h, w = t['height'], t['width']
435
+ segm = ann['segmentation']
436
+ if type(segm) == list:
437
+ # polygon -- a single object might consist of multiple parts
438
+ # we merge all parts into one mask rle code
439
+ rles = maskUtils.frPyObjects(segm, h, w)
440
+ rle = maskUtils.merge(rles)
441
+ elif type(segm['counts']) == list:
442
+ # uncompressed RLE
443
+ rle = maskUtils.frPyObjects(segm, h, w)
444
+ else:
445
+ # rle
446
+ rle = ann['segmentation']
447
+ return rle
448
+
449
+ def annToMask(self, ann):
450
+ """
451
+ Convert annotation which can be polygons, uncompressed RLE, or RLE to binary mask.
452
+ :return: binary mask (numpy 2D array)
453
+ """
454
+ rle = self.annToRLE(ann)
455
+ m = maskUtils.decode(rle)
456
+ return m