_stereo_matching.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  1. import functools
  2. import json
  3. import os
  4. import random
  5. import shutil
  6. from abc import ABC, abstractmethod
  7. from glob import glob
  8. from pathlib import Path
  9. from typing import Callable, cast, Optional, Union
  10. import numpy as np
  11. from PIL import Image
  12. from .utils import _read_pfm, download_and_extract_archive, verify_str_arg
  13. from .vision import VisionDataset
  14. T1 = tuple[Image.Image, Image.Image, Optional[np.ndarray], np.ndarray]
  15. T2 = tuple[Image.Image, Image.Image, Optional[np.ndarray]]
  16. __all__ = ()
  17. _read_pfm_file = functools.partial(_read_pfm, slice_channels=1)
  18. class StereoMatchingDataset(ABC, VisionDataset):
  19. """Base interface for Stereo matching datasets"""
  20. _has_built_in_disparity_mask = False
  21. def __init__(self, root: Union[str, Path], transforms: Optional[Callable] = None) -> None:
  22. """
  23. Args:
  24. root(str): Root directory of the dataset.
  25. transforms(callable, optional): A function/transform that takes in Tuples of
  26. (images, disparities, valid_masks) and returns a transformed version of each of them.
  27. images is a Tuple of (``PIL.Image``, ``PIL.Image``)
  28. disparities is a Tuple of (``np.ndarray``, ``np.ndarray``) with shape (1, H, W)
  29. valid_masks is a Tuple of (``np.ndarray``, ``np.ndarray``) with shape (H, W)
  30. In some cases, when a dataset does not provide disparities, the ``disparities`` and
  31. ``valid_masks`` can be Tuples containing None values.
  32. For training splits generally the datasets provide a minimal guarantee of
  33. images: (``PIL.Image``, ``PIL.Image``)
  34. disparities: (``np.ndarray``, ``None``) with shape (1, H, W)
  35. Optionally, based on the dataset, it can return a ``mask`` as well:
  36. valid_masks: (``np.ndarray | None``, ``None``) with shape (H, W)
  37. For some test splits, the datasets provides outputs that look like:
  38. imgaes: (``PIL.Image``, ``PIL.Image``)
  39. disparities: (``None``, ``None``)
  40. Optionally, based on the dataset, it can return a ``mask`` as well:
  41. valid_masks: (``None``, ``None``)
  42. """
  43. super().__init__(root=root)
  44. self.transforms = transforms
  45. self._images = [] # type: ignore
  46. self._disparities = [] # type: ignore
  47. def _read_img(self, file_path: Union[str, Path]) -> Image.Image:
  48. img = Image.open(file_path)
  49. if img.mode != "RGB":
  50. img = img.convert("RGB") # type: ignore [assignment]
  51. return img
  52. def _scan_pairs(
  53. self,
  54. paths_left_pattern: str,
  55. paths_right_pattern: Optional[str] = None,
  56. ) -> list[tuple[str, Optional[str]]]:
  57. left_paths = list(sorted(glob(paths_left_pattern)))
  58. right_paths: list[Union[None, str]]
  59. if paths_right_pattern:
  60. right_paths = list(sorted(glob(paths_right_pattern)))
  61. else:
  62. right_paths = list(None for _ in left_paths)
  63. if not left_paths:
  64. raise FileNotFoundError(f"Could not find any files matching the patterns: {paths_left_pattern}")
  65. if not right_paths:
  66. raise FileNotFoundError(f"Could not find any files matching the patterns: {paths_right_pattern}")
  67. if len(left_paths) != len(right_paths):
  68. raise ValueError(
  69. f"Found {len(left_paths)} left files but {len(right_paths)} right files using:\n "
  70. f"left pattern: {paths_left_pattern}\n"
  71. f"right pattern: {paths_right_pattern}\n"
  72. )
  73. paths = list((left, right) for left, right in zip(left_paths, right_paths))
  74. return paths
  75. @abstractmethod
  76. def _read_disparity(self, file_path: str) -> tuple[Optional[np.ndarray], Optional[np.ndarray]]:
  77. # function that returns a disparity map and an occlusion map
  78. pass
  79. def __getitem__(self, index: int) -> Union[T1, T2]:
  80. """Return example at given index.
  81. Args:
  82. index(int): The index of the example to retrieve
  83. Returns:
  84. tuple: A 3 or 4-tuple with ``(img_left, img_right, disparity, Optional[valid_mask])`` where ``valid_mask``
  85. can be a numpy boolean mask of shape (H, W) if the dataset provides a file
  86. indicating which disparity pixels are valid. The disparity is a numpy array of
  87. shape (1, H, W) and the images are PIL images. ``disparity`` is None for
  88. datasets on which for ``split="test"`` the authors did not provide annotations.
  89. """
  90. img_left = self._read_img(self._images[index][0])
  91. img_right = self._read_img(self._images[index][1])
  92. dsp_map_left, valid_mask_left = self._read_disparity(self._disparities[index][0])
  93. dsp_map_right, valid_mask_right = self._read_disparity(self._disparities[index][1])
  94. imgs = (img_left, img_right)
  95. dsp_maps = (dsp_map_left, dsp_map_right)
  96. valid_masks = (valid_mask_left, valid_mask_right)
  97. if self.transforms is not None:
  98. (
  99. imgs,
  100. dsp_maps,
  101. valid_masks,
  102. ) = self.transforms(imgs, dsp_maps, valid_masks)
  103. if self._has_built_in_disparity_mask or valid_masks[0] is not None:
  104. return imgs[0], imgs[1], dsp_maps[0], cast(np.ndarray, valid_masks[0])
  105. else:
  106. return imgs[0], imgs[1], dsp_maps[0]
  107. def __len__(self) -> int:
  108. return len(self._images)
  109. class CarlaStereo(StereoMatchingDataset):
  110. """
  111. Carla simulator data linked in the `CREStereo github repo <https://github.com/megvii-research/CREStereo>`_.
  112. The dataset is expected to have the following structure: ::
  113. root
  114. carla-highres
  115. trainingF
  116. scene1
  117. img0.png
  118. img1.png
  119. disp0GT.pfm
  120. disp1GT.pfm
  121. calib.txt
  122. scene2
  123. img0.png
  124. img1.png
  125. disp0GT.pfm
  126. disp1GT.pfm
  127. calib.txt
  128. ...
  129. Args:
  130. root (str or ``pathlib.Path``): Root directory where `carla-highres` is located.
  131. transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version.
  132. """
  133. def __init__(self, root: Union[str, Path], transforms: Optional[Callable] = None) -> None:
  134. super().__init__(root, transforms)
  135. root = Path(root) / "carla-highres"
  136. left_image_pattern = str(root / "trainingF" / "*" / "im0.png")
  137. right_image_pattern = str(root / "trainingF" / "*" / "im1.png")
  138. imgs = self._scan_pairs(left_image_pattern, right_image_pattern)
  139. self._images = imgs
  140. left_disparity_pattern = str(root / "trainingF" / "*" / "disp0GT.pfm")
  141. right_disparity_pattern = str(root / "trainingF" / "*" / "disp1GT.pfm")
  142. disparities = self._scan_pairs(left_disparity_pattern, right_disparity_pattern)
  143. self._disparities = disparities
  144. def _read_disparity(self, file_path: str) -> tuple[np.ndarray, None]:
  145. disparity_map = _read_pfm_file(file_path)
  146. disparity_map = np.abs(disparity_map) # ensure that the disparity is positive
  147. valid_mask = None
  148. return disparity_map, valid_mask
  149. def __getitem__(self, index: int) -> T1:
  150. """Return example at given index.
  151. Args:
  152. index(int): The index of the example to retrieve
  153. Returns:
  154. tuple: A 3-tuple with ``(img_left, img_right, disparity)``.
  155. The disparity is a numpy array of shape (1, H, W) and the images are PIL images.
  156. If a ``valid_mask`` is generated within the ``transforms`` parameter,
  157. a 4-tuple with ``(img_left, img_right, disparity, valid_mask)`` is returned.
  158. """
  159. return cast(T1, super().__getitem__(index))
  160. class Kitti2012Stereo(StereoMatchingDataset):
  161. """
  162. KITTI dataset from the `2012 stereo evaluation benchmark <http://www.cvlibs.net/datasets/kitti/eval_stereo_flow.php>`_.
  163. Uses the RGB images for consistency with KITTI 2015.
  164. The dataset is expected to have the following structure: ::
  165. root
  166. Kitti2012
  167. testing
  168. colored_0
  169. 1_10.png
  170. 2_10.png
  171. ...
  172. colored_1
  173. 1_10.png
  174. 2_10.png
  175. ...
  176. training
  177. colored_0
  178. 1_10.png
  179. 2_10.png
  180. ...
  181. colored_1
  182. 1_10.png
  183. 2_10.png
  184. ...
  185. disp_noc
  186. 1.png
  187. 2.png
  188. ...
  189. calib
  190. Args:
  191. root (str or ``pathlib.Path``): Root directory where `Kitti2012` is located.
  192. split (string, optional): The dataset split of scenes, either "train" (default) or "test".
  193. transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version.
  194. """
  195. _has_built_in_disparity_mask = True
  196. def __init__(self, root: Union[str, Path], split: str = "train", transforms: Optional[Callable] = None) -> None:
  197. super().__init__(root, transforms)
  198. verify_str_arg(split, "split", valid_values=("train", "test"))
  199. root = Path(root) / "Kitti2012" / (split + "ing")
  200. left_img_pattern = str(root / "colored_0" / "*_10.png")
  201. right_img_pattern = str(root / "colored_1" / "*_10.png")
  202. self._images = self._scan_pairs(left_img_pattern, right_img_pattern)
  203. if split == "train":
  204. disparity_pattern = str(root / "disp_noc" / "*.png")
  205. self._disparities = self._scan_pairs(disparity_pattern, None)
  206. else:
  207. self._disparities = list((None, None) for _ in self._images)
  208. def _read_disparity(self, file_path: str) -> tuple[Optional[np.ndarray], None]:
  209. # test split has no disparity maps
  210. if file_path is None:
  211. return None, None
  212. disparity_map = np.asarray(Image.open(file_path)) / 256.0
  213. # unsqueeze the disparity map into (C, H, W) format
  214. disparity_map = disparity_map[None, :, :]
  215. valid_mask = None
  216. return disparity_map, valid_mask
  217. def __getitem__(self, index: int) -> T1:
  218. """Return example at given index.
  219. Args:
  220. index(int): The index of the example to retrieve
  221. Returns:
  222. tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)``.
  223. The disparity is a numpy array of shape (1, H, W) and the images are PIL images.
  224. ``valid_mask`` is implicitly ``None`` if the ``transforms`` parameter does not
  225. generate a valid mask.
  226. Both ``disparity`` and ``valid_mask`` are ``None`` if the dataset split is test.
  227. """
  228. return cast(T1, super().__getitem__(index))
  229. class Kitti2015Stereo(StereoMatchingDataset):
  230. """
  231. KITTI dataset from the `2015 stereo evaluation benchmark <http://www.cvlibs.net/datasets/kitti/eval_scene_flow.php>`_.
  232. The dataset is expected to have the following structure: ::
  233. root
  234. Kitti2015
  235. testing
  236. image_2
  237. img1.png
  238. img2.png
  239. ...
  240. image_3
  241. img1.png
  242. img2.png
  243. ...
  244. training
  245. image_2
  246. img1.png
  247. img2.png
  248. ...
  249. image_3
  250. img1.png
  251. img2.png
  252. ...
  253. disp_occ_0
  254. img1.png
  255. img2.png
  256. ...
  257. disp_occ_1
  258. img1.png
  259. img2.png
  260. ...
  261. calib
  262. Args:
  263. root (str or ``pathlib.Path``): Root directory where `Kitti2015` is located.
  264. split (string, optional): The dataset split of scenes, either "train" (default) or "test".
  265. transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version.
  266. """
  267. _has_built_in_disparity_mask = True
  268. def __init__(self, root: Union[str, Path], split: str = "train", transforms: Optional[Callable] = None) -> None:
  269. super().__init__(root, transforms)
  270. verify_str_arg(split, "split", valid_values=("train", "test"))
  271. root = Path(root) / "Kitti2015" / (split + "ing")
  272. left_img_pattern = str(root / "image_2" / "*.png")
  273. right_img_pattern = str(root / "image_3" / "*.png")
  274. self._images = self._scan_pairs(left_img_pattern, right_img_pattern)
  275. if split == "train":
  276. left_disparity_pattern = str(root / "disp_occ_0" / "*.png")
  277. right_disparity_pattern = str(root / "disp_occ_1" / "*.png")
  278. self._disparities = self._scan_pairs(left_disparity_pattern, right_disparity_pattern)
  279. else:
  280. self._disparities = list((None, None) for _ in self._images)
  281. def _read_disparity(self, file_path: str) -> tuple[Optional[np.ndarray], None]:
  282. # test split has no disparity maps
  283. if file_path is None:
  284. return None, None
  285. disparity_map = np.asarray(Image.open(file_path)) / 256.0
  286. # unsqueeze the disparity map into (C, H, W) format
  287. disparity_map = disparity_map[None, :, :]
  288. valid_mask = None
  289. return disparity_map, valid_mask
  290. def __getitem__(self, index: int) -> T1:
  291. """Return example at given index.
  292. Args:
  293. index(int): The index of the example to retrieve
  294. Returns:
  295. tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)``.
  296. The disparity is a numpy array of shape (1, H, W) and the images are PIL images.
  297. ``valid_mask`` is implicitly ``None`` if the ``transforms`` parameter does not
  298. generate a valid mask.
  299. Both ``disparity`` and ``valid_mask`` are ``None`` if the dataset split is test.
  300. """
  301. return cast(T1, super().__getitem__(index))
  302. class Middlebury2014Stereo(StereoMatchingDataset):
  303. """Publicly available scenes from the Middlebury dataset `2014 version <https://vision.middlebury.edu/stereo/data/scenes2014/>`.
  304. The dataset mostly follows the original format, without containing the ambient subdirectories. : ::
  305. root
  306. Middlebury2014
  307. train
  308. scene1-{perfect,imperfect}
  309. calib.txt
  310. im{0,1}.png
  311. im1E.png
  312. im1L.png
  313. disp{0,1}.pfm
  314. disp{0,1}-n.png
  315. disp{0,1}-sd.pfm
  316. disp{0,1}y.pfm
  317. scene2-{perfect,imperfect}
  318. calib.txt
  319. im{0,1}.png
  320. im1E.png
  321. im1L.png
  322. disp{0,1}.pfm
  323. disp{0,1}-n.png
  324. disp{0,1}-sd.pfm
  325. disp{0,1}y.pfm
  326. ...
  327. additional
  328. scene1-{perfect,imperfect}
  329. calib.txt
  330. im{0,1}.png
  331. im1E.png
  332. im1L.png
  333. disp{0,1}.pfm
  334. disp{0,1}-n.png
  335. disp{0,1}-sd.pfm
  336. disp{0,1}y.pfm
  337. ...
  338. test
  339. scene1
  340. calib.txt
  341. im{0,1}.png
  342. scene2
  343. calib.txt
  344. im{0,1}.png
  345. ...
  346. Args:
  347. root (str or ``pathlib.Path``): Root directory of the Middleburry 2014 Dataset.
  348. split (string, optional): The dataset split of scenes, either "train" (default), "test", or "additional"
  349. use_ambient_views (boolean, optional): Whether to use different expose or lightning views when possible.
  350. The dataset samples with equal probability between ``[im1.png, im1E.png, im1L.png]``.
  351. calibration (string, optional): Whether or not to use the calibrated (default) or uncalibrated scenes.
  352. transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version.
  353. download (boolean, optional): Whether or not to download the dataset in the ``root`` directory.
  354. """
  355. splits = {
  356. "train": [
  357. "Adirondack",
  358. "Jadeplant",
  359. "Motorcycle",
  360. "Piano",
  361. "Pipes",
  362. "Playroom",
  363. "Playtable",
  364. "Recycle",
  365. "Shelves",
  366. "Vintage",
  367. ],
  368. "additional": [
  369. "Backpack",
  370. "Bicycle1",
  371. "Cable",
  372. "Classroom1",
  373. "Couch",
  374. "Flowers",
  375. "Mask",
  376. "Shopvac",
  377. "Sticks",
  378. "Storage",
  379. "Sword1",
  380. "Sword2",
  381. "Umbrella",
  382. ],
  383. "test": [
  384. "Plants",
  385. "Classroom2E",
  386. "Classroom2",
  387. "Australia",
  388. "DjembeL",
  389. "CrusadeP",
  390. "Crusade",
  391. "Hoops",
  392. "Bicycle2",
  393. "Staircase",
  394. "Newkuba",
  395. "AustraliaP",
  396. "Djembe",
  397. "Livingroom",
  398. "Computer",
  399. ],
  400. }
  401. _has_built_in_disparity_mask = True
  402. def __init__(
  403. self,
  404. root: Union[str, Path],
  405. split: str = "train",
  406. calibration: Optional[str] = "perfect",
  407. use_ambient_views: bool = False,
  408. transforms: Optional[Callable] = None,
  409. download: bool = False,
  410. ) -> None:
  411. super().__init__(root, transforms)
  412. verify_str_arg(split, "split", valid_values=("train", "test", "additional"))
  413. self.split = split
  414. if calibration:
  415. verify_str_arg(calibration, "calibration", valid_values=("perfect", "imperfect", "both", None)) # type: ignore
  416. if split == "test":
  417. raise ValueError("Split 'test' has only no calibration settings, please set `calibration=None`.")
  418. else:
  419. if split != "test":
  420. raise ValueError(
  421. f"Split '{split}' has calibration settings, however None was provided as an argument."
  422. f"\nSetting calibration to 'perfect' for split '{split}'. Available calibration settings are: 'perfect', 'imperfect', 'both'.",
  423. )
  424. if download:
  425. self._download_dataset(root)
  426. root = Path(root) / "Middlebury2014"
  427. if not os.path.exists(root / split):
  428. raise FileNotFoundError(f"The {split} directory was not found in the provided root directory")
  429. split_scenes = self.splits[split]
  430. # check that the provided root folder contains the scene splits
  431. if not any(
  432. # using startswith to account for perfect / imperfect calibrartion
  433. scene.startswith(s)
  434. for scene in os.listdir(root / split)
  435. for s in split_scenes
  436. ):
  437. raise FileNotFoundError(f"Provided root folder does not contain any scenes from the {split} split.")
  438. calibrartion_suffixes = {
  439. None: [""],
  440. "perfect": ["-perfect"],
  441. "imperfect": ["-imperfect"],
  442. "both": ["-perfect", "-imperfect"],
  443. }[calibration]
  444. for calibration_suffix in calibrartion_suffixes:
  445. scene_pattern = "*" + calibration_suffix
  446. left_img_pattern = str(root / split / scene_pattern / "im0.png")
  447. right_img_pattern = str(root / split / scene_pattern / "im1.png")
  448. self._images += self._scan_pairs(left_img_pattern, right_img_pattern)
  449. if split == "test":
  450. self._disparities = list((None, None) for _ in self._images)
  451. else:
  452. left_dispartity_pattern = str(root / split / scene_pattern / "disp0.pfm")
  453. right_dispartity_pattern = str(root / split / scene_pattern / "disp1.pfm")
  454. self._disparities += self._scan_pairs(left_dispartity_pattern, right_dispartity_pattern)
  455. self.use_ambient_views = use_ambient_views
  456. def _read_img(self, file_path: Union[str, Path]) -> Image.Image:
  457. """
  458. Function that reads either the original right image or an augmented view when ``use_ambient_views`` is True.
  459. When ``use_ambient_views`` is True, the dataset will return at random one of ``[im1.png, im1E.png, im1L.png]``
  460. as the right image.
  461. """
  462. ambient_file_paths: list[Union[str, Path]] # make mypy happy
  463. if not isinstance(file_path, Path):
  464. file_path = Path(file_path)
  465. if file_path.name == "im1.png" and self.use_ambient_views:
  466. base_path = file_path.parent
  467. # initialize sampleable container
  468. ambient_file_paths = list(base_path / view_name for view_name in ["im1E.png", "im1L.png"])
  469. # double check that we're not going to try to read from an invalid file path
  470. ambient_file_paths = list(filter(lambda p: os.path.exists(p), ambient_file_paths))
  471. # keep the original image as an option as well for uniform sampling between base views
  472. ambient_file_paths.append(file_path)
  473. file_path = random.choice(ambient_file_paths) # type: ignore
  474. return super()._read_img(file_path)
  475. def _read_disparity(self, file_path: str) -> Union[tuple[None, None], tuple[np.ndarray, np.ndarray]]:
  476. # test split has not disparity maps
  477. if file_path is None:
  478. return None, None
  479. disparity_map = _read_pfm_file(file_path)
  480. disparity_map = np.abs(disparity_map) # ensure that the disparity is positive
  481. disparity_map[disparity_map == np.inf] = 0 # remove infinite disparities
  482. valid_mask = (disparity_map > 0).squeeze(0) # mask out invalid disparities
  483. return disparity_map, valid_mask
  484. def _download_dataset(self, root: Union[str, Path]) -> None:
  485. base_url = "https://vision.middlebury.edu/stereo/data/scenes2014/zip"
  486. # train and additional splits have 2 different calibration settings
  487. root = Path(root) / "Middlebury2014"
  488. split_name = self.split
  489. if split_name != "test":
  490. for split_scene in self.splits[split_name]:
  491. split_root = root / split_name
  492. for calibration in ["perfect", "imperfect"]:
  493. scene_name = f"{split_scene}-{calibration}"
  494. scene_url = f"{base_url}/{scene_name}.zip"
  495. # download the scene only if it doesn't exist
  496. if not (split_root / scene_name).exists():
  497. download_and_extract_archive(
  498. url=scene_url,
  499. filename=f"{scene_name}.zip",
  500. download_root=str(split_root),
  501. remove_finished=True,
  502. )
  503. else:
  504. os.makedirs(root / "test")
  505. if any(s not in os.listdir(root / "test") for s in self.splits["test"]):
  506. # test split is downloaded from a different location
  507. test_set_url = "https://vision.middlebury.edu/stereo/submit3/zip/MiddEval3-data-F.zip"
  508. # the unzip is going to produce a directory MiddEval3 with two subdirectories trainingF and testF
  509. # we want to move the contents from testF into the directory
  510. download_and_extract_archive(url=test_set_url, download_root=str(root), remove_finished=True)
  511. for scene_dir, scene_names, _ in os.walk(str(root / "MiddEval3/testF")):
  512. for scene in scene_names:
  513. scene_dst_dir = root / "test"
  514. scene_src_dir = Path(scene_dir) / scene
  515. os.makedirs(scene_dst_dir, exist_ok=True)
  516. shutil.move(str(scene_src_dir), str(scene_dst_dir))
  517. # cleanup MiddEval3 directory
  518. shutil.rmtree(str(root / "MiddEval3"))
  519. def __getitem__(self, index: int) -> T2:
  520. """Return example at given index.
  521. Args:
  522. index(int): The index of the example to retrieve
  523. Returns:
  524. tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)``.
  525. The disparity is a numpy array of shape (1, H, W) and the images are PIL images.
  526. ``valid_mask`` is implicitly ``None`` for `split=test`.
  527. """
  528. return cast(T2, super().__getitem__(index))
  529. class CREStereo(StereoMatchingDataset):
  530. """Synthetic dataset used in training the `CREStereo <https://arxiv.org/pdf/2203.11483.pdf>`_ architecture.
  531. Dataset details on the official paper `repo <https://github.com/megvii-research/CREStereo>`_.
  532. The dataset is expected to have the following structure: ::
  533. root
  534. CREStereo
  535. tree
  536. img1_left.jpg
  537. img1_right.jpg
  538. img1_left.disp.jpg
  539. img1_right.disp.jpg
  540. img2_left.jpg
  541. img2_right.jpg
  542. img2_left.disp.jpg
  543. img2_right.disp.jpg
  544. ...
  545. shapenet
  546. img1_left.jpg
  547. img1_right.jpg
  548. img1_left.disp.jpg
  549. img1_right.disp.jpg
  550. ...
  551. reflective
  552. img1_left.jpg
  553. img1_right.jpg
  554. img1_left.disp.jpg
  555. img1_right.disp.jpg
  556. ...
  557. hole
  558. img1_left.jpg
  559. img1_right.jpg
  560. img1_left.disp.jpg
  561. img1_right.disp.jpg
  562. ...
  563. Args:
  564. root (str): Root directory of the dataset.
  565. transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version.
  566. """
  567. _has_built_in_disparity_mask = True
  568. def __init__(
  569. self,
  570. root: Union[str, Path],
  571. transforms: Optional[Callable] = None,
  572. ) -> None:
  573. super().__init__(root, transforms)
  574. root = Path(root) / "CREStereo"
  575. dirs = ["shapenet", "reflective", "tree", "hole"]
  576. for s in dirs:
  577. left_image_pattern = str(root / s / "*_left.jpg")
  578. right_image_pattern = str(root / s / "*_right.jpg")
  579. imgs = self._scan_pairs(left_image_pattern, right_image_pattern)
  580. self._images += imgs
  581. left_disparity_pattern = str(root / s / "*_left.disp.png")
  582. right_disparity_pattern = str(root / s / "*_right.disp.png")
  583. disparities = self._scan_pairs(left_disparity_pattern, right_disparity_pattern)
  584. self._disparities += disparities
  585. def _read_disparity(self, file_path: str) -> tuple[np.ndarray, None]:
  586. disparity_map = np.asarray(Image.open(file_path), dtype=np.float32)
  587. # unsqueeze the disparity map into (C, H, W) format
  588. disparity_map = disparity_map[None, :, :] / 32.0
  589. valid_mask = None
  590. return disparity_map, valid_mask
  591. def __getitem__(self, index: int) -> T1:
  592. """Return example at given index.
  593. Args:
  594. index(int): The index of the example to retrieve
  595. Returns:
  596. tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)``.
  597. The disparity is a numpy array of shape (1, H, W) and the images are PIL images.
  598. ``valid_mask`` is implicitly ``None`` if the ``transforms`` parameter does not
  599. generate a valid mask.
  600. """
  601. return cast(T1, super().__getitem__(index))
  602. class FallingThingsStereo(StereoMatchingDataset):
  603. """`FallingThings <https://research.nvidia.com/publication/2018-06_falling-things-synthetic-dataset-3d-object-detection-and-pose-estimation>`_ dataset.
  604. The dataset is expected to have the following structure: ::
  605. root
  606. FallingThings
  607. single
  608. dir1
  609. scene1
  610. _object_settings.json
  611. _camera_settings.json
  612. image1.left.depth.png
  613. image1.right.depth.png
  614. image1.left.jpg
  615. image1.right.jpg
  616. image2.left.depth.png
  617. image2.right.depth.png
  618. image2.left.jpg
  619. image2.right
  620. ...
  621. scene2
  622. ...
  623. mixed
  624. scene1
  625. _object_settings.json
  626. _camera_settings.json
  627. image1.left.depth.png
  628. image1.right.depth.png
  629. image1.left.jpg
  630. image1.right.jpg
  631. image2.left.depth.png
  632. image2.right.depth.png
  633. image2.left.jpg
  634. image2.right
  635. ...
  636. scene2
  637. ...
  638. Args:
  639. root (str or ``pathlib.Path``): Root directory where FallingThings is located.
  640. variant (string): Which variant to use. Either "single", "mixed", or "both".
  641. transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version.
  642. """
  643. def __init__(self, root: Union[str, Path], variant: str = "single", transforms: Optional[Callable] = None) -> None:
  644. super().__init__(root, transforms)
  645. root = Path(root) / "FallingThings"
  646. verify_str_arg(variant, "variant", valid_values=("single", "mixed", "both"))
  647. variants = {
  648. "single": ["single"],
  649. "mixed": ["mixed"],
  650. "both": ["single", "mixed"],
  651. }[variant]
  652. split_prefix = {
  653. "single": Path("*") / "*",
  654. "mixed": Path("*"),
  655. }
  656. for s in variants:
  657. left_img_pattern = str(root / s / split_prefix[s] / "*.left.jpg")
  658. right_img_pattern = str(root / s / split_prefix[s] / "*.right.jpg")
  659. self._images += self._scan_pairs(left_img_pattern, right_img_pattern)
  660. left_disparity_pattern = str(root / s / split_prefix[s] / "*.left.depth.png")
  661. right_disparity_pattern = str(root / s / split_prefix[s] / "*.right.depth.png")
  662. self._disparities += self._scan_pairs(left_disparity_pattern, right_disparity_pattern)
  663. def _read_disparity(self, file_path: str) -> tuple[np.ndarray, None]:
  664. # (H, W) image
  665. depth = np.asarray(Image.open(file_path))
  666. # as per https://research.nvidia.com/sites/default/files/pubs/2018-06_Falling-Things/readme_0.txt
  667. # in order to extract disparity from depth maps
  668. camera_settings_path = Path(file_path).parent / "_camera_settings.json"
  669. with open(camera_settings_path) as f:
  670. # inverse of depth-from-disparity equation: depth = (baseline * focal) / (disparity * pixel_constant)
  671. intrinsics = json.load(f)
  672. focal = intrinsics["camera_settings"][0]["intrinsic_settings"]["fx"]
  673. baseline, pixel_constant = 6, 100 # pixel constant is inverted
  674. disparity_map = (baseline * focal * pixel_constant) / depth.astype(np.float32)
  675. # unsqueeze disparity to (C, H, W)
  676. disparity_map = disparity_map[None, :, :]
  677. valid_mask = None
  678. return disparity_map, valid_mask
  679. def __getitem__(self, index: int) -> T1:
  680. """Return example at given index.
  681. Args:
  682. index(int): The index of the example to retrieve
  683. Returns:
  684. tuple: A 3-tuple with ``(img_left, img_right, disparity)``.
  685. The disparity is a numpy array of shape (1, H, W) and the images are PIL images.
  686. If a ``valid_mask`` is generated within the ``transforms`` parameter,
  687. a 4-tuple with ``(img_left, img_right, disparity, valid_mask)`` is returned.
  688. """
  689. return cast(T1, super().__getitem__(index))
  690. class SceneFlowStereo(StereoMatchingDataset):
  691. """Dataset interface for `Scene Flow <https://lmb.informatik.uni-freiburg.de/resources/datasets/SceneFlowDatasets.en.html>`_ datasets.
  692. This interface provides access to the `FlyingThings3D, `Monkaa` and `Driving` datasets.
  693. The dataset is expected to have the following structure: ::
  694. root
  695. SceneFlow
  696. Monkaa
  697. frames_cleanpass
  698. scene1
  699. left
  700. img1.png
  701. img2.png
  702. right
  703. img1.png
  704. img2.png
  705. scene2
  706. left
  707. img1.png
  708. img2.png
  709. right
  710. img1.png
  711. img2.png
  712. frames_finalpass
  713. scene1
  714. left
  715. img1.png
  716. img2.png
  717. right
  718. img1.png
  719. img2.png
  720. ...
  721. ...
  722. disparity
  723. scene1
  724. left
  725. img1.pfm
  726. img2.pfm
  727. right
  728. img1.pfm
  729. img2.pfm
  730. FlyingThings3D
  731. ...
  732. ...
  733. Args:
  734. root (str or ``pathlib.Path``): Root directory where SceneFlow is located.
  735. variant (string): Which dataset variant to user, "FlyingThings3D" (default), "Monkaa" or "Driving".
  736. pass_name (string): Which pass to use, "clean" (default), "final" or "both".
  737. transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version.
  738. """
  739. def __init__(
  740. self,
  741. root: Union[str, Path],
  742. variant: str = "FlyingThings3D",
  743. pass_name: str = "clean",
  744. transforms: Optional[Callable] = None,
  745. ) -> None:
  746. super().__init__(root, transforms)
  747. root = Path(root) / "SceneFlow"
  748. verify_str_arg(variant, "variant", valid_values=("FlyingThings3D", "Driving", "Monkaa"))
  749. verify_str_arg(pass_name, "pass_name", valid_values=("clean", "final", "both"))
  750. passes = {
  751. "clean": ["frames_cleanpass"],
  752. "final": ["frames_finalpass"],
  753. "both": ["frames_cleanpass", "frames_finalpass"],
  754. }[pass_name]
  755. root = root / variant
  756. prefix_directories = {
  757. "Monkaa": Path("*"),
  758. "FlyingThings3D": Path("*") / "*" / "*",
  759. "Driving": Path("*") / "*" / "*",
  760. }
  761. for p in passes:
  762. left_image_pattern = str(root / p / prefix_directories[variant] / "left" / "*.png")
  763. right_image_pattern = str(root / p / prefix_directories[variant] / "right" / "*.png")
  764. self._images += self._scan_pairs(left_image_pattern, right_image_pattern)
  765. left_disparity_pattern = str(root / "disparity" / prefix_directories[variant] / "left" / "*.pfm")
  766. right_disparity_pattern = str(root / "disparity" / prefix_directories[variant] / "right" / "*.pfm")
  767. self._disparities += self._scan_pairs(left_disparity_pattern, right_disparity_pattern)
  768. def _read_disparity(self, file_path: str) -> tuple[np.ndarray, None]:
  769. disparity_map = _read_pfm_file(file_path)
  770. disparity_map = np.abs(disparity_map) # ensure that the disparity is positive
  771. valid_mask = None
  772. return disparity_map, valid_mask
  773. def __getitem__(self, index: int) -> T1:
  774. """Return example at given index.
  775. Args:
  776. index(int): The index of the example to retrieve
  777. Returns:
  778. tuple: A 3-tuple with ``(img_left, img_right, disparity)``.
  779. The disparity is a numpy array of shape (1, H, W) and the images are PIL images.
  780. If a ``valid_mask`` is generated within the ``transforms`` parameter,
  781. a 4-tuple with ``(img_left, img_right, disparity, valid_mask)`` is returned.
  782. """
  783. return cast(T1, super().__getitem__(index))
  784. class SintelStereo(StereoMatchingDataset):
  785. """Sintel `Stereo Dataset <http://sintel.is.tue.mpg.de/stereo>`_.
  786. The dataset is expected to have the following structure: ::
  787. root
  788. Sintel
  789. training
  790. final_left
  791. scene1
  792. img1.png
  793. img2.png
  794. ...
  795. ...
  796. final_right
  797. scene2
  798. img1.png
  799. img2.png
  800. ...
  801. ...
  802. disparities
  803. scene1
  804. img1.png
  805. img2.png
  806. ...
  807. ...
  808. occlusions
  809. scene1
  810. img1.png
  811. img2.png
  812. ...
  813. ...
  814. outofframe
  815. scene1
  816. img1.png
  817. img2.png
  818. ...
  819. ...
  820. Args:
  821. root (str or ``pathlib.Path``): Root directory where Sintel Stereo is located.
  822. pass_name (string): The name of the pass to use, either "final", "clean" or "both".
  823. transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version.
  824. """
  825. _has_built_in_disparity_mask = True
  826. def __init__(self, root: Union[str, Path], pass_name: str = "final", transforms: Optional[Callable] = None) -> None:
  827. super().__init__(root, transforms)
  828. verify_str_arg(pass_name, "pass_name", valid_values=("final", "clean", "both"))
  829. root = Path(root) / "Sintel"
  830. pass_names = {
  831. "final": ["final"],
  832. "clean": ["clean"],
  833. "both": ["final", "clean"],
  834. }[pass_name]
  835. for p in pass_names:
  836. left_img_pattern = str(root / "training" / f"{p}_left" / "*" / "*.png")
  837. right_img_pattern = str(root / "training" / f"{p}_right" / "*" / "*.png")
  838. self._images += self._scan_pairs(left_img_pattern, right_img_pattern)
  839. disparity_pattern = str(root / "training" / "disparities" / "*" / "*.png")
  840. self._disparities += self._scan_pairs(disparity_pattern, None)
  841. def _get_occlussion_mask_paths(self, file_path: str) -> tuple[str, str]:
  842. # helper function to get the occlusion mask paths
  843. # a path will look like .../.../.../training/disparities/scene1/img1.png
  844. # we want to get something like .../.../.../training/occlusions/scene1/img1.png
  845. fpath = Path(file_path)
  846. basename = fpath.name
  847. scenedir = fpath.parent
  848. # the parent of the scenedir is actually the disparity dir
  849. sampledir = scenedir.parent.parent
  850. occlusion_path = str(sampledir / "occlusions" / scenedir.name / basename)
  851. outofframe_path = str(sampledir / "outofframe" / scenedir.name / basename)
  852. if not os.path.exists(occlusion_path):
  853. raise FileNotFoundError(f"Occlusion mask {occlusion_path} does not exist")
  854. if not os.path.exists(outofframe_path):
  855. raise FileNotFoundError(f"Out of frame mask {outofframe_path} does not exist")
  856. return occlusion_path, outofframe_path
  857. def _read_disparity(self, file_path: str) -> Union[tuple[None, None], tuple[np.ndarray, np.ndarray]]:
  858. if file_path is None:
  859. return None, None
  860. # disparity decoding as per Sintel instructions in the README provided with the dataset
  861. disparity_map = np.asarray(Image.open(file_path), dtype=np.float32)
  862. r, g, b = np.split(disparity_map, 3, axis=-1)
  863. disparity_map = r * 4 + g / (2**6) + b / (2**14)
  864. # reshape into (C, H, W) format
  865. disparity_map = np.transpose(disparity_map, (2, 0, 1))
  866. # find the appropriate file paths
  867. occlued_mask_path, out_of_frame_mask_path = self._get_occlussion_mask_paths(file_path)
  868. # occlusion masks
  869. valid_mask = np.asarray(Image.open(occlued_mask_path)) == 0
  870. # out of frame masks
  871. off_mask = np.asarray(Image.open(out_of_frame_mask_path)) == 0
  872. # combine the masks together
  873. valid_mask = np.logical_and(off_mask, valid_mask)
  874. return disparity_map, valid_mask
  875. def __getitem__(self, index: int) -> T2:
  876. """Return example at given index.
  877. Args:
  878. index(int): The index of the example to retrieve
  879. Returns:
  880. tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)`` is returned.
  881. The disparity is a numpy array of shape (1, H, W) and the images are PIL images whilst
  882. the valid_mask is a numpy array of shape (H, W).
  883. """
  884. return cast(T2, super().__getitem__(index))
  885. class InStereo2k(StereoMatchingDataset):
  886. """`InStereo2k <https://github.com/YuhuaXu/StereoDataset>`_ dataset.
  887. The dataset is expected to have the following structure: ::
  888. root
  889. InStereo2k
  890. train
  891. scene1
  892. left.png
  893. right.png
  894. left_disp.png
  895. right_disp.png
  896. ...
  897. scene2
  898. ...
  899. test
  900. scene1
  901. left.png
  902. right.png
  903. left_disp.png
  904. right_disp.png
  905. ...
  906. scene2
  907. ...
  908. Args:
  909. root (str or ``pathlib.Path``): Root directory where InStereo2k is located.
  910. split (string): Either "train" or "test".
  911. transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version.
  912. """
  913. def __init__(self, root: Union[str, Path], split: str = "train", transforms: Optional[Callable] = None) -> None:
  914. super().__init__(root, transforms)
  915. root = Path(root) / "InStereo2k" / split
  916. verify_str_arg(split, "split", valid_values=("train", "test"))
  917. left_img_pattern = str(root / "*" / "left.png")
  918. right_img_pattern = str(root / "*" / "right.png")
  919. self._images = self._scan_pairs(left_img_pattern, right_img_pattern)
  920. left_disparity_pattern = str(root / "*" / "left_disp.png")
  921. right_disparity_pattern = str(root / "*" / "right_disp.png")
  922. self._disparities = self._scan_pairs(left_disparity_pattern, right_disparity_pattern)
  923. def _read_disparity(self, file_path: str) -> tuple[np.ndarray, None]:
  924. disparity_map = np.asarray(Image.open(file_path), dtype=np.float32)
  925. # unsqueeze disparity to (C, H, W)
  926. disparity_map = disparity_map[None, :, :] / 1024.0
  927. valid_mask = None
  928. return disparity_map, valid_mask
  929. def __getitem__(self, index: int) -> T1:
  930. """Return example at given index.
  931. Args:
  932. index(int): The index of the example to retrieve
  933. Returns:
  934. tuple: A 3-tuple with ``(img_left, img_right, disparity)``.
  935. The disparity is a numpy array of shape (1, H, W) and the images are PIL images.
  936. If a ``valid_mask`` is generated within the ``transforms`` parameter,
  937. a 4-tuple with ``(img_left, img_right, disparity, valid_mask)`` is returned.
  938. """
  939. return cast(T1, super().__getitem__(index))
  940. class ETH3DStereo(StereoMatchingDataset):
  941. """ETH3D `Low-Res Two-View <https://www.eth3d.net/datasets>`_ dataset.
  942. The dataset is expected to have the following structure: ::
  943. root
  944. ETH3D
  945. two_view_training
  946. scene1
  947. im1.png
  948. im0.png
  949. images.txt
  950. cameras.txt
  951. calib.txt
  952. scene2
  953. im1.png
  954. im0.png
  955. images.txt
  956. cameras.txt
  957. calib.txt
  958. ...
  959. two_view_training_gt
  960. scene1
  961. disp0GT.pfm
  962. mask0nocc.png
  963. scene2
  964. disp0GT.pfm
  965. mask0nocc.png
  966. ...
  967. two_view_testing
  968. scene1
  969. im1.png
  970. im0.png
  971. images.txt
  972. cameras.txt
  973. calib.txt
  974. scene2
  975. im1.png
  976. im0.png
  977. images.txt
  978. cameras.txt
  979. calib.txt
  980. ...
  981. Args:
  982. root (str or ``pathlib.Path``): Root directory of the ETH3D Dataset.
  983. split (string, optional): The dataset split of scenes, either "train" (default) or "test".
  984. transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version.
  985. """
  986. _has_built_in_disparity_mask = True
  987. def __init__(self, root: Union[str, Path], split: str = "train", transforms: Optional[Callable] = None) -> None:
  988. super().__init__(root, transforms)
  989. verify_str_arg(split, "split", valid_values=("train", "test"))
  990. root = Path(root) / "ETH3D"
  991. img_dir = "two_view_training" if split == "train" else "two_view_test"
  992. anot_dir = "two_view_training_gt"
  993. left_img_pattern = str(root / img_dir / "*" / "im0.png")
  994. right_img_pattern = str(root / img_dir / "*" / "im1.png")
  995. self._images = self._scan_pairs(left_img_pattern, right_img_pattern)
  996. if split == "test":
  997. self._disparities = list((None, None) for _ in self._images)
  998. else:
  999. disparity_pattern = str(root / anot_dir / "*" / "disp0GT.pfm")
  1000. self._disparities = self._scan_pairs(disparity_pattern, None)
  1001. def _read_disparity(self, file_path: str) -> Union[tuple[None, None], tuple[np.ndarray, np.ndarray]]:
  1002. # test split has no disparity maps
  1003. if file_path is None:
  1004. return None, None
  1005. disparity_map = _read_pfm_file(file_path)
  1006. disparity_map = np.abs(disparity_map) # ensure that the disparity is positive
  1007. mask_path = Path(file_path).parent / "mask0nocc.png"
  1008. valid_mask = Image.open(mask_path)
  1009. valid_mask = np.asarray(valid_mask).astype(bool)
  1010. return disparity_map, valid_mask
  1011. def __getitem__(self, index: int) -> T2:
  1012. """Return example at given index.
  1013. Args:
  1014. index(int): The index of the example to retrieve
  1015. Returns:
  1016. tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)``.
  1017. The disparity is a numpy array of shape (1, H, W) and the images are PIL images.
  1018. ``valid_mask`` is implicitly ``None`` if the ``transforms`` parameter does not
  1019. generate a valid mask.
  1020. Both ``disparity`` and ``valid_mask`` are ``None`` if the dataset split is test.
  1021. """
  1022. return cast(T2, super().__getitem__(index))