pcam.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import pathlib
  2. from typing import Any, Callable, Optional, Tuple
  3. from PIL import Image
  4. from .utils import _decompress, download_file_from_google_drive, verify_str_arg
  5. from .vision import VisionDataset
  6. class PCAM(VisionDataset):
  7. """`PCAM Dataset <https://github.com/basveeling/pcam>`_.
  8. The PatchCamelyon dataset is a binary classification dataset with 327,680
  9. color images (96px x 96px), extracted from histopathologic scans of lymph node
  10. sections. Each image is annotated with a binary label indicating presence of
  11. metastatic tissue.
  12. This dataset requires the ``h5py`` package which you can install with ``pip install h5py``.
  13. Args:
  14. root (string): Root directory of the dataset.
  15. split (string, optional): The dataset split, supports ``"train"`` (default), ``"test"`` or ``"val"``.
  16. transform (callable, optional): A function/transform that takes in a PIL image and returns a transformed
  17. version. E.g, ``transforms.RandomCrop``.
  18. target_transform (callable, optional): A function/transform that takes in the target and transforms it.
  19. download (bool, optional): If True, downloads the dataset from the internet and puts it into ``root/pcam``. If
  20. dataset is already downloaded, it is not downloaded again.
  21. """
  22. _FILES = {
  23. "train": {
  24. "images": (
  25. "camelyonpatch_level_2_split_train_x.h5", # Data file name
  26. "1Ka0XfEMiwgCYPdTI-vv6eUElOBnKFKQ2", # Google Drive ID
  27. "1571f514728f59376b705fc836ff4b63", # md5 hash
  28. ),
  29. "targets": (
  30. "camelyonpatch_level_2_split_train_y.h5",
  31. "1269yhu3pZDP8UYFQs-NYs3FPwuK-nGSG",
  32. "35c2d7259d906cfc8143347bb8e05be7",
  33. ),
  34. },
  35. "test": {
  36. "images": (
  37. "camelyonpatch_level_2_split_test_x.h5",
  38. "1qV65ZqZvWzuIVthK8eVDhIwrbnsJdbg_",
  39. "d8c2d60d490dbd479f8199bdfa0cf6ec",
  40. ),
  41. "targets": (
  42. "camelyonpatch_level_2_split_test_y.h5",
  43. "17BHrSrwWKjYsOgTMmoqrIjDy6Fa2o_gP",
  44. "60a7035772fbdb7f34eb86d4420cf66a",
  45. ),
  46. },
  47. "val": {
  48. "images": (
  49. "camelyonpatch_level_2_split_valid_x.h5",
  50. "1hgshYGWK8V-eGRy8LToWJJgDU_rXWVJ3",
  51. "d5b63470df7cfa627aeec8b9dc0c066e",
  52. ),
  53. "targets": (
  54. "camelyonpatch_level_2_split_valid_y.h5",
  55. "1bH8ZRbhSVAhScTS0p9-ZzGnX91cHT3uO",
  56. "2b85f58b927af9964a4c15b8f7e8f179",
  57. ),
  58. },
  59. }
  60. def __init__(
  61. self,
  62. root: str,
  63. split: str = "train",
  64. transform: Optional[Callable] = None,
  65. target_transform: Optional[Callable] = None,
  66. download: bool = False,
  67. ):
  68. try:
  69. import h5py
  70. self.h5py = h5py
  71. except ImportError:
  72. raise RuntimeError(
  73. "h5py is not found. This dataset needs to have h5py installed: please run pip install h5py"
  74. )
  75. self._split = verify_str_arg(split, "split", ("train", "test", "val"))
  76. super().__init__(root, transform=transform, target_transform=target_transform)
  77. self._base_folder = pathlib.Path(self.root) / "pcam"
  78. if download:
  79. self._download()
  80. if not self._check_exists():
  81. raise RuntimeError("Dataset not found. You can use download=True to download it")
  82. def __len__(self) -> int:
  83. images_file = self._FILES[self._split]["images"][0]
  84. with self.h5py.File(self._base_folder / images_file) as images_data:
  85. return images_data["x"].shape[0]
  86. def __getitem__(self, idx: int) -> Tuple[Any, Any]:
  87. images_file = self._FILES[self._split]["images"][0]
  88. with self.h5py.File(self._base_folder / images_file) as images_data:
  89. image = Image.fromarray(images_data["x"][idx]).convert("RGB")
  90. targets_file = self._FILES[self._split]["targets"][0]
  91. with self.h5py.File(self._base_folder / targets_file) as targets_data:
  92. target = int(targets_data["y"][idx, 0, 0, 0]) # shape is [num_images, 1, 1, 1]
  93. if self.transform:
  94. image = self.transform(image)
  95. if self.target_transform:
  96. target = self.target_transform(target)
  97. return image, target
  98. def _check_exists(self) -> bool:
  99. images_file = self._FILES[self._split]["images"][0]
  100. targets_file = self._FILES[self._split]["targets"][0]
  101. return all(self._base_folder.joinpath(h5_file).exists() for h5_file in (images_file, targets_file))
  102. def _download(self) -> None:
  103. if self._check_exists():
  104. return
  105. for file_name, file_id, md5 in self._FILES[self._split].values():
  106. archive_name = file_name + ".gz"
  107. download_file_from_google_drive(file_id, str(self._base_folder), filename=archive_name, md5=md5)
  108. _decompress(str(self._base_folder / archive_name))