cityscapes.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. import json
  2. import os
  3. from collections import namedtuple
  4. from typing import Any, Callable, Dict, List, Optional, Tuple, Union
  5. from PIL import Image
  6. from .utils import extract_archive, iterable_to_str, verify_str_arg
  7. from .vision import VisionDataset
  8. class Cityscapes(VisionDataset):
  9. """`Cityscapes <http://www.cityscapes-dataset.com/>`_ Dataset.
  10. Args:
  11. root (string): Root directory of dataset where directory ``leftImg8bit``
  12. and ``gtFine`` or ``gtCoarse`` are located.
  13. split (string, optional): The image split to use, ``train``, ``test`` or ``val`` if mode="fine"
  14. otherwise ``train``, ``train_extra`` or ``val``
  15. mode (string, optional): The quality mode to use, ``fine`` or ``coarse``
  16. target_type (string or list, optional): Type of target to use, ``instance``, ``semantic``, ``polygon``
  17. or ``color``. Can also be a list to output a tuple with all specified target types.
  18. transform (callable, optional): A function/transform that takes in a PIL image
  19. and returns a transformed version. E.g, ``transforms.RandomCrop``
  20. target_transform (callable, optional): A function/transform that takes in the
  21. target and transforms it.
  22. transforms (callable, optional): A function/transform that takes input sample and its target as entry
  23. and returns a transformed version.
  24. Examples:
  25. Get semantic segmentation target
  26. .. code-block:: python
  27. dataset = Cityscapes('./data/cityscapes', split='train', mode='fine',
  28. target_type='semantic')
  29. img, smnt = dataset[0]
  30. Get multiple targets
  31. .. code-block:: python
  32. dataset = Cityscapes('./data/cityscapes', split='train', mode='fine',
  33. target_type=['instance', 'color', 'polygon'])
  34. img, (inst, col, poly) = dataset[0]
  35. Validate on the "coarse" set
  36. .. code-block:: python
  37. dataset = Cityscapes('./data/cityscapes', split='val', mode='coarse',
  38. target_type='semantic')
  39. img, smnt = dataset[0]
  40. """
  41. # Based on https://github.com/mcordts/cityscapesScripts
  42. CityscapesClass = namedtuple(
  43. "CityscapesClass",
  44. ["name", "id", "train_id", "category", "category_id", "has_instances", "ignore_in_eval", "color"],
  45. )
  46. classes = [
  47. CityscapesClass("unlabeled", 0, 255, "void", 0, False, True, (0, 0, 0)),
  48. CityscapesClass("ego vehicle", 1, 255, "void", 0, False, True, (0, 0, 0)),
  49. CityscapesClass("rectification border", 2, 255, "void", 0, False, True, (0, 0, 0)),
  50. CityscapesClass("out of roi", 3, 255, "void", 0, False, True, (0, 0, 0)),
  51. CityscapesClass("static", 4, 255, "void", 0, False, True, (0, 0, 0)),
  52. CityscapesClass("dynamic", 5, 255, "void", 0, False, True, (111, 74, 0)),
  53. CityscapesClass("ground", 6, 255, "void", 0, False, True, (81, 0, 81)),
  54. CityscapesClass("road", 7, 0, "flat", 1, False, False, (128, 64, 128)),
  55. CityscapesClass("sidewalk", 8, 1, "flat", 1, False, False, (244, 35, 232)),
  56. CityscapesClass("parking", 9, 255, "flat", 1, False, True, (250, 170, 160)),
  57. CityscapesClass("rail track", 10, 255, "flat", 1, False, True, (230, 150, 140)),
  58. CityscapesClass("building", 11, 2, "construction", 2, False, False, (70, 70, 70)),
  59. CityscapesClass("wall", 12, 3, "construction", 2, False, False, (102, 102, 156)),
  60. CityscapesClass("fence", 13, 4, "construction", 2, False, False, (190, 153, 153)),
  61. CityscapesClass("guard rail", 14, 255, "construction", 2, False, True, (180, 165, 180)),
  62. CityscapesClass("bridge", 15, 255, "construction", 2, False, True, (150, 100, 100)),
  63. CityscapesClass("tunnel", 16, 255, "construction", 2, False, True, (150, 120, 90)),
  64. CityscapesClass("pole", 17, 5, "object", 3, False, False, (153, 153, 153)),
  65. CityscapesClass("polegroup", 18, 255, "object", 3, False, True, (153, 153, 153)),
  66. CityscapesClass("traffic light", 19, 6, "object", 3, False, False, (250, 170, 30)),
  67. CityscapesClass("traffic sign", 20, 7, "object", 3, False, False, (220, 220, 0)),
  68. CityscapesClass("vegetation", 21, 8, "nature", 4, False, False, (107, 142, 35)),
  69. CityscapesClass("terrain", 22, 9, "nature", 4, False, False, (152, 251, 152)),
  70. CityscapesClass("sky", 23, 10, "sky", 5, False, False, (70, 130, 180)),
  71. CityscapesClass("person", 24, 11, "human", 6, True, False, (220, 20, 60)),
  72. CityscapesClass("rider", 25, 12, "human", 6, True, False, (255, 0, 0)),
  73. CityscapesClass("car", 26, 13, "vehicle", 7, True, False, (0, 0, 142)),
  74. CityscapesClass("truck", 27, 14, "vehicle", 7, True, False, (0, 0, 70)),
  75. CityscapesClass("bus", 28, 15, "vehicle", 7, True, False, (0, 60, 100)),
  76. CityscapesClass("caravan", 29, 255, "vehicle", 7, True, True, (0, 0, 90)),
  77. CityscapesClass("trailer", 30, 255, "vehicle", 7, True, True, (0, 0, 110)),
  78. CityscapesClass("train", 31, 16, "vehicle", 7, True, False, (0, 80, 100)),
  79. CityscapesClass("motorcycle", 32, 17, "vehicle", 7, True, False, (0, 0, 230)),
  80. CityscapesClass("bicycle", 33, 18, "vehicle", 7, True, False, (119, 11, 32)),
  81. CityscapesClass("license plate", -1, -1, "vehicle", 7, False, True, (0, 0, 142)),
  82. ]
  83. def __init__(
  84. self,
  85. root: str,
  86. split: str = "train",
  87. mode: str = "fine",
  88. target_type: Union[List[str], str] = "instance",
  89. transform: Optional[Callable] = None,
  90. target_transform: Optional[Callable] = None,
  91. transforms: Optional[Callable] = None,
  92. ) -> None:
  93. super().__init__(root, transforms, transform, target_transform)
  94. self.mode = "gtFine" if mode == "fine" else "gtCoarse"
  95. self.images_dir = os.path.join(self.root, "leftImg8bit", split)
  96. self.targets_dir = os.path.join(self.root, self.mode, split)
  97. self.target_type = target_type
  98. self.split = split
  99. self.images = []
  100. self.targets = []
  101. verify_str_arg(mode, "mode", ("fine", "coarse"))
  102. if mode == "fine":
  103. valid_modes = ("train", "test", "val")
  104. else:
  105. valid_modes = ("train", "train_extra", "val")
  106. msg = "Unknown value '{}' for argument split if mode is '{}'. Valid values are {{{}}}."
  107. msg = msg.format(split, mode, iterable_to_str(valid_modes))
  108. verify_str_arg(split, "split", valid_modes, msg)
  109. if not isinstance(target_type, list):
  110. self.target_type = [target_type]
  111. [
  112. verify_str_arg(value, "target_type", ("instance", "semantic", "polygon", "color"))
  113. for value in self.target_type
  114. ]
  115. if not os.path.isdir(self.images_dir) or not os.path.isdir(self.targets_dir):
  116. if split == "train_extra":
  117. image_dir_zip = os.path.join(self.root, "leftImg8bit_trainextra.zip")
  118. else:
  119. image_dir_zip = os.path.join(self.root, "leftImg8bit_trainvaltest.zip")
  120. if self.mode == "gtFine":
  121. target_dir_zip = os.path.join(self.root, f"{self.mode}_trainvaltest.zip")
  122. elif self.mode == "gtCoarse":
  123. target_dir_zip = os.path.join(self.root, f"{self.mode}.zip")
  124. if os.path.isfile(image_dir_zip) and os.path.isfile(target_dir_zip):
  125. extract_archive(from_path=image_dir_zip, to_path=self.root)
  126. extract_archive(from_path=target_dir_zip, to_path=self.root)
  127. else:
  128. raise RuntimeError(
  129. "Dataset not found or incomplete. Please make sure all required folders for the"
  130. ' specified "split" and "mode" are inside the "root" directory'
  131. )
  132. for city in os.listdir(self.images_dir):
  133. img_dir = os.path.join(self.images_dir, city)
  134. target_dir = os.path.join(self.targets_dir, city)
  135. for file_name in os.listdir(img_dir):
  136. target_types = []
  137. for t in self.target_type:
  138. target_name = "{}_{}".format(
  139. file_name.split("_leftImg8bit")[0], self._get_target_suffix(self.mode, t)
  140. )
  141. target_types.append(os.path.join(target_dir, target_name))
  142. self.images.append(os.path.join(img_dir, file_name))
  143. self.targets.append(target_types)
  144. def __getitem__(self, index: int) -> Tuple[Any, Any]:
  145. """
  146. Args:
  147. index (int): Index
  148. Returns:
  149. tuple: (image, target) where target is a tuple of all target types if target_type is a list with more
  150. than one item. Otherwise, target is a json object if target_type="polygon", else the image segmentation.
  151. """
  152. image = Image.open(self.images[index]).convert("RGB")
  153. targets: Any = []
  154. for i, t in enumerate(self.target_type):
  155. if t == "polygon":
  156. target = self._load_json(self.targets[index][i])
  157. else:
  158. target = Image.open(self.targets[index][i])
  159. targets.append(target)
  160. target = tuple(targets) if len(targets) > 1 else targets[0]
  161. if self.transforms is not None:
  162. image, target = self.transforms(image, target)
  163. return image, target
  164. def __len__(self) -> int:
  165. return len(self.images)
  166. def extra_repr(self) -> str:
  167. lines = ["Split: {split}", "Mode: {mode}", "Type: {target_type}"]
  168. return "\n".join(lines).format(**self.__dict__)
  169. def _load_json(self, path: str) -> Dict[str, Any]:
  170. with open(path) as file:
  171. data = json.load(file)
  172. return data
  173. def _get_target_suffix(self, mode: str, target_type: str) -> str:
  174. if target_type == "instance":
  175. return f"{mode}_instanceIds.png"
  176. elif target_type == "semantic":
  177. return f"{mode}_labelIds.png"
  178. elif target_type == "color":
  179. return f"{mode}_color.png"
  180. else:
  181. return f"{mode}_polygons.json"