"scripts/server/start_server.sh" did not exist on "cbf7820ffa15d8c6e054b1559f23b5328b6c4515"
hmdb51.py 5.77 KB
Newer Older
1
2
import glob
import os
3
from typing import Any, Callable, Dict, List, Optional, Tuple
4

5
from torch import Tensor
6

7
from .folder import find_classes, make_dataset
8
from .video_utils import VideoClips
9
10
11
12
from .vision import VisionDataset


class HMDB51(VisionDataset):
13
    """
14
    `HMDB51 <https://serre-lab.clps.brown.edu/resource/hmdb-a-large-human-motion-database/>`_
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    dataset.

    HMDB51 is an action recognition video dataset.
    This dataset consider every video as a collection of video clips of fixed size, specified
    by ``frames_per_clip``, where the step in frames between each clip is given by
    ``step_between_clips``.

    To give an example, for 2 videos with 10 and 15 frames respectively, if ``frames_per_clip=5``
    and ``step_between_clips=5``, the dataset size will be (2 + 3) = 5, where the first two
    elements will come from video 1, and the next three elements from video 2.
    Note that we drop clips which do not have exactly ``frames_per_clip`` elements, so not all
    frames in a video might be present.

    Internally, it uses a VideoClips object to handle clip creation.

    Args:
        root (string): Root directory of the HMDB51 Dataset.
32
33
34
35
36
        annotation_path (str): Path to the folder containing the split files.
        frames_per_clip (int): Number of frames in a clip.
        step_between_clips (int): Number of frames between each clip.
        fold (int, optional): Which fold to use. Should be between 1 and 3.
        train (bool, optional): If ``True``, creates a dataset from the train split,
37
            otherwise from the ``test`` split.
38
        transform (callable, optional): A function/transform that takes in a TxHxWxC video
39
            and returns a transformed version.
40
41
        output_format (str, optional): The format of the output video tensors (before transforms).
            Can be either "THWC" (default) or "TCHW".
42
43

    Returns:
44
45
        tuple: A 3-tuple with the following entries:

46
            - video (Tensor[T, H, W, C] or Tensor[T, C, H, W]): The `T` video frames
47
48
49
            - audio(Tensor[K, L]): the audio frames, where `K` is the number of channels
              and `L` is the number of points
            - label (int): class of the video clip
50
    """
51

52
    data_url = "https://serre-lab.clps.brown.edu/wp-content/uploads/2013/10/hmdb51_org.rar"
53
    splits = {
54
        "url": "https://serre-lab.clps.brown.edu/wp-content/uploads/2013/10/test_train_splits.rar",
55
        "md5": "15e67781e70dcfbdce2d7dbb9b3344b5",
56
    }
57
58
    TRAIN_TAG = 1
    TEST_TAG = 2
59

60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
    def __init__(
        self,
        root: str,
        annotation_path: str,
        frames_per_clip: int,
        step_between_clips: int = 1,
        frame_rate: Optional[int] = None,
        fold: int = 1,
        train: bool = True,
        transform: Optional[Callable] = None,
        _precomputed_metadata: Optional[Dict[str, Any]] = None,
        num_workers: int = 1,
        _video_width: int = 0,
        _video_height: int = 0,
        _video_min_dimension: int = 0,
        _audio_samples: int = 0,
76
        output_format: str = "THWC",
77
    ) -> None:
78
        super().__init__(root)
79
        if fold not in (1, 2, 3):
80
            raise ValueError(f"fold should be between 1 and 3, got {fold}")
81

82
        extensions = ("avi",)
83
        self.classes, class_to_idx = find_classes(self.root)
84
85
86
87
88
        self.samples = make_dataset(
            self.root,
            class_to_idx,
            extensions,
        )
89

90
        video_paths = [path for (path, _) in self.samples]
91
        video_clips = VideoClips(
92
            video_paths,
93
94
95
96
            frames_per_clip,
            step_between_clips,
            frame_rate,
            _precomputed_metadata,
97
98
99
100
101
            num_workers=num_workers,
            _video_width=_video_width,
            _video_height=_video_height,
            _video_min_dimension=_video_min_dimension,
            _audio_samples=_audio_samples,
102
            output_format=output_format,
103
        )
104
        # we bookkeep the full version of video clips because we want to be able
105
        # to return the metadata of full version rather than the subset version of
106
107
        # video clips
        self.full_video_clips = video_clips
108
109
110
        self.fold = fold
        self.train = train
        self.indices = self._select_fold(video_paths, annotation_path, fold, train)
111
        self.video_clips = video_clips.subset(self.indices)
112
        self.transform = transform
113

114
    @property
115
    def metadata(self) -> Dict[str, Any]:
116
        return self.full_video_clips.metadata
117

118
    def _select_fold(self, video_list: List[str], annotations_dir: str, fold: int, train: bool) -> List[int]:
119
        target_tag = self.TRAIN_TAG if train else self.TEST_TAG
120
        split_pattern_name = f"*test_split{fold}.txt"
121
122
        split_pattern_path = os.path.join(annotations_dir, split_pattern_name)
        annotation_paths = glob.glob(split_pattern_path)
123
        selected_files = set()
124
125
126
127
128
129
130
        for filepath in annotation_paths:
            with open(filepath) as fid:
                lines = fid.readlines()
            for line in lines:
                video_filename, tag_string = line.split()
                tag = int(tag_string)
                if tag == target_tag:
131
                    selected_files.add(video_filename)
132
133
134
135
136
137

        indices = []
        for video_index, video_path in enumerate(video_list):
            if os.path.basename(video_path) in selected_files:
                indices.append(video_index)

138
139
        return indices

140
    def __len__(self) -> int:
141
142
        return self.video_clips.num_clips()

143
    def __getitem__(self, idx: int) -> Tuple[Tensor, Tensor, int]:
144
145
146
        video, audio, _, video_idx = self.video_clips.get_clip(idx)
        sample_index = self.indices[video_idx]
        _, class_index = self.samples[sample_index]
147

148
149
150
        if self.transform is not None:
            video = self.transform(video)

151
        return video, audio, class_index