Reference:

  1. https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoDemo.ipynb
  2. https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocotools/coco.py
  3. https://blog.csdn.net/yeyang911/article/details/78675942

Here is my code. But there is still a problem that when I use the function 'showAnns()' to show the instances' annotations of the image, it cannot show the figure though the code run successfully. If you have any solutions, please leave a message in the comment area. Thanks!

 import matplotlib
import numpy as np
import skimage.io as io
import matplotlib.pyplot as plt
import pylab
from pycocotools.coco import COCO
pylab.rcParams['figure.figsize'] = (8.0, 10.0) # image pixel # if skimage.io declares before pycocotools.coco, the backend will be chosen as Qt5Agg
# if pycocotools.coco declares before skimage.io, the backend will be chosen as Agg
print(matplotlib.get_backend()) dataDir = r'G:\MSCOCO 2017\annotations_trainval2017'
dataType = r'val2017'
annFile = r'{}\annotations\instances_{}.json'.format(dataDir, dataType) # initialize COCO api for instance annotations
coco = COCO(annotation_file=annFile) # COCO api class that loads COCO annotation file and prepare data structures.
# loading annotations into memory...
# Done (t=0.80s)
# creating index...
# index created! # print(coco.info()) # Print information about the annotation file.
# description: COCO 2017 Dataset
# url: http://cocodataset.org
# version: 1.0
# year: 2017
# contributor: COCO Consortium
# date_created: 2017/09/01
# None # display COCO categories and supercategories
# coco.loadCats(self, ids=[]): Load cats with the specified ids.
cats = coco.loadCats(coco.getCatIds())
# print(cats)
# [{'supercategory': 'person', 'id': 1, 'name': 'person'},
# {'supercategory': 'vehicle', 'id': 2, 'name': 'bicycle'},
# {'supercategory': 'vehicle', 'id': 3, 'name': 'car'},
# {...}, {...}, {...}, ... ...,
# {'supercategory': 'indoor', 'id': 90, 'name': 'toothbrush'}]
nms = [cat['name'] for cat in cats]
# print('COCO categories: \n{}\n'.format(' '.join(nms)))
# person bicycle car motorcycle airplane ... hair drier toothbrush
nms = set([cat['supercategory'] for cat in cats])
# print('COCO supercategories: \n{}'.format(' '.join(nms)))
# vehicle person kitchen electronic appliance indoor accessory animal food furniture outdoor sports # get all images containing given categories, select one at random
catIds = coco.getCatIds(catNms=['person', 'dog', 'skateboard'])
# print(catIds) # [1, 18, 41]
imgIds = coco.getImgIds(catIds=catIds) # param catIds (int array): get images with all given categories
# imgIds = coco.getImgIds(imgIds=[324158]) # param imgIds (int array): get images for given ids
index = np.random.randint(0, len(imgIds))
# print('randomly selected imgId: %d' % index)
img = coco.loadImgs(imgIds[index])[0] # Load images with specified ids.
# print(img)
# if index=2, print:
# {'license': 2, 'file_name': '000000279278.jpg', 'coco_url': 'http://images.cocodataset.org/val2017/000000279278.jpg',
# 'height': 429, 'width': 640, 'date_captured': '2013-11-15 01:07:24',
# 'flickr_url': 'http://farm7.staticflickr.com/6101/6275412942_f8dc734c3f_z.jpg', 'id': 279278} # load and display image
# i = io.imread('%s/image/%s/%s' % (dataDir, dataType, img['file_name']))
# use url to load image
# print(img['coco_url']) # http://images.cocodataset.org/val2017/000000279278.jpg
i = io.imread(img['coco_url'])
plt.axis('off')
plt.imshow(i)
# print(plt.imshow(i)) # AxesImage(100, 110; 620x770)
plt.show() # 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) # initialize COCO api for person keypoints annotations
annFile = '{}/annotations/person_keypoints_{}.json'.format(dataDir, dataType)
coco_kps = COCO(annFile) # 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) # initialize COCO api for caption annotations
annFile = '{}/annotations/captions_{}.json'.format(dataDir, dataType)
coco_caps = COCO(annFile) # 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()

最新文章

  1. HTTP协议简解
  2. JS表单设置值
  3. 022. ASP.NET为DataSet中数据集添加关系及动态创建主子表和添加主子表关系
  4. hdoj 5500 Reorder the Books
  5. 【Flume NG用户指南】(2)构造
  6. ZooKeeper 主要的操作演示样品
  7. LeetCode 385. Mini Parse
  8. mycat 测试主从读写分离
  9. gevent模块学习(二)
  10. MacBook Home End
  11. python ----django---打包重用
  12. jloi2015
  13. CookieUitl
  14. php查询快递的类
  15. C# 组件模组引用第三方组件问题
  16. Navicat 的安装及破解
  17. 第78讲:Type与Class实战详解
  18. 第一次项目上Linux服务器(六:Nginx安装及相关命令(转))
  19. 【arm学习】我的第一个裸板程序
  20. jq table页二级联动

热门文章

  1. ssh框架错误:org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role。
  2. 1001. 温度转换 (Standard IO)
  3. Ubuntu16.04安装TensorFlow
  4. docker 入门 (一)重要概念介绍
  5. MongoDB固定集合(capped collection)
  6. python实现文件夹的排序
  7. 2017-2018-1 20155323《信息安全技术》实验二 Windows口令破解
  8. 20155331 2016-2017-2 《Java程序设计》第10周学习总结
  9. 20155339 《信息安全技术》实验二、Windows口令破解实验报告
  10. asp.net self host and urlacl(解决UnHandledException Message:拒绝访问的问题)