ucf101.py 5.3 KB

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