cityscapes.py 10 KB

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