coco.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. __author__ = 'tylin'
  2. __version__ = '1.0.1'
  3. # Interface for accessing the Microsoft COCO dataset.
  4. # Microsoft COCO is a large image dataset designed for object detection,
  5. # segmentation, and caption generation. pycocotools is a Python API that
  6. # assists in loading, parsing and visualizing the annotations in COCO.
  7. # Please visit http://mscoco.org/ for more information on COCO, including
  8. # for the data, paper, and tutorials. The exact format of the annotations
  9. # is also described on the COCO website. For example usage of the pycocotools
  10. # please see pycocotools_demo.ipynb. In addition to this API, please download both
  11. # the COCO images and annotations in order to run the demo.
  12. # An alternative to using the API is to load the annotations directly
  13. # into Python dictionary
  14. # Using the API provides additional utility functions. Note that this API
  15. # supports both *instance* and *caption* annotations. In the case of
  16. # captions not all functions are defined (e.g. categories are undefined).
  17. # The following API functions are defined:
  18. # COCO - COCO api class that loads COCO annotation file and prepare data structures.
  19. # decodeMask - Decode binary mask M encoded via run-length encoding.
  20. # encodeMask - Encode binary mask M using run-length encoding.
  21. # getAnnIds - Get ann ids that satisfy given filter conditions.
  22. # getCatIds - Get cat ids that satisfy given filter conditions.
  23. # getImgIds - Get img ids that satisfy given filter conditions.
  24. # loadAnns - Load anns with the specified ids.
  25. # loadCats - Load cats with the specified ids.
  26. # loadImgs - Load imgs with the specified ids.
  27. # segToMask - Convert polygon segmentation to binary mask.
  28. # showAnns - Display the specified annotations.
  29. # loadRes - Load algorithm results and create API for accessing them.
  30. # download - Download COCO images from mscoco.org server.
  31. # Throughout the API "ann"=annotation, "cat"=category, and "img"=image.
  32. # Help on each functions can be accessed by: "help COCO>function".
  33. # See also COCO>decodeMask,
  34. # COCO>encodeMask, COCO>getAnnIds, COCO>getCatIds,
  35. # COCO>getImgIds, COCO>loadAnns, COCO>loadCats,
  36. # COCO>loadImgs, COCO>segToMask, COCO>showAnns
  37. # Microsoft COCO Toolbox. version 2.0
  38. # Data, paper, and tutorials available at: http://mscoco.org/
  39. # Code written by Piotr Dollar and Tsung-Yi Lin, 2014.
  40. # Licensed under the Simplified BSD License [see bsd.txt]
  41. import json
  42. import datetime
  43. import time
  44. import matplotlib.pyplot as plt
  45. from matplotlib.collections import PatchCollection
  46. from matplotlib.patches import Polygon
  47. import numpy as np
  48. from skimage.draw import polygon
  49. import urllib
  50. import copy
  51. import itertools
  52. import mask
  53. import os
  54. class COCO:
  55. def __init__(self, annotation_file=None):
  56. """
  57. Constructor of Microsoft COCO helper class for reading and visualizing annotations.
  58. :param annotation_file (str): location of annotation file
  59. :param image_folder (str): location to the folder that hosts images.
  60. :return:
  61. """
  62. # load dataset
  63. self.dataset = {}
  64. self.anns = []
  65. self.imgToAnns = {}
  66. self.catToImgs = {}
  67. self.imgs = {}
  68. self.cats = {}
  69. if not annotation_file == None:
  70. print 'loading annotations into memory...'
  71. tic = time.time()
  72. dataset = json.load(open(annotation_file, 'r'))
  73. print 'Done (t=%0.2fs)'%(time.time()- tic)
  74. self.dataset = dataset
  75. self.createIndex()
  76. def createIndex(self):
  77. # create index
  78. print 'creating index...'
  79. anns = {}
  80. imgToAnns = {}
  81. catToImgs = {}
  82. cats = {}
  83. imgs = {}
  84. if 'annotations' in self.dataset:
  85. imgToAnns = {ann['image_id']: [] for ann in self.dataset['annotations']}
  86. anns = {ann['id']: [] for ann in self.dataset['annotations']}
  87. for ann in self.dataset['annotations']:
  88. imgToAnns[ann['image_id']] += [ann]
  89. anns[ann['id']] = ann
  90. if 'images' in self.dataset:
  91. imgs = {im['id']: {} for im in self.dataset['images']}
  92. for img in self.dataset['images']:
  93. imgs[img['id']] = img
  94. if 'categories' in self.dataset:
  95. cats = {cat['id']: [] for cat in self.dataset['categories']}
  96. for cat in self.dataset['categories']:
  97. cats[cat['id']] = cat
  98. catToImgs = {cat['id']: [] for cat in self.dataset['categories']}
  99. if 'annotations' in self.dataset:
  100. for ann in self.dataset['annotations']:
  101. catToImgs[ann['category_id']] += [ann['image_id']]
  102. print 'index created!'
  103. # create class members
  104. self.anns = anns
  105. self.imgToAnns = imgToAnns
  106. self.catToImgs = catToImgs
  107. self.imgs = imgs
  108. self.cats = cats
  109. def info(self):
  110. """
  111. Print information about the annotation file.
  112. :return:
  113. """
  114. for key, value in self.dataset['info'].items():
  115. print '%s: %s'%(key, value)
  116. def getAnnIds(self, imgIds=[], catIds=[], areaRng=[], iscrowd=None):
  117. """
  118. Get ann ids that satisfy given filter conditions. default skips that filter
  119. :param imgIds (int array) : get anns for given imgs
  120. catIds (int array) : get anns for given cats
  121. areaRng (float array) : get anns for given area range (e.g. [0 inf])
  122. iscrowd (boolean) : get anns for given crowd label (False or True)
  123. :return: ids (int array) : integer array of ann ids
  124. """
  125. imgIds = imgIds if type(imgIds) == list else [imgIds]
  126. catIds = catIds if type(catIds) == list else [catIds]
  127. if len(imgIds) == len(catIds) == len(areaRng) == 0:
  128. anns = self.dataset['annotations']
  129. else:
  130. if not len(imgIds) == 0:
  131. # this can be changed by defaultdict
  132. lists = [self.imgToAnns[imgId] for imgId in imgIds if imgId in self.imgToAnns]
  133. anns = list(itertools.chain.from_iterable(lists))
  134. else:
  135. anns = self.dataset['annotations']
  136. anns = anns if len(catIds) == 0 else [ann for ann in anns if ann['category_id'] in catIds]
  137. anns = anns if len(areaRng) == 0 else [ann for ann in anns if ann['area'] > areaRng[0] and ann['area'] < areaRng[1]]
  138. if not iscrowd == None:
  139. ids = [ann['id'] for ann in anns if ann['iscrowd'] == iscrowd]
  140. else:
  141. ids = [ann['id'] for ann in anns]
  142. return ids
  143. def getCatIds(self, catNms=[], supNms=[], catIds=[]):
  144. """
  145. filtering parameters. default skips that filter.
  146. :param catNms (str array) : get cats for given cat names
  147. :param supNms (str array) : get cats for given supercategory names
  148. :param catIds (int array) : get cats for given cat ids
  149. :return: ids (int array) : integer array of cat ids
  150. """
  151. catNms = catNms if type(catNms) == list else [catNms]
  152. supNms = supNms if type(supNms) == list else [supNms]
  153. catIds = catIds if type(catIds) == list else [catIds]
  154. if len(catNms) == len(supNms) == len(catIds) == 0:
  155. cats = self.dataset['categories']
  156. else:
  157. cats = self.dataset['categories']
  158. cats = cats if len(catNms) == 0 else [cat for cat in cats if cat['name'] in catNms]
  159. cats = cats if len(supNms) == 0 else [cat for cat in cats if cat['supercategory'] in supNms]
  160. cats = cats if len(catIds) == 0 else [cat for cat in cats if cat['id'] in catIds]
  161. ids = [cat['id'] for cat in cats]
  162. return ids
  163. def getImgIds(self, imgIds=[], catIds=[]):
  164. '''
  165. Get img ids that satisfy given filter conditions.
  166. :param imgIds (int array) : get imgs for given ids
  167. :param catIds (int array) : get imgs with all given cats
  168. :return: ids (int array) : integer array of img ids
  169. '''
  170. imgIds = imgIds if type(imgIds) == list else [imgIds]
  171. catIds = catIds if type(catIds) == list else [catIds]
  172. if len(imgIds) == len(catIds) == 0:
  173. ids = self.imgs.keys()
  174. else:
  175. ids = set(imgIds)
  176. for i, catId in enumerate(catIds):
  177. if i == 0 and len(ids) == 0:
  178. ids = set(self.catToImgs[catId])
  179. else:
  180. ids &= set(self.catToImgs[catId])
  181. return list(ids)
  182. def loadAnns(self, ids=[]):
  183. """
  184. Load anns with the specified ids.
  185. :param ids (int array) : integer ids specifying anns
  186. :return: anns (object array) : loaded ann objects
  187. """
  188. if type(ids) == list:
  189. return [self.anns[id] for id in ids]
  190. elif type(ids) == int:
  191. return [self.anns[ids]]
  192. def loadCats(self, ids=[]):
  193. """
  194. Load cats with the specified ids.
  195. :param ids (int array) : integer ids specifying cats
  196. :return: cats (object array) : loaded cat objects
  197. """
  198. if type(ids) == list:
  199. return [self.cats[id] for id in ids]
  200. elif type(ids) == int:
  201. return [self.cats[ids]]
  202. def loadImgs(self, ids=[]):
  203. """
  204. Load anns with the specified ids.
  205. :param ids (int array) : integer ids specifying img
  206. :return: imgs (object array) : loaded img objects
  207. """
  208. if type(ids) == list:
  209. return [self.imgs[id] for id in ids]
  210. elif type(ids) == int:
  211. return [self.imgs[ids]]
  212. def showAnns(self, anns):
  213. """
  214. Display the specified annotations.
  215. :param anns (array of object): annotations to display
  216. :return: None
  217. """
  218. if len(anns) == 0:
  219. return 0
  220. if 'segmentation' in anns[0]:
  221. datasetType = 'instances'
  222. elif 'caption' in anns[0]:
  223. datasetType = 'captions'
  224. if datasetType == 'instances':
  225. ax = plt.gca()
  226. polygons = []
  227. color = []
  228. for ann in anns:
  229. c = np.random.random((1, 3)).tolist()[0]
  230. if type(ann['segmentation']) == list:
  231. # polygon
  232. for seg in ann['segmentation']:
  233. poly = np.array(seg).reshape((len(seg)/2, 2))
  234. polygons.append(Polygon(poly, True,alpha=0.4))
  235. color.append(c)
  236. else:
  237. # mask
  238. t = self.imgs[ann['image_id']]
  239. if type(ann['segmentation']['counts']) == list:
  240. rle = mask.frPyObjects([ann['segmentation']], t['height'], t['width'])
  241. else:
  242. rle = [ann['segmentation']]
  243. m = mask.decode(rle)
  244. img = np.ones( (m.shape[0], m.shape[1], 3) )
  245. if ann['iscrowd'] == 1:
  246. color_mask = np.array([2.0,166.0,101.0])/255
  247. if ann['iscrowd'] == 0:
  248. color_mask = np.random.random((1, 3)).tolist()[0]
  249. for i in range(3):
  250. img[:,:,i] = color_mask[i]
  251. ax.imshow(np.dstack( (img, m*0.5) ))
  252. p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4)
  253. ax.add_collection(p)
  254. elif datasetType == 'captions':
  255. for ann in anns:
  256. print ann['caption']
  257. def loadRes(self, resFile):
  258. """
  259. Load result file and return a result api object.
  260. :param resFile (str) : file name of result file
  261. :return: res (obj) : result api object
  262. """
  263. res = COCO()
  264. res.dataset['images'] = [img for img in self.dataset['images']]
  265. # res.dataset['info'] = copy.deepcopy(self.dataset['info'])
  266. # res.dataset['licenses'] = copy.deepcopy(self.dataset['licenses'])
  267. print 'Loading and preparing results... '
  268. tic = time.time()
  269. anns = json.load(open(resFile))
  270. assert type(anns) == list, 'results in not an array of objects'
  271. annsImgIds = [ann['image_id'] for ann in anns]
  272. assert set(annsImgIds) == (set(annsImgIds) & set(self.getImgIds())), \
  273. 'Results do not correspond to current coco set'
  274. if 'caption' in anns[0]:
  275. imgIds = set([img['id'] for img in res.dataset['images']]) & set([ann['image_id'] for ann in anns])
  276. res.dataset['images'] = [img for img in res.dataset['images'] if img['id'] in imgIds]
  277. for id, ann in enumerate(anns):
  278. ann['id'] = id+1
  279. elif 'bbox' in anns[0] and not anns[0]['bbox'] == []:
  280. res.dataset['categories'] = copy.deepcopy(self.dataset['categories'])
  281. for id, ann in enumerate(anns):
  282. bb = ann['bbox']
  283. x1, x2, y1, y2 = [bb[0], bb[0]+bb[2], bb[1], bb[1]+bb[3]]
  284. if not 'segmentation' in ann:
  285. ann['segmentation'] = [[x1, y1, x1, y2, x2, y2, x2, y1]]
  286. ann['area'] = bb[2]*bb[3]
  287. ann['id'] = id+1
  288. ann['iscrowd'] = 0
  289. elif 'segmentation' in anns[0]:
  290. res.dataset['categories'] = copy.deepcopy(self.dataset['categories'])
  291. for id, ann in enumerate(anns):
  292. # now only support compressed RLE format as segmentation results
  293. ann['area'] = mask.area([ann['segmentation']])[0]
  294. if not 'bbox' in ann:
  295. ann['bbox'] = mask.toBbox([ann['segmentation']])[0]
  296. ann['id'] = id+1
  297. ann['iscrowd'] = 0
  298. print 'DONE (t=%0.2fs)'%(time.time()- tic)
  299. res.dataset['annotations'] = anns
  300. res.createIndex()
  301. return res
  302. def download( self, tarDir = None, imgIds = [] ):
  303. '''
  304. Download COCO images from mscoco.org server.
  305. :param tarDir (str): COCO results directory name
  306. imgIds (list): images to be downloaded
  307. :return:
  308. '''
  309. if tarDir is None:
  310. print 'Please specify target directory'
  311. return -1
  312. if len(imgIds) == 0:
  313. imgs = self.imgs.values()
  314. else:
  315. imgs = self.loadImgs(imgIds)
  316. N = len(imgs)
  317. if not os.path.exists(tarDir):
  318. os.makedirs(tarDir)
  319. for i, img in enumerate(imgs):
  320. tic = time.time()
  321. fname = os.path.join(tarDir, img['file_name'])
  322. if not os.path.exists(fname):
  323. urllib.urlretrieve(img['coco_url'], fname)
  324. print 'downloaded %d/%d images (t=%.1fs)'%(i, N, time.time()- tic)