|
| 1 | +# Copyright 2024 Adobe. All rights reserved. |
| 2 | + |
| 3 | +#%% |
| 4 | +import glob |
| 5 | +import torch |
| 6 | +import torchvision |
| 7 | +import matplotlib.pyplot as plt |
| 8 | +from torch.utils.data import Dataset |
| 9 | +import numpy as np |
| 10 | + |
| 11 | + |
| 12 | +# %% |
| 13 | +class MomentsDataset(Dataset): |
| 14 | + def __init__(self, videos_folder, num_frames, samples_per_video, frame_size=512) -> None: |
| 15 | + super().__init__() |
| 16 | + |
| 17 | + self.videos_paths = glob.glob(f'{videos_folder}/*mp4') |
| 18 | + self.resize = torchvision.transforms.Resize(size=frame_size) |
| 19 | + self.center_crop = torchvision.transforms.CenterCrop(size=frame_size) |
| 20 | + self.num_samples_per_video = samples_per_video |
| 21 | + self.num_frames = num_frames |
| 22 | + |
| 23 | + def __len__(self): |
| 24 | + return len(self.videos_paths) * self.num_samples_per_video |
| 25 | + |
| 26 | + def __getitem__(self, idx): |
| 27 | + video_idx = idx // self.num_samples_per_video |
| 28 | + video_path = self.videos_paths[video_idx] |
| 29 | + |
| 30 | + try: |
| 31 | + start_idx = np.random.randint(0, 20) |
| 32 | + |
| 33 | + unsampled_video_frames, audio_frames, info = torchvision.io.read_video(video_path,output_format="TCHW") |
| 34 | + sampled_indices = torch.tensor(np.linspace(start_idx, len(unsampled_video_frames)-1, self.num_frames).astype(int)) |
| 35 | + sampled_frames = unsampled_video_frames[sampled_indices] |
| 36 | + processed_frames = [] |
| 37 | + |
| 38 | + for frame in sampled_frames: |
| 39 | + resized_cropped_frame = self.center_crop(self.resize(frame)) |
| 40 | + processed_frames.append(resized_cropped_frame) |
| 41 | + frames = torch.stack(processed_frames, dim=0) |
| 42 | + frames = frames.float() / 255.0 |
| 43 | + except Exception as e: |
| 44 | + print('oops', e) |
| 45 | + rand_idx = np.random.randint(0, len(self)) |
| 46 | + return self.__getitem__(rand_idx) |
| 47 | + |
| 48 | + out_dict = {'frames': frames, |
| 49 | + 'caption': 'none', |
| 50 | + 'keywords': 'none'} |
| 51 | + |
| 52 | + return out_dict |
| 53 | + |
| 54 | + |
0 commit comments