_optical_flow.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. import itertools
  2. import os
  3. from abc import ABC, abstractmethod
  4. from glob import glob
  5. from pathlib import Path
  6. from typing import Callable, List, Optional, Tuple, Union
  7. import numpy as np
  8. import torch
  9. from PIL import Image
  10. from ..io.image import _read_png_16
  11. from .utils import _read_pfm, verify_str_arg
  12. from .vision import VisionDataset
  13. T1 = Tuple[Image.Image, Image.Image, Optional[np.ndarray], Optional[np.ndarray]]
  14. T2 = Tuple[Image.Image, Image.Image, Optional[np.ndarray]]
  15. __all__ = (
  16. "KittiFlow",
  17. "Sintel",
  18. "FlyingThings3D",
  19. "FlyingChairs",
  20. "HD1K",
  21. )
  22. class FlowDataset(ABC, VisionDataset):
  23. # Some datasets like Kitti have a built-in valid_flow_mask, indicating which flow values are valid
  24. # For those we return (img1, img2, flow, valid_flow_mask), and for the rest we return (img1, img2, flow),
  25. # and it's up to whatever consumes the dataset to decide what valid_flow_mask should be.
  26. _has_builtin_flow_mask = False
  27. def __init__(self, root: str, transforms: Optional[Callable] = None) -> None:
  28. super().__init__(root=root)
  29. self.transforms = transforms
  30. self._flow_list: List[str] = []
  31. self._image_list: List[List[str]] = []
  32. def _read_img(self, file_name: str) -> Image.Image:
  33. img = Image.open(file_name)
  34. if img.mode != "RGB":
  35. img = img.convert("RGB")
  36. return img
  37. @abstractmethod
  38. def _read_flow(self, file_name: str):
  39. # Return the flow or a tuple with the flow and the valid_flow_mask if _has_builtin_flow_mask is True
  40. pass
  41. def __getitem__(self, index: int) -> Union[T1, T2]:
  42. img1 = self._read_img(self._image_list[index][0])
  43. img2 = self._read_img(self._image_list[index][1])
  44. if self._flow_list: # it will be empty for some dataset when split="test"
  45. flow = self._read_flow(self._flow_list[index])
  46. if self._has_builtin_flow_mask:
  47. flow, valid_flow_mask = flow
  48. else:
  49. valid_flow_mask = None
  50. else:
  51. flow = valid_flow_mask = None
  52. if self.transforms is not None:
  53. img1, img2, flow, valid_flow_mask = self.transforms(img1, img2, flow, valid_flow_mask)
  54. if self._has_builtin_flow_mask or valid_flow_mask is not None:
  55. # The `or valid_flow_mask is not None` part is here because the mask can be generated within a transform
  56. return img1, img2, flow, valid_flow_mask
  57. else:
  58. return img1, img2, flow
  59. def __len__(self) -> int:
  60. return len(self._image_list)
  61. def __rmul__(self, v: int) -> torch.utils.data.ConcatDataset:
  62. return torch.utils.data.ConcatDataset([self] * v)
  63. class Sintel(FlowDataset):
  64. """`Sintel <http://sintel.is.tue.mpg.de/>`_ Dataset for optical flow.
  65. The dataset is expected to have the following structure: ::
  66. root
  67. Sintel
  68. testing
  69. clean
  70. scene_1
  71. scene_2
  72. ...
  73. final
  74. scene_1
  75. scene_2
  76. ...
  77. training
  78. clean
  79. scene_1
  80. scene_2
  81. ...
  82. final
  83. scene_1
  84. scene_2
  85. ...
  86. flow
  87. scene_1
  88. scene_2
  89. ...
  90. Args:
  91. root (string): Root directory of the Sintel Dataset.
  92. split (string, optional): The dataset split, either "train" (default) or "test"
  93. pass_name (string, optional): The pass to use, either "clean" (default), "final", or "both". See link above for
  94. details on the different passes.
  95. transforms (callable, optional): A function/transform that takes in
  96. ``img1, img2, flow, valid_flow_mask`` and returns a transformed version.
  97. ``valid_flow_mask`` is expected for consistency with other datasets which
  98. return a built-in valid mask, such as :class:`~torchvision.datasets.KittiFlow`.
  99. """
  100. def __init__(
  101. self,
  102. root: str,
  103. split: str = "train",
  104. pass_name: str = "clean",
  105. transforms: Optional[Callable] = None,
  106. ) -> None:
  107. super().__init__(root=root, transforms=transforms)
  108. verify_str_arg(split, "split", valid_values=("train", "test"))
  109. verify_str_arg(pass_name, "pass_name", valid_values=("clean", "final", "both"))
  110. passes = ["clean", "final"] if pass_name == "both" else [pass_name]
  111. root = Path(root) / "Sintel"
  112. flow_root = root / "training" / "flow"
  113. for pass_name in passes:
  114. split_dir = "training" if split == "train" else split
  115. image_root = root / split_dir / pass_name
  116. for scene in os.listdir(image_root):
  117. image_list = sorted(glob(str(image_root / scene / "*.png")))
  118. for i in range(len(image_list) - 1):
  119. self._image_list += [[image_list[i], image_list[i + 1]]]
  120. if split == "train":
  121. self._flow_list += sorted(glob(str(flow_root / scene / "*.flo")))
  122. def __getitem__(self, index: int) -> Union[T1, T2]:
  123. """Return example at given index.
  124. Args:
  125. index(int): The index of the example to retrieve
  126. Returns:
  127. tuple: A 3-tuple with ``(img1, img2, flow)``.
  128. The flow is a numpy array of shape (2, H, W) and the images are PIL images.
  129. ``flow`` is None if ``split="test"``.
  130. If a valid flow mask is generated within the ``transforms`` parameter,
  131. a 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` is returned.
  132. """
  133. return super().__getitem__(index)
  134. def _read_flow(self, file_name: str) -> np.ndarray:
  135. return _read_flo(file_name)
  136. class KittiFlow(FlowDataset):
  137. """`KITTI <http://www.cvlibs.net/datasets/kitti/eval_scene_flow.php?benchmark=flow>`__ dataset for optical flow (2015).
  138. The dataset is expected to have the following structure: ::
  139. root
  140. KittiFlow
  141. testing
  142. image_2
  143. training
  144. image_2
  145. flow_occ
  146. Args:
  147. root (string): Root directory of the KittiFlow Dataset.
  148. split (string, optional): The dataset split, either "train" (default) or "test"
  149. transforms (callable, optional): A function/transform that takes in
  150. ``img1, img2, flow, valid_flow_mask`` and returns a transformed version.
  151. """
  152. _has_builtin_flow_mask = True
  153. def __init__(self, root: str, split: str = "train", transforms: Optional[Callable] = None) -> None:
  154. super().__init__(root=root, transforms=transforms)
  155. verify_str_arg(split, "split", valid_values=("train", "test"))
  156. root = Path(root) / "KittiFlow" / (split + "ing")
  157. images1 = sorted(glob(str(root / "image_2" / "*_10.png")))
  158. images2 = sorted(glob(str(root / "image_2" / "*_11.png")))
  159. if not images1 or not images2:
  160. raise FileNotFoundError(
  161. "Could not find the Kitti flow images. Please make sure the directory structure is correct."
  162. )
  163. for img1, img2 in zip(images1, images2):
  164. self._image_list += [[img1, img2]]
  165. if split == "train":
  166. self._flow_list = sorted(glob(str(root / "flow_occ" / "*_10.png")))
  167. def __getitem__(self, index: int) -> Union[T1, T2]:
  168. """Return example at given index.
  169. Args:
  170. index(int): The index of the example to retrieve
  171. Returns:
  172. tuple: A 4-tuple with ``(img1, img2, flow, valid_flow_mask)``
  173. where ``valid_flow_mask`` is a numpy boolean mask of shape (H, W)
  174. indicating which flow values are valid. The flow is a numpy array of
  175. shape (2, H, W) and the images are PIL images. ``flow`` and ``valid_flow_mask`` are None if
  176. ``split="test"``.
  177. """
  178. return super().__getitem__(index)
  179. def _read_flow(self, file_name: str) -> Tuple[np.ndarray, np.ndarray]:
  180. return _read_16bits_png_with_flow_and_valid_mask(file_name)
  181. class FlyingChairs(FlowDataset):
  182. """`FlyingChairs <https://lmb.informatik.uni-freiburg.de/resources/datasets/FlyingChairs.en.html#flyingchairs>`_ Dataset for optical flow.
  183. You will also need to download the FlyingChairs_train_val.txt file from the dataset page.
  184. The dataset is expected to have the following structure: ::
  185. root
  186. FlyingChairs
  187. data
  188. 00001_flow.flo
  189. 00001_img1.ppm
  190. 00001_img2.ppm
  191. ...
  192. FlyingChairs_train_val.txt
  193. Args:
  194. root (string): Root directory of the FlyingChairs Dataset.
  195. split (string, optional): The dataset split, either "train" (default) or "val"
  196. transforms (callable, optional): A function/transform that takes in
  197. ``img1, img2, flow, valid_flow_mask`` and returns a transformed version.
  198. ``valid_flow_mask`` is expected for consistency with other datasets which
  199. return a built-in valid mask, such as :class:`~torchvision.datasets.KittiFlow`.
  200. """
  201. def __init__(self, root: str, split: str = "train", transforms: Optional[Callable] = None) -> None:
  202. super().__init__(root=root, transforms=transforms)
  203. verify_str_arg(split, "split", valid_values=("train", "val"))
  204. root = Path(root) / "FlyingChairs"
  205. images = sorted(glob(str(root / "data" / "*.ppm")))
  206. flows = sorted(glob(str(root / "data" / "*.flo")))
  207. split_file_name = "FlyingChairs_train_val.txt"
  208. if not os.path.exists(root / split_file_name):
  209. raise FileNotFoundError(
  210. "The FlyingChairs_train_val.txt file was not found - please download it from the dataset page (see docstring)."
  211. )
  212. split_list = np.loadtxt(str(root / split_file_name), dtype=np.int32)
  213. for i in range(len(flows)):
  214. split_id = split_list[i]
  215. if (split == "train" and split_id == 1) or (split == "val" and split_id == 2):
  216. self._flow_list += [flows[i]]
  217. self._image_list += [[images[2 * i], images[2 * i + 1]]]
  218. def __getitem__(self, index: int) -> Union[T1, T2]:
  219. """Return example at given index.
  220. Args:
  221. index(int): The index of the example to retrieve
  222. Returns:
  223. tuple: A 3-tuple with ``(img1, img2, flow)``.
  224. The flow is a numpy array of shape (2, H, W) and the images are PIL images.
  225. ``flow`` is None if ``split="val"``.
  226. If a valid flow mask is generated within the ``transforms`` parameter,
  227. a 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` is returned.
  228. """
  229. return super().__getitem__(index)
  230. def _read_flow(self, file_name: str) -> np.ndarray:
  231. return _read_flo(file_name)
  232. class FlyingThings3D(FlowDataset):
  233. """`FlyingThings3D <https://lmb.informatik.uni-freiburg.de/resources/datasets/SceneFlowDatasets.en.html>`_ dataset for optical flow.
  234. The dataset is expected to have the following structure: ::
  235. root
  236. FlyingThings3D
  237. frames_cleanpass
  238. TEST
  239. TRAIN
  240. frames_finalpass
  241. TEST
  242. TRAIN
  243. optical_flow
  244. TEST
  245. TRAIN
  246. Args:
  247. root (string): Root directory of the intel FlyingThings3D Dataset.
  248. split (string, optional): The dataset split, either "train" (default) or "test"
  249. pass_name (string, optional): The pass to use, either "clean" (default) or "final" or "both". See link above for
  250. details on the different passes.
  251. camera (string, optional): Which camera to return images from. Can be either "left" (default) or "right" or "both".
  252. transforms (callable, optional): A function/transform that takes in
  253. ``img1, img2, flow, valid_flow_mask`` and returns a transformed version.
  254. ``valid_flow_mask`` is expected for consistency with other datasets which
  255. return a built-in valid mask, such as :class:`~torchvision.datasets.KittiFlow`.
  256. """
  257. def __init__(
  258. self,
  259. root: str,
  260. split: str = "train",
  261. pass_name: str = "clean",
  262. camera: str = "left",
  263. transforms: Optional[Callable] = None,
  264. ) -> None:
  265. super().__init__(root=root, transforms=transforms)
  266. verify_str_arg(split, "split", valid_values=("train", "test"))
  267. split = split.upper()
  268. verify_str_arg(pass_name, "pass_name", valid_values=("clean", "final", "both"))
  269. passes = {
  270. "clean": ["frames_cleanpass"],
  271. "final": ["frames_finalpass"],
  272. "both": ["frames_cleanpass", "frames_finalpass"],
  273. }[pass_name]
  274. verify_str_arg(camera, "camera", valid_values=("left", "right", "both"))
  275. cameras = ["left", "right"] if camera == "both" else [camera]
  276. root = Path(root) / "FlyingThings3D"
  277. directions = ("into_future", "into_past")
  278. for pass_name, camera, direction in itertools.product(passes, cameras, directions):
  279. image_dirs = sorted(glob(str(root / pass_name / split / "*/*")))
  280. image_dirs = sorted(Path(image_dir) / camera for image_dir in image_dirs)
  281. flow_dirs = sorted(glob(str(root / "optical_flow" / split / "*/*")))
  282. flow_dirs = sorted(Path(flow_dir) / direction / camera for flow_dir in flow_dirs)
  283. if not image_dirs or not flow_dirs:
  284. raise FileNotFoundError(
  285. "Could not find the FlyingThings3D flow images. "
  286. "Please make sure the directory structure is correct."
  287. )
  288. for image_dir, flow_dir in zip(image_dirs, flow_dirs):
  289. images = sorted(glob(str(image_dir / "*.png")))
  290. flows = sorted(glob(str(flow_dir / "*.pfm")))
  291. for i in range(len(flows) - 1):
  292. if direction == "into_future":
  293. self._image_list += [[images[i], images[i + 1]]]
  294. self._flow_list += [flows[i]]
  295. elif direction == "into_past":
  296. self._image_list += [[images[i + 1], images[i]]]
  297. self._flow_list += [flows[i + 1]]
  298. def __getitem__(self, index: int) -> Union[T1, T2]:
  299. """Return example at given index.
  300. Args:
  301. index(int): The index of the example to retrieve
  302. Returns:
  303. tuple: A 3-tuple with ``(img1, img2, flow)``.
  304. The flow is a numpy array of shape (2, H, W) and the images are PIL images.
  305. ``flow`` is None if ``split="test"``.
  306. If a valid flow mask is generated within the ``transforms`` parameter,
  307. a 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` is returned.
  308. """
  309. return super().__getitem__(index)
  310. def _read_flow(self, file_name: str) -> np.ndarray:
  311. return _read_pfm(file_name)
  312. class HD1K(FlowDataset):
  313. """`HD1K <http://hci-benchmark.iwr.uni-heidelberg.de/>`__ dataset for optical flow.
  314. The dataset is expected to have the following structure: ::
  315. root
  316. hd1k
  317. hd1k_challenge
  318. image_2
  319. hd1k_flow_gt
  320. flow_occ
  321. hd1k_input
  322. image_2
  323. Args:
  324. root (string): Root directory of the HD1K Dataset.
  325. split (string, optional): The dataset split, either "train" (default) or "test"
  326. transforms (callable, optional): A function/transform that takes in
  327. ``img1, img2, flow, valid_flow_mask`` and returns a transformed version.
  328. """
  329. _has_builtin_flow_mask = True
  330. def __init__(self, root: str, split: str = "train", transforms: Optional[Callable] = None) -> None:
  331. super().__init__(root=root, transforms=transforms)
  332. verify_str_arg(split, "split", valid_values=("train", "test"))
  333. root = Path(root) / "hd1k"
  334. if split == "train":
  335. # There are 36 "sequences" and we don't want seq i to overlap with seq i + 1, so we need this for loop
  336. for seq_idx in range(36):
  337. flows = sorted(glob(str(root / "hd1k_flow_gt" / "flow_occ" / f"{seq_idx:06d}_*.png")))
  338. images = sorted(glob(str(root / "hd1k_input" / "image_2" / f"{seq_idx:06d}_*.png")))
  339. for i in range(len(flows) - 1):
  340. self._flow_list += [flows[i]]
  341. self._image_list += [[images[i], images[i + 1]]]
  342. else:
  343. images1 = sorted(glob(str(root / "hd1k_challenge" / "image_2" / "*10.png")))
  344. images2 = sorted(glob(str(root / "hd1k_challenge" / "image_2" / "*11.png")))
  345. for image1, image2 in zip(images1, images2):
  346. self._image_list += [[image1, image2]]
  347. if not self._image_list:
  348. raise FileNotFoundError(
  349. "Could not find the HD1K images. Please make sure the directory structure is correct."
  350. )
  351. def _read_flow(self, file_name: str) -> Tuple[np.ndarray, np.ndarray]:
  352. return _read_16bits_png_with_flow_and_valid_mask(file_name)
  353. def __getitem__(self, index: int) -> Union[T1, T2]:
  354. """Return example at given index.
  355. Args:
  356. index(int): The index of the example to retrieve
  357. Returns:
  358. tuple: A 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` where ``valid_flow_mask``
  359. is a numpy boolean mask of shape (H, W)
  360. indicating which flow values are valid. The flow is a numpy array of
  361. shape (2, H, W) and the images are PIL images. ``flow`` and ``valid_flow_mask`` are None if
  362. ``split="test"``.
  363. """
  364. return super().__getitem__(index)
  365. def _read_flo(file_name: str) -> np.ndarray:
  366. """Read .flo file in Middlebury format"""
  367. # Code adapted from:
  368. # http://stackoverflow.com/questions/28013200/reading-middlebury-flow-files-with-python-bytes-array-numpy
  369. # Everything needs to be in little Endian according to
  370. # https://vision.middlebury.edu/flow/code/flow-code/README.txt
  371. with open(file_name, "rb") as f:
  372. magic = np.fromfile(f, "c", count=4).tobytes()
  373. if magic != b"PIEH":
  374. raise ValueError("Magic number incorrect. Invalid .flo file")
  375. w = int(np.fromfile(f, "<i4", count=1))
  376. h = int(np.fromfile(f, "<i4", count=1))
  377. data = np.fromfile(f, "<f4", count=2 * w * h)
  378. return data.reshape(h, w, 2).transpose(2, 0, 1)
  379. def _read_16bits_png_with_flow_and_valid_mask(file_name: str) -> Tuple[np.ndarray, np.ndarray]:
  380. flow_and_valid = _read_png_16(file_name).to(torch.float32)
  381. flow, valid_flow_mask = flow_and_valid[:2, :, :], flow_and_valid[2, :, :]
  382. flow = (flow - 2**15) / 64 # This conversion is explained somewhere on the kitti archive
  383. valid_flow_mask = valid_flow_mask.bool()
  384. # For consistency with other datasets, we convert to numpy
  385. return flow.numpy(), valid_flow_mask.numpy()