clevr.py 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import json
  2. import pathlib
  3. from typing import Any, Callable, List, Optional, Tuple
  4. from urllib.parse import urlparse
  5. from PIL import Image
  6. from .utils import download_and_extract_archive, verify_str_arg
  7. from .vision import VisionDataset
  8. class CLEVRClassification(VisionDataset):
  9. """`CLEVR <https://cs.stanford.edu/people/jcjohns/clevr/>`_ classification dataset.
  10. The number of objects in a scene are used as label.
  11. Args:
  12. root (string): Root directory of dataset where directory ``root/clevr`` exists or will be saved to if download is
  13. set to True.
  14. split (string, optional): The dataset split, supports ``"train"`` (default), ``"val"``, or ``"test"``.
  15. transform (callable, optional): A function/transform that takes in an PIL image and returns a transformed
  16. version. E.g, ``transforms.RandomCrop``
  17. target_transform (callable, optional): A function/transform that takes in them target and transforms it.
  18. download (bool, optional): If true, downloads the dataset from the internet and puts it in root directory. If
  19. dataset is already downloaded, it is not downloaded again.
  20. """
  21. _URL = "https://dl.fbaipublicfiles.com/clevr/CLEVR_v1.0.zip"
  22. _MD5 = "b11922020e72d0cd9154779b2d3d07d2"
  23. def __init__(
  24. self,
  25. root: str,
  26. split: str = "train",
  27. transform: Optional[Callable] = None,
  28. target_transform: Optional[Callable] = None,
  29. download: bool = False,
  30. ) -> None:
  31. self._split = verify_str_arg(split, "split", ("train", "val", "test"))
  32. super().__init__(root, transform=transform, target_transform=target_transform)
  33. self._base_folder = pathlib.Path(self.root) / "clevr"
  34. self._data_folder = self._base_folder / pathlib.Path(urlparse(self._URL).path).stem
  35. if download:
  36. self._download()
  37. if not self._check_exists():
  38. raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it")
  39. self._image_files = sorted(self._data_folder.joinpath("images", self._split).glob("*"))
  40. self._labels: List[Optional[int]]
  41. if self._split != "test":
  42. with open(self._data_folder / "scenes" / f"CLEVR_{self._split}_scenes.json") as file:
  43. content = json.load(file)
  44. num_objects = {scene["image_filename"]: len(scene["objects"]) for scene in content["scenes"]}
  45. self._labels = [num_objects[image_file.name] for image_file in self._image_files]
  46. else:
  47. self._labels = [None] * len(self._image_files)
  48. def __len__(self) -> int:
  49. return len(self._image_files)
  50. def __getitem__(self, idx: int) -> Tuple[Any, Any]:
  51. image_file = self._image_files[idx]
  52. label = self._labels[idx]
  53. image = Image.open(image_file).convert("RGB")
  54. if self.transform:
  55. image = self.transform(image)
  56. if self.target_transform:
  57. label = self.target_transform(label)
  58. return image, label
  59. def _check_exists(self) -> bool:
  60. return self._data_folder.exists() and self._data_folder.is_dir()
  61. def _download(self) -> None:
  62. if self._check_exists():
  63. return
  64. download_and_extract_archive(self._URL, str(self._base_folder), md5=self._MD5)
  65. def extra_repr(self) -> str:
  66. return f"split={self._split}"