ucf101.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. import os
  2. from pathlib import Path
  3. from typing import Any, Callable, Optional, Union
  4. from torch import Tensor
  5. from .folder import find_classes, make_dataset
  6. from .video_utils import VideoClips
  7. from .vision import VisionDataset
  8. class UCF101(VisionDataset):
  9. """
  10. `UCF101 <https://www.crcv.ucf.edu/data/UCF101.php>`_ dataset.
  11. UCF101 is an action recognition video dataset.
  12. This dataset consider every video as a collection of video clips of fixed size, specified
  13. by ``frames_per_clip``, where the step in frames between each clip is given by
  14. ``step_between_clips``. The dataset itself can be downloaded from the dataset website;
  15. annotations that ``annotation_path`` should be pointing to can be downloaded from `here
  16. <https://www.crcv.ucf.edu/data/UCF101/UCF101TrainTestSplits-RecognitionTask.zip>`_.
  17. To give an example, for 2 videos with 10 and 15 frames respectively, if ``frames_per_clip=5``
  18. and ``step_between_clips=5``, the dataset size will be (2 + 3) = 5, where the first two
  19. elements will come from video 1, and the next three elements from video 2.
  20. Note that we drop clips which do not have exactly ``frames_per_clip`` elements, so not all
  21. frames in a video might be present.
  22. Internally, it uses a VideoClips object to handle clip creation.
  23. Args:
  24. root (str or ``pathlib.Path``): Root directory of the UCF101 Dataset.
  25. annotation_path (str): path to the folder containing the split files;
  26. see docstring above for download instructions of these files
  27. frames_per_clip (int): number of frames in a clip.
  28. step_between_clips (int, optional): number of frames between each clip.
  29. fold (int, optional): which fold to use. Should be between 1 and 3.
  30. train (bool, optional): if ``True``, creates a dataset from the train split,
  31. otherwise from the ``test`` split.
  32. transform (callable, optional): A function/transform that takes in a TxHxWxC video
  33. and returns a transformed version.
  34. output_format (str, optional): The format of the output video tensors (before transforms).
  35. Can be either "THWC" (default) or "TCHW".
  36. Returns:
  37. tuple: A 3-tuple with the following entries:
  38. - video (Tensor[T, H, W, C] or Tensor[T, C, H, W]): The `T` video frames
  39. - audio(Tensor[K, L]): the audio frames, where `K` is the number of channels
  40. and `L` is the number of points
  41. - label (int): class of the video clip
  42. """
  43. def __init__(
  44. self,
  45. root: Union[str, Path],
  46. annotation_path: str,
  47. frames_per_clip: int,
  48. step_between_clips: int = 1,
  49. frame_rate: Optional[int] = None,
  50. fold: int = 1,
  51. train: bool = True,
  52. transform: Optional[Callable] = None,
  53. _precomputed_metadata: Optional[dict[str, Any]] = None,
  54. num_workers: int = 1,
  55. _video_width: int = 0,
  56. _video_height: int = 0,
  57. _video_min_dimension: int = 0,
  58. _audio_samples: int = 0,
  59. output_format: str = "THWC",
  60. ) -> None:
  61. super().__init__(root)
  62. if not 1 <= fold <= 3:
  63. raise ValueError(f"fold should be between 1 and 3, got {fold}")
  64. extensions = ("avi",)
  65. self.fold = fold
  66. self.train = train
  67. self.classes, class_to_idx = find_classes(self.root)
  68. self.samples = make_dataset(self.root, class_to_idx, extensions, is_valid_file=None)
  69. video_list = [x[0] for x in self.samples]
  70. video_clips = VideoClips(
  71. video_list,
  72. frames_per_clip,
  73. step_between_clips,
  74. frame_rate,
  75. _precomputed_metadata,
  76. num_workers=num_workers,
  77. _video_width=_video_width,
  78. _video_height=_video_height,
  79. _video_min_dimension=_video_min_dimension,
  80. _audio_samples=_audio_samples,
  81. output_format=output_format,
  82. )
  83. # we bookkeep the full version of video clips because we want to be able
  84. # to return the metadata of full version rather than the subset version of
  85. # video clips
  86. self.full_video_clips = video_clips
  87. self.indices = self._select_fold(video_list, annotation_path, fold, train)
  88. self.video_clips = video_clips.subset(self.indices)
  89. self.transform = transform
  90. @property
  91. def metadata(self) -> dict[str, Any]:
  92. return self.full_video_clips.metadata
  93. def _select_fold(self, video_list: list[str], annotation_path: str, fold: int, train: bool) -> list[int]:
  94. name = "train" if train else "test"
  95. name = f"{name}list{fold:02d}.txt"
  96. f = os.path.join(annotation_path, name)
  97. selected_files = set()
  98. with open(f) as fid:
  99. data = fid.readlines()
  100. data = [x.strip().split(" ")[0] for x in data]
  101. data = [os.path.join(self.root, *x.split("/")) for x in data]
  102. selected_files.update(data)
  103. indices = [i for i in range(len(video_list)) if video_list[i] in selected_files]
  104. return indices
  105. def __len__(self) -> int:
  106. return self.video_clips.num_clips()
  107. def __getitem__(self, idx: int) -> tuple[Tensor, Tensor, int]:
  108. video, audio, info, video_idx = self.video_clips.get_clip(idx)
  109. label = self.samples[self.indices[video_idx]][1]
  110. if self.transform is not None:
  111. video = self.transform(video)
  112. return video, audio, label