yfyangd commited on
Commit
e16e2f7
·
1 Parent(s): 83c38a3

Upload video_dataset.py

Browse files
Files changed (1) hide show
  1. BLIP/data/video_dataset.py +110 -0
BLIP/data/video_dataset.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.utils.data import Dataset
2
+ from torchvision.datasets.utils import download_url
3
+
4
+ from PIL import Image
5
+ import torch
6
+ import numpy as np
7
+ import random
8
+ import decord
9
+ from decord import VideoReader
10
+ import json
11
+ import os
12
+ from data.utils import pre_caption
13
+
14
+ decord.bridge.set_bridge("torch")
15
+
16
+ class ImageNorm(object):
17
+ """Apply Normalization to Image Pixels on GPU
18
+ """
19
+ def __init__(self, mean, std):
20
+ self.mean = torch.tensor(mean).view(1, 3, 1, 1)
21
+ self.std = torch.tensor(std).view(1, 3, 1, 1)
22
+
23
+ def __call__(self, img):
24
+
25
+ if torch.max(img) > 1 and self.mean.max() <= 1:
26
+ img.div_(255.)
27
+ return img.sub_(self.mean).div_(self.std)
28
+
29
+ def load_jsonl(filename):
30
+ with open(filename, "r") as f:
31
+ return [json.loads(l.strip("\n")) for l in f.readlines()]
32
+
33
+
34
+ class VideoDataset(Dataset):
35
+
36
+ def __init__(self, video_root, ann_root, num_frm=4, frm_sampling_strategy="rand", max_img_size=384, video_fmt='.mp4'):
37
+ '''
38
+ image_root (string): Root directory of video
39
+ ann_root (string): directory to store the annotation file
40
+ '''
41
+ url = 'https://storage.googleapis.com/sfr-vision-language-research/datasets/msrvtt_test.jsonl'
42
+ filename = 'msrvtt_test.jsonl'
43
+
44
+ download_url(url,ann_root)
45
+ self.annotation = load_jsonl(os.path.join(ann_root,filename))
46
+
47
+ self.num_frm = num_frm
48
+ self.frm_sampling_strategy = frm_sampling_strategy
49
+ self.max_img_size = max_img_size
50
+ self.video_root = video_root
51
+ self.video_fmt = video_fmt
52
+ self.img_norm = ImageNorm(mean=(0.48145466, 0.4578275, 0.40821073), std=(0.26862954, 0.26130258, 0.27577711))
53
+
54
+ self.text = [pre_caption(ann['caption'],40) for ann in self.annotation]
55
+ self.txt2video = [i for i in range(len(self.annotation))]
56
+ self.video2txt = self.txt2video
57
+
58
+
59
+ def __len__(self):
60
+ return len(self.annotation)
61
+
62
+ def __getitem__(self, index):
63
+
64
+ ann = self.annotation[index]
65
+
66
+ video_path = os.path.join(self.video_root, ann['clip_name'] + self.video_fmt)
67
+
68
+ vid_frm_array = self._load_video_from_path_decord(video_path, height=self.max_img_size, width=self.max_img_size)
69
+
70
+ video = self.img_norm(vid_frm_array.float())
71
+
72
+ return video, ann['clip_name']
73
+
74
+
75
+
76
+ def _load_video_from_path_decord(self, video_path, height=None, width=None, start_time=None, end_time=None, fps=-1):
77
+ try:
78
+ if not height or not width:
79
+ vr = VideoReader(video_path)
80
+ else:
81
+ vr = VideoReader(video_path, width=width, height=height)
82
+
83
+ vlen = len(vr)
84
+
85
+ if start_time or end_time:
86
+ assert fps > 0, 'must provide video fps if specifying start and end time.'
87
+
88
+ start_idx = min(int(start_time * fps), vlen)
89
+ end_idx = min(int(end_time * fps), vlen)
90
+ else:
91
+ start_idx, end_idx = 0, vlen
92
+
93
+ if self.frm_sampling_strategy == 'uniform':
94
+ frame_indices = np.arange(start_idx, end_idx, vlen / self.num_frm, dtype=int)
95
+ elif self.frm_sampling_strategy == 'rand':
96
+ frame_indices = sorted(random.sample(range(vlen), self.num_frm))
97
+ elif self.frm_sampling_strategy == 'headtail':
98
+ frame_indices_head = sorted(random.sample(range(vlen // 2), self.num_frm // 2))
99
+ frame_indices_tail = sorted(random.sample(range(vlen // 2, vlen), self.num_frm // 2))
100
+ frame_indices = frame_indices_head + frame_indices_tail
101
+ else:
102
+ raise NotImplementedError('Invalid sampling strategy {} '.format(self.frm_sampling_strategy))
103
+
104
+ raw_sample_frms = vr.get_batch(frame_indices)
105
+ except Exception as e:
106
+ return None
107
+
108
+ raw_sample_frms = raw_sample_frms.permute(0, 3, 1, 2)
109
+
110
+ return raw_sample_frms