stanford_cars.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import pathlib
  2. from typing import Any, Callable, Optional, Union
  3. from .folder import default_loader
  4. from .utils import verify_str_arg
  5. from .vision import VisionDataset
  6. class StanfordCars(VisionDataset):
  7. """Stanford Cars Dataset
  8. The Cars dataset contains 16,185 images of 196 classes of cars. The data is
  9. split into 8,144 training images and 8,041 testing images, where each class
  10. has been split roughly in a 50-50 split
  11. The original URL is https://ai.stanford.edu/~jkrause/cars/car_dataset.html,
  12. the dataset isn't available online anymore.
  13. .. note::
  14. This class needs `scipy <https://docs.scipy.org/doc/>`_ to load target files from `.mat` format.
  15. Args:
  16. root (str or ``pathlib.Path``): Root directory of dataset
  17. split (string, optional): The dataset split, supports ``"train"`` (default) or ``"test"``.
  18. transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader,
  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. download (bool, optional): This parameter exists for backward compatibility but it does not
  23. download the dataset, since the original URL is not available anymore.
  24. loader (callable, optional): A function to load an image given its path.
  25. By default, it uses PIL as its image loader, but users could also pass in
  26. ``torchvision.io.decode_image`` for decoding image data into tensors directly.
  27. """
  28. def __init__(
  29. self,
  30. root: Union[str, pathlib.Path],
  31. split: str = "train",
  32. transform: Optional[Callable] = None,
  33. target_transform: Optional[Callable] = None,
  34. download: bool = False,
  35. loader: Callable[[str], Any] = default_loader,
  36. ) -> None:
  37. try:
  38. import scipy.io as sio
  39. except ImportError:
  40. raise RuntimeError("Scipy is not found. This dataset needs to have scipy installed: pip install scipy")
  41. super().__init__(root, transform=transform, target_transform=target_transform)
  42. self._split = verify_str_arg(split, "split", ("train", "test"))
  43. self._base_folder = pathlib.Path(root) / "stanford_cars"
  44. devkit = self._base_folder / "devkit"
  45. if self._split == "train":
  46. self._annotations_mat_path = devkit / "cars_train_annos.mat"
  47. self._images_base_path = self._base_folder / "cars_train"
  48. else:
  49. self._annotations_mat_path = self._base_folder / "cars_test_annos_withlabels.mat"
  50. self._images_base_path = self._base_folder / "cars_test"
  51. if download:
  52. self.download()
  53. if not self._check_exists():
  54. raise RuntimeError("Dataset not found.")
  55. self._samples = [
  56. (
  57. str(self._images_base_path / annotation["fname"]),
  58. annotation["class"] - 1, # Original target mapping starts from 1, hence -1
  59. )
  60. for annotation in sio.loadmat(self._annotations_mat_path, squeeze_me=True)["annotations"]
  61. ]
  62. self.classes = sio.loadmat(str(devkit / "cars_meta.mat"), squeeze_me=True)["class_names"].tolist()
  63. self.class_to_idx = {cls: i for i, cls in enumerate(self.classes)}
  64. self.loader = loader
  65. def __len__(self) -> int:
  66. return len(self._samples)
  67. def __getitem__(self, idx: int) -> tuple[Any, Any]:
  68. """Returns pil_image and class_id for given index"""
  69. image_path, target = self._samples[idx]
  70. image = self.loader(image_path)
  71. if self.transform is not None:
  72. image = self.transform(image)
  73. if self.target_transform is not None:
  74. target = self.target_transform(target)
  75. return image, target
  76. def _check_exists(self) -> bool:
  77. if not (self._base_folder / "devkit").is_dir():
  78. return False
  79. return self._annotations_mat_path.exists() and self._images_base_path.is_dir()
  80. def download(self):
  81. raise ValueError("The original URL is broken so the StanfordCars dataset cannot be downloaded anymore.")