In [1]:
%matplotlib inline
from pycocotools.coco import COCO
import numpy as np
import skimage.io as io
import matplotlib.pyplot as plt
import pylab
pylab.rcParams['figure.figsize'] = (10.0, 8.0)

In [2]:
dataDir='..'
dataType='train2014'
annFile='%s/annotations/instances_%s.json'%(dataDir,dataType)

In [3]:
# initialize COCO api for instance annotations
coco=COCO(annFile)


loading annotations into memory...
Done (t=7.69s)
creating index...
index created!

In [37]:
def findCatInfoById(parCats, parId):
    ret=None
    for ii in parCats:
        if ii['id']==parId:
            return ii
    return ret

# display COCO categories and supercategories
cats = coco.loadCats(coco.getCatIds())
nms=[cat['name'] for cat in cats]
print 'COCO categories: \n\n', ' '.join(nms)

nms = set([cat['supercategory'] for cat in cats])
print 'COCO supercategories: \n', ' '.join(nms)


COCO categories: 

person bicycle car motorcycle airplane bus train truck boat traffic light fire hydrant stop sign parking meter bench bird cat dog horse sheep cow elephant bear zebra giraffe backpack umbrella handbag tie suitcase frisbee skis snowboard sports ball kite baseball bat baseball glove skateboard surfboard tennis racket bottle wine glass cup fork knife spoon bowl banana apple sandwich orange broccoli carrot hot dog pizza donut cake chair couch potted plant bed dining table toilet tv laptop mouse remote keyboard cell phone microwave oven toaster sink refrigerator book clock vase scissors teddy bear hair drier toothbrush
COCO supercategories: 
outdoor food indoor appliance sports person animal vehicle furniture accessory electronic kitchen

In [38]:
listFoodsIdx=coco.getCatIds(supNms=['food'])
print(listFoodsIdx)
for ii,idx in enumerate(listFoodsIdx):
    tmpCat=findCatInfoById(cats, idx)
    print('%d [%d]:\t%s (%s)' % (ii, idx, tmpCat['name'], tmpCat['supercategory']))


[52, 53, 54, 55, 56, 57, 58, 59, 60, 61]
0 [52]:	banana (food)
1 [53]:	apple (food)
2 [54]:	sandwich (food)
3 [55]:	orange (food)
4 [56]:	broccoli (food)
5 [57]:	carrot (food)
6 [58]:	hot dog (food)
7 [59]:	pizza (food)
8 [60]:	donut (food)
9 [61]:	cake (food)

In [ ]:
imgIds = coco.getImgIds(catIds=[listFoodsIdx[0]])
listImages = coco.loadImgs(imgIds)
print('%d/%d' % (len(imgIds), len(listImages)))
tmpImgPosIdx=0
timg = io.imread('%s/%s/%s' % (dataDir, dataType, listImages[tmpImgPosIdx]['file_name']))
plt.imshow(timg)

In [ ]:
# annIds = coco.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None)
tmpListAnnIds=coco.getAnnIds(imgIds=[listImages[tmpImgPosIdx]['id']], catIds=[listFoodsIdx[0]], iscrowd=None)
print(len(tmpListAnnIds))
anns = coco.loadAnns(tmpListAnnIds)
plt.imshow(timg); plt.axis('off')
coco.showAnns(anns)

In [77]:
anns[0].keys()


Out[77]:
[u'segmentation',
 u'area',
 u'iscrowd',
 u'image_id',
 u'bbox',
 u'category_id',
 u'id']

In [44]:
# get all images containing given categories, select one at random
catIds = coco.getCatIds(catNms=['person','dog','skateboard']);
imgIds = coco.getImgIds(catIds=catIds );
img = coco.loadImgs(imgIds[np.random.randint(0,len(imgIds))])[0]

In [ ]:
# load and display image
# I = io.imread('%s/images/%s/%s'%(dataDir,dataType,img['file_name']))
# use url to load image
I = io.imread('http://mscoco.org/images/%d'%(img['id']))
plt.figure(); plt.axis('off')
plt.imshow(I)
plt.show()

In [ ]:
# load and display instance annotations
plt.imshow(I); plt.axis('off')
annIds = coco.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None)
anns = coco.loadAnns(annIds)
coco.showAnns(anns)

In [10]:
# initialize COCO api for person keypoints annotations
annFile = '%s/annotations/person_keypoints_%s.json'%(dataDir,dataType)
coco_kps=COCO(annFile)


loading annotations into memory...
Done (t=13.65s)
creating index...
index created!

In [ ]:
# load and display keypoints annotations
plt.imshow(I); plt.axis('off')
ax = plt.gca()
annIds = coco_kps.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None)
anns = coco_kps.loadAnns(annIds)
coco_kps.showAnns(anns)

In [12]:
# initialize COCO api for caption annotations
annFile = '%s/annotations/captions_%s.json'%(dataDir,dataType)
coco_caps=COCO(annFile)


loading annotations into memory...
Done (t=4.08s)
creating index...
index created!

In [ ]:
# load and display caption annotations
annIds = coco_caps.getAnnIds(imgIds=img['id']);
anns = coco_caps.loadAnns(annIds)
coco_caps.showAnns(anns)
plt.imshow(I); plt.axis('off')
plt.show()