data.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. import copy
  2. import functools
  3. import json
  4. import os
  5. import pickle
  6. from glob import glob
  7. from typing import Tuple, List
  8. import torch
  9. import torch.utils.data as data
  10. from PIL import Image
  11. class AV(data.Dataset):
  12. def __init__(self, path: str):
  13. self.path = path
  14. self.data = []
  15. def __len__(self):
  16. return len(self.data)
  17. def __getitem__(self, idx: int) -> Tuple[torch.Tensor, torch.Tensor, int]:
  18. return self.data[idx]
  19. class AudioVideo(AV):
  20. def __init__(self, path: str):
  21. # output format:
  22. # return (
  23. # torch.rand((1, 96, 64)),
  24. # torch.rand((3, 224, 224)),
  25. # np.random.choice([0, 1])
  26. # )
  27. super().__init__(path)
  28. for file_path in glob(f'{path}/*.pkl'):
  29. audios, images, label = pickle.load(open(file_path, 'rb'))
  30. self.data += [(audios[i], images[i], label) for i in range(len(audios))]
  31. class AudioVideo3D(AV):
  32. def __init__(self, path: str):
  33. # output format:
  34. # return (
  35. # torch.rand((1, 96, 64)),
  36. # torch.rand((3, 16, 224, 224)),
  37. # np.random.choice([0, 1])
  38. # )
  39. super().__init__(path)
  40. frames = 16
  41. for file_path in glob(f'{path}/*.pkl'):
  42. audios, images, label = pickle.load(open(file_path, 'rb'))
  43. images_temporal = self._process_temporal_tensor(images, frames)
  44. self.data += [(audios[i], images_temporal[i], label) for i in range(len(audios))]
  45. @staticmethod
  46. def _process_temporal_tensor(images: List[torch.Tensor],
  47. frames: int) -> List[torch.Tensor]:
  48. out = []
  49. for i in range(len(images)):
  50. e = torch.zeros((frames, 3, 224, 224))
  51. e[-1] = images[0]
  52. for j in range(min(i, frames)):
  53. e[-1 - j] = images[j]
  54. # try:
  55. # e[-1 - j] = images[j]
  56. # except:
  57. # raise ValueError(f"trying to get {i} from images with len = {len(images)}")
  58. ee = e.permute((1, 0, 2, 3))
  59. out.append(ee)
  60. return out
  61. def pil_loader(path):
  62. # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
  63. with open(path, 'rb') as f:
  64. with Image.open(f) as img:
  65. return img.convert('RGB')
  66. def accimage_loader(path):
  67. # try:
  68. # return accimage.Image(path)
  69. # except IOError:
  70. # # Potentially a decoding problem, fall back to PIL.Image
  71. # return pil_loader(path)
  72. return pil_loader(path)
  73. def get_default_image_loader():
  74. from torchvision import get_image_backend
  75. if get_image_backend() == 'accimage':
  76. return accimage_loader
  77. else:
  78. return pil_loader
  79. def video_loader(video_dir_path, frame_indices, image_loader):
  80. video = []
  81. for i in frame_indices:
  82. image_path = os.path.join(video_dir_path, 'image_{:05d}.jpg'.format(i))
  83. if os.path.exists(image_path):
  84. video.append(image_loader(image_path))
  85. else:
  86. return video
  87. return video
  88. def get_default_video_loader():
  89. image_loader = get_default_image_loader()
  90. return functools.partial(video_loader, image_loader=image_loader)
  91. def load_annotation_data(data_file_path):
  92. with open(data_file_path, 'r') as data_file:
  93. return json.load(data_file)
  94. def get_class_labels(data):
  95. class_labels_map = {}
  96. index = 0
  97. for class_label in data['labels']:
  98. class_labels_map[class_label] = index
  99. index += 1
  100. return class_labels_map
  101. def get_video_names_and_annotations(data, subset):
  102. video_names = []
  103. annotations = []
  104. for key, value in data['database'].items():
  105. this_subset = value['subset']
  106. if this_subset == subset:
  107. if subset == 'testing':
  108. video_names.append('test/{}'.format(key))
  109. else:
  110. label = value['annotations']['label']
  111. video_names.append('{}/{}'.format(label, key))
  112. annotations.append(value['annotations'])
  113. return video_names, annotations
  114. def make_dataset(video_path, sample_duration):
  115. dataset = []
  116. n_frames = len(os.listdir(video_path))
  117. begin_t = 1
  118. end_t = n_frames
  119. sample = {
  120. 'video': video_path,
  121. 'segment': [begin_t, end_t],
  122. 'n_frames': n_frames,
  123. }
  124. step = sample_duration
  125. for i in range(1, (n_frames - sample_duration + 1), step):
  126. sample_i = copy.deepcopy(sample)
  127. sample_i['frame_indices'] = list(range(i, i + sample_duration))
  128. sample_i['segment'] = torch.IntTensor([i, i + sample_duration - 1])
  129. dataset.append(sample_i)
  130. return dataset
  131. class Video(data.Dataset):
  132. def __init__(self, video_path,
  133. spatial_transform=None, temporal_transform=None,
  134. sample_duration=16, get_loader=get_default_video_loader):
  135. self.data = make_dataset(video_path, sample_duration)
  136. self.spatial_transform = spatial_transform
  137. self.temporal_transform = temporal_transform
  138. self.loader = get_loader()
  139. def __getitem__(self, index):
  140. """
  141. Args:
  142. index (int): Index
  143. Returns:
  144. tuple: (image, target) where target is class_index of the target class.
  145. """
  146. path = self.data[index]['video']
  147. frame_indices = self.data[index]['frame_indices']
  148. if self.temporal_transform is not None:
  149. frame_indices = self.temporal_transform(frame_indices)
  150. clip = self.loader(path, frame_indices)
  151. if self.spatial_transform is not None:
  152. clip = [self.spatial_transform(img) for img in clip]
  153. clip = torch.stack(clip, 0).permute(1, 0, 2, 3)
  154. target = self.data[index]['segment']
  155. return clip, target
  156. def __len__(self):
  157. return len(self.data)