phototour.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. import os
  2. from pathlib import Path
  3. from typing import Any, Callable, Optional, Union
  4. import numpy as np
  5. import torch
  6. from PIL import Image
  7. from .utils import download_url
  8. from .vision import VisionDataset
  9. class PhotoTour(VisionDataset):
  10. """`Multi-view Stereo Correspondence <http://matthewalunbrown.com/patchdata/patchdata.html>`_ Dataset.
  11. .. note::
  12. We only provide the newer version of the dataset, since the authors state that it
  13. is more suitable for training descriptors based on difference of Gaussian, or Harris corners, as the
  14. patches are centred on real interest point detections, rather than being projections of 3D points as is the
  15. case in the old dataset.
  16. The original dataset is available under http://phototour.cs.washington.edu/patches/default.htm.
  17. Args:
  18. root (str or ``pathlib.Path``): Root directory where images are.
  19. name (string): Name of the dataset to load.
  20. transform (callable, optional): A function/transform that takes in a PIL image
  21. and returns a transformed version.
  22. download (bool, optional): If true, downloads the dataset from the internet and
  23. puts it in root directory. If dataset is already downloaded, it is not
  24. downloaded again.
  25. """
  26. urls = {
  27. "notredame_harris": [
  28. "http://matthewalunbrown.com/patchdata/notredame_harris.zip",
  29. "notredame_harris.zip",
  30. "69f8c90f78e171349abdf0307afefe4d",
  31. ],
  32. "yosemite_harris": [
  33. "http://matthewalunbrown.com/patchdata/yosemite_harris.zip",
  34. "yosemite_harris.zip",
  35. "a73253d1c6fbd3ba2613c45065c00d46",
  36. ],
  37. "liberty_harris": [
  38. "http://matthewalunbrown.com/patchdata/liberty_harris.zip",
  39. "liberty_harris.zip",
  40. "c731fcfb3abb4091110d0ae8c7ba182c",
  41. ],
  42. "notredame": [
  43. "http://icvl.ee.ic.ac.uk/vbalnt/notredame.zip",
  44. "notredame.zip",
  45. "509eda8535847b8c0a90bbb210c83484",
  46. ],
  47. "yosemite": ["http://icvl.ee.ic.ac.uk/vbalnt/yosemite.zip", "yosemite.zip", "533b2e8eb7ede31be40abc317b2fd4f0"],
  48. "liberty": ["http://icvl.ee.ic.ac.uk/vbalnt/liberty.zip", "liberty.zip", "fdd9152f138ea5ef2091746689176414"],
  49. }
  50. means = {
  51. "notredame": 0.4854,
  52. "yosemite": 0.4844,
  53. "liberty": 0.4437,
  54. "notredame_harris": 0.4854,
  55. "yosemite_harris": 0.4844,
  56. "liberty_harris": 0.4437,
  57. }
  58. stds = {
  59. "notredame": 0.1864,
  60. "yosemite": 0.1818,
  61. "liberty": 0.2019,
  62. "notredame_harris": 0.1864,
  63. "yosemite_harris": 0.1818,
  64. "liberty_harris": 0.2019,
  65. }
  66. lens = {
  67. "notredame": 468159,
  68. "yosemite": 633587,
  69. "liberty": 450092,
  70. "liberty_harris": 379587,
  71. "yosemite_harris": 450912,
  72. "notredame_harris": 325295,
  73. }
  74. image_ext = "bmp"
  75. info_file = "info.txt"
  76. matches_files = "m50_100000_100000_0.txt"
  77. def __init__(
  78. self,
  79. root: Union[str, Path],
  80. name: str,
  81. train: bool = True,
  82. transform: Optional[Callable] = None,
  83. download: bool = False,
  84. ) -> None:
  85. super().__init__(root, transform=transform)
  86. self.name = name
  87. self.data_dir = os.path.join(self.root, name)
  88. self.data_down = os.path.join(self.root, f"{name}.zip")
  89. self.data_file = os.path.join(self.root, f"{name}.pt")
  90. self.train = train
  91. self.mean = self.means[name]
  92. self.std = self.stds[name]
  93. if download:
  94. self.download()
  95. if not self._check_datafile_exists():
  96. self.cache()
  97. # load the serialized data
  98. self.data, self.labels, self.matches = torch.load(self.data_file, weights_only=True)
  99. def __getitem__(self, index: int) -> Union[torch.Tensor, tuple[Any, Any, torch.Tensor]]:
  100. """
  101. Args:
  102. index (int): Index
  103. Returns:
  104. tuple: (data1, data2, matches)
  105. """
  106. if self.train:
  107. data = self.data[index]
  108. if self.transform is not None:
  109. data = self.transform(data)
  110. return data
  111. m = self.matches[index]
  112. data1, data2 = self.data[m[0]], self.data[m[1]]
  113. if self.transform is not None:
  114. data1 = self.transform(data1)
  115. data2 = self.transform(data2)
  116. return data1, data2, m[2]
  117. def __len__(self) -> int:
  118. return len(self.data if self.train else self.matches)
  119. def _check_datafile_exists(self) -> bool:
  120. return os.path.exists(self.data_file)
  121. def _check_downloaded(self) -> bool:
  122. return os.path.exists(self.data_dir)
  123. def download(self) -> None:
  124. if self._check_datafile_exists():
  125. return
  126. if not self._check_downloaded():
  127. # download files
  128. url = self.urls[self.name][0]
  129. filename = self.urls[self.name][1]
  130. md5 = self.urls[self.name][2]
  131. fpath = os.path.join(self.root, filename)
  132. download_url(url, self.root, filename, md5)
  133. import zipfile
  134. with zipfile.ZipFile(fpath, "r") as z:
  135. z.extractall(self.data_dir)
  136. os.unlink(fpath)
  137. def cache(self) -> None:
  138. # process and save as torch files
  139. dataset = (
  140. read_image_file(self.data_dir, self.image_ext, self.lens[self.name]),
  141. read_info_file(self.data_dir, self.info_file),
  142. read_matches_files(self.data_dir, self.matches_files),
  143. )
  144. with open(self.data_file, "wb") as f:
  145. torch.save(dataset, f)
  146. def extra_repr(self) -> str:
  147. split = "Train" if self.train is True else "Test"
  148. return f"Split: {split}"
  149. def read_image_file(data_dir: str, image_ext: str, n: int) -> torch.Tensor:
  150. """Return a Tensor containing the patches"""
  151. def PIL2array(_img: Image.Image) -> np.ndarray:
  152. """Convert PIL image type to numpy 2D array"""
  153. return np.array(_img.getdata(), dtype=np.uint8).reshape(64, 64)
  154. def find_files(_data_dir: str, _image_ext: str) -> list[str]:
  155. """Return a list with the file names of the images containing the patches"""
  156. files = []
  157. # find those files with the specified extension
  158. for file_dir in os.listdir(_data_dir):
  159. if file_dir.endswith(_image_ext):
  160. files.append(os.path.join(_data_dir, file_dir))
  161. return sorted(files) # sort files in ascend order to keep relations
  162. patches = []
  163. list_files = find_files(data_dir, image_ext)
  164. for fpath in list_files:
  165. img = Image.open(fpath)
  166. for y in range(0, img.height, 64):
  167. for x in range(0, img.width, 64):
  168. patch = img.crop((x, y, x + 64, y + 64))
  169. patches.append(PIL2array(patch))
  170. return torch.ByteTensor(np.array(patches[:n]))
  171. def read_info_file(data_dir: str, info_file: str) -> torch.Tensor:
  172. """Return a Tensor containing the list of labels
  173. Read the file and keep only the ID of the 3D point.
  174. """
  175. with open(os.path.join(data_dir, info_file)) as f:
  176. labels = [int(line.split()[0]) for line in f]
  177. return torch.LongTensor(labels)
  178. def read_matches_files(data_dir: str, matches_file: str) -> torch.Tensor:
  179. """Return a Tensor containing the ground truth matches
  180. Read the file and keep only 3D point ID.
  181. Matches are represented with a 1, non matches with a 0.
  182. """
  183. matches = []
  184. with open(os.path.join(data_dir, matches_file)) as f:
  185. for line in f:
  186. line_split = line.split()
  187. matches.append([int(line_split[0]), int(line_split[3]), int(line_split[1] == line_split[4])])
  188. return torch.LongTensor(matches)