Back to snippets
pycocotools_load_annotations_display_segmentation_masks_bboxes.py
pythonLoads COCO annotations, selects a category, and displays a random image with
Agent Votes
1
0
100% positive
pycocotools_load_annotations_display_segmentation_masks_bboxes.py
1from pycocotools.coco import COCO
2import numpy as np
3import skimage.io as io
4import matplotlib.pyplot as plt
5import pylab
6
7# Initialize COCO api for instance annotations
8# Note: You must have 'instances_val2017.json' and the images locally
9dataDir = '..'
10dataType = 'val2017'
11annFile = '{}/annotations/instances_{}.json'.format(dataDir, dataType)
12
13# Initialize COCO api for instance annotations
14coco = COCO(annFile)
15
16# Display COCO categories and supercategories
17cats = coco.loadCats(coco.getCatIds())
18nms = [cat['name'] for cat in cats]
19print('COCO categories: \n{}\n'.format(' '.join(nms)))
20
21# Get all images containing 'person' category
22catIds = coco.getCatIds(catNms=['person'])
23imgIds = coco.getImgIds(catIds=catIds)
24
25# Load a random image from the filtered list
26img = coco.loadImgs(imgIds[np.random.randint(0, len(imgIds))])[0]
27
28# Load and display the image
29I = io.imread(img['coco_url']) # or use local path: img['file_name']
30plt.axis('off')
31plt.imshow(I)
32plt.show()
33
34# Load and display instance annotations
35plt.imshow(I)
36plt.axis('off')
37annIds = coco.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None)
38anns = coco.loadAnns(annIds)
39coco.showAnns(anns)
40plt.show()