You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

lvis.py 7.8 kB

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
  2. import logging
  3. import os
  4. from fvcore.common.timer import Timer
  5. from detectron2.structures import BoxMode
  6. from fvcore.common.file_io import PathManager
  7. from detectron2.data import DatasetCatalog, MetadataCatalog
  8. from .lvis_v0_5_categories import LVIS_CATEGORIES
  9. """
  10. This file contains functions to parse LVIS-format annotations into dicts in the
  11. "Detectron2 format".
  12. """
  13. logger = logging.getLogger(__name__)
  14. __all__ = ["load_lvis_json", "register_lvis_instances", "get_lvis_instances_meta"]
  15. def register_lvis_instances(name, metadata, json_file, image_root):
  16. """
  17. Register a dataset in LVIS's json annotation format for instance detection and segmentation.
  18. Args:
  19. name (str): a name that identifies the dataset, e.g. "lvis_v0.5_train".
  20. metadata (dict): extra metadata associated with this dataset. It can be an empty dict.
  21. json_file (str): path to the json instance annotation file.
  22. image_root (str): directory which contains all the images.
  23. """
  24. DatasetCatalog.register(name, lambda: load_lvis_json(json_file, image_root, name))
  25. MetadataCatalog.get(name).set(
  26. json_file=json_file, image_root=image_root, evaluator_type="lvis", **metadata
  27. )
  28. def load_lvis_json(json_file, image_root, dataset_name=None):
  29. """
  30. Load a json file in LVIS's annotation format.
  31. Args:
  32. json_file (str): full path to the LVIS json annotation file.
  33. image_root (str): the directory where the images in this json file exists.
  34. dataset_name (str): the name of the dataset (e.g., "lvis_v0.5_train").
  35. If provided, this function will put "thing_classes" into the metadata
  36. associated with this dataset.
  37. Returns:
  38. list[dict]: a list of dicts in Detectron2 standard format. (See
  39. `Using Custom Datasets </tutorials/datasets.html>`_ )
  40. Notes:
  41. 1. This function does not read the image files.
  42. The results do not have the "image" field.
  43. """
  44. from lvis import LVIS
  45. json_file = PathManager.get_local_path(json_file)
  46. timer = Timer()
  47. lvis_api = LVIS(json_file)
  48. if timer.seconds() > 1:
  49. logger.info("Loading {} takes {:.2f} seconds.".format(json_file, timer.seconds()))
  50. if dataset_name is not None:
  51. meta = get_lvis_instances_meta(dataset_name)
  52. MetadataCatalog.get(dataset_name).set(**meta)
  53. # sort indices for reproducible results
  54. img_ids = sorted(list(lvis_api.imgs.keys()))
  55. # imgs is a list of dicts, each looks something like:
  56. # {'license': 4,
  57. # 'url': 'http://farm6.staticflickr.com/5454/9413846304_881d5e5c3b_z.jpg',
  58. # 'file_name': 'COCO_val2014_000000001268.jpg',
  59. # 'height': 427,
  60. # 'width': 640,
  61. # 'date_captured': '2013-11-17 05:57:24',
  62. # 'id': 1268}
  63. imgs = lvis_api.load_imgs(img_ids)
  64. # anns is a list[list[dict]], where each dict is an annotation
  65. # record for an object. The inner list enumerates the objects in an image
  66. # and the outer list enumerates over images. Example of anns[0]:
  67. # [{'segmentation': [[192.81,
  68. # 247.09,
  69. # ...
  70. # 219.03,
  71. # 249.06]],
  72. # 'area': 1035.749,
  73. # 'image_id': 1268,
  74. # 'bbox': [192.81, 224.8, 74.73, 33.43],
  75. # 'category_id': 16,
  76. # 'id': 42986},
  77. # ...]
  78. anns = [lvis_api.img_ann_map[img_id] for img_id in img_ids]
  79. # Sanity check that each annotation has a unique id
  80. ann_ids = [ann["id"] for anns_per_image in anns for ann in anns_per_image]
  81. assert len(set(ann_ids)) == len(ann_ids), "Annotation ids in '{}' are not unique".format(
  82. json_file
  83. )
  84. imgs_anns = list(zip(imgs, anns))
  85. logger.info("Loaded {} images in the LVIS format from {}".format(len(imgs_anns), json_file))
  86. dataset_dicts = []
  87. for (img_dict, anno_dict_list) in imgs_anns:
  88. record = {}
  89. file_name = img_dict["file_name"]
  90. if img_dict["file_name"].startswith("COCO"):
  91. # Convert form the COCO 2014 file naming convention of
  92. # COCO_[train/val/test]2014_000000000000.jpg to the 2017 naming convention of
  93. # 000000000000.jpg (LVIS v1 will fix this naming issue)
  94. file_name = file_name[-16:]
  95. record["file_name"] = os.path.join(image_root, file_name)
  96. record["height"] = img_dict["height"]
  97. record["width"] = img_dict["width"]
  98. record["not_exhaustive_category_ids"] = img_dict.get("not_exhaustive_category_ids", [])
  99. record["neg_category_ids"] = img_dict.get("neg_category_ids", [])
  100. image_id = record["image_id"] = img_dict["id"]
  101. objs = []
  102. for anno in anno_dict_list:
  103. # Check that the image_id in this annotation is the same as
  104. # the image_id we're looking at.
  105. # This fails only when the data parsing logic or the annotation file is buggy.
  106. assert anno["image_id"] == image_id
  107. obj = {"bbox": anno["bbox"], "bbox_mode": BoxMode.XYWH_ABS}
  108. obj["category_id"] = anno["category_id"] - 1 # Convert 1-indexed to 0-indexed
  109. segm = anno["segmentation"] # list[list[float]]
  110. # filter out invalid polygons (< 3 points)
  111. valid_segm = [poly for poly in segm if len(poly) % 2 == 0 and len(poly) >= 6]
  112. assert len(segm) == len(
  113. valid_segm
  114. ), "Annotation contains an invalid polygon with < 3 points"
  115. assert len(segm) > 0
  116. obj["segmentation"] = segm
  117. objs.append(obj)
  118. record["annotations"] = objs
  119. dataset_dicts.append(record)
  120. return dataset_dicts
  121. def get_lvis_instances_meta(dataset_name):
  122. """
  123. Load LVIS metadata.
  124. Args:
  125. dataset_name (str): LVIS dataset name without the split name (e.g., "lvis_v0.5").
  126. Returns:
  127. dict: LVIS metadata with keys: thing_classes
  128. """
  129. if "v0.5" in dataset_name:
  130. return _get_lvis_instances_meta_v0_5()
  131. # There will be a v1 in the future
  132. # elif dataset_name == "lvis_v1":
  133. # return get_lvis_instances_meta_v1()
  134. raise ValueError("No built-in metadata for dataset {}".format(dataset_name))
  135. def _get_lvis_instances_meta_v0_5():
  136. assert len(LVIS_CATEGORIES) == 1230
  137. cat_ids = [k["id"] for k in LVIS_CATEGORIES]
  138. assert min(cat_ids) == 1 and max(cat_ids) == len(
  139. cat_ids
  140. ), "Category ids are not in [1, #categories], as expected"
  141. # Ensure that the category list is sorted by id
  142. lvis_categories = [k for k in sorted(LVIS_CATEGORIES, key=lambda x: x["id"])]
  143. thing_classes = [k["synonyms"][0] for k in lvis_categories]
  144. meta = {"thing_classes": thing_classes}
  145. return meta
  146. if __name__ == "__main__":
  147. """
  148. Test the LVIS json dataset loader.
  149. Usage:
  150. python -m detectron2.data.datasets.lvis \
  151. path/to/json path/to/image_root dataset_name vis_limit
  152. """
  153. import sys
  154. import numpy as np
  155. from detectron2.utils.logger import setup_logger
  156. from PIL import Image
  157. import detectron2.data.datasets # noqa # add pre-defined metadata
  158. from detectron2.utils.visualizer import Visualizer
  159. logger = setup_logger(name=__name__)
  160. meta = MetadataCatalog.get(sys.argv[3])
  161. dicts = load_lvis_json(sys.argv[1], sys.argv[2], sys.argv[3])
  162. logger.info("Done loading {} samples.".format(len(dicts)))
  163. dirname = "lvis-data-vis"
  164. os.makedirs(dirname, exist_ok=True)
  165. for d in dicts[: int(sys.argv[4])]:
  166. img = np.array(Image.open(d["file_name"]))
  167. visualizer = Visualizer(img, metadata=meta)
  168. vis = visualizer.draw_dataset_dict(d)
  169. fpath = os.path.join(dirname, os.path.basename(d["file_name"]))
  170. vis.save(fpath)

No Description