-
Notifications
You must be signed in to change notification settings - Fork 8
/
charades_dataset.py
168 lines (127 loc) · 4.86 KB
/
charades_dataset.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import torch
import torch.utils.data as data_utl
from torch.utils.data.dataloader import default_collate
import numpy as np
import json
import csv
import h5py
import random
import os
import os.path
import cv2
def video_to_tensor(pic):
"""Convert a ``numpy.ndarray`` to tensor.
Converts a numpy.ndarray (T x H x W x C)
to a torch.FloatTensor of shape (C x T x H x W)
Args:
pic (numpy.ndarray): Video to be converted to tensor.
Returns:
Tensor: Converted video.
"""
return torch.from_numpy(pic.transpose([3,0,1,2]))
def load_rgb_frames(image_dir, vid, start, num):
frames = []
for i in range(start, start+num):
img = cv2.imread(os.path.join(image_dir, vid, vid+'-'+str(i).zfill(6)+'.jpg'))[:, :, [2, 1, 0]]
w,h,c = img.shape
if w < 226 or h < 226:
d = 226.-min(w,h)
sc = 1+d/min(w,h)
img = cv2.resize(img,dsize=(0,0),fx=sc,fy=sc)
img = (img/255.)*2 - 1
frames.append(img)
return np.asarray(frames, dtype=np.float32)
def load_flow_frames(image_dir, vid, start, num):
frames = []
for i in range(start, start+num):
imgx = cv2.imread(os.path.join(image_dir, vid, vid+'-'+str(i).zfill(6)+'x.jpg'), cv2.IMREAD_GRAYSCALE)
imgy = cv2.imread(os.path.join(image_dir, vid, vid+'-'+str(i).zfill(6)+'y.jpg'), cv2.IMREAD_GRAYSCALE)
w,h = imgx.shape
if w < 224 or h < 224:
d = 224.-min(w,h)
sc = 1+d/min(w,h)
imgx = cv2.resize(imgx,dsize=(0,0),fx=sc,fy=sc)
imgy = cv2.resize(imgy,dsize=(0,0),fx=sc,fy=sc)
imgx = (imgx/255.)*2 - 1
imgy = (imgy/255.)*2 - 1
img = np.asarray([imgx, imgy]).transpose([1,2,0])
frames.append(img)
return np.asarray(frames, dtype=np.float32)
def make_dataset(split_file, split, root, mode, snippets, num_classes=157):
count_items = 0
dataset = []
with open(split_file, 'r') as f:
data = json.load(f)
for vid in data.keys():
if data[vid]['subset'] != split:
continue
if not os.path.exists(os.path.join(root, vid)):
continue
num_frames = len(os.listdir(os.path.join(root, vid)))
if mode == "flow":
num_frames = num_frames//2
fps = num_frames/data[vid]['duration']
for j in range(0, num_frames, snippets):
if j+snippets>num_frames:
continue
label = np.zeros((num_classes, snippets), np.float32)
for ann in data[vid]['actions']:
for fr in range(j+1,j+snippets+1,1):
if fr/fps >= ann[1] and fr/fps <= ann[2]:
label[ann[0], (fr-1)%snippets] = 1
dataset.append((vid, j+1, label))
count_items += 1
print("Make dataset {}: {} examples".format(split, count_items*snippets))
return dataset
class Charades(data_utl.Dataset):
def __init__(self, split_file, split, root, mode, snippets, transforms=None):
self.data = make_dataset(split_file, split, root, mode, snippets)
self.split_file = split_file
self.transforms = transforms
self.mode = mode
self.root = root
self.snippets = snippets
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (image, target) where target is class_index of the target class.
"""
vid, start, label = self.data[index]
#start_f = random.randint(1,nf-65)
if self.mode == 'rgb':
imgs = load_rgb_frames(self.root, vid, start, self.snippets)
else:
imgs = load_flow_frames(self.root, vid, start, self.snippets)
#label = label[:, :] #start_f:start_f+64]
imgs = self.transforms(imgs)
return video_to_tensor(imgs), torch.from_numpy(label)
def __len__(self):
return len(self.data)
class Charades_eval(data_utl.Dataset):
def __init__(self, split_file, split, root, mode, snippets, transforms=None):
self.data = make_dataset(split_file, split, root, mode, snippets)
self.split_file = split_file
self.transforms = transforms
self.mode = mode
self.root = root
self.snippets = snippets
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (image, target) where target is class_index of the target class.
"""
vid, start, label = self.data[index]
#start_f = random.randint(1,nf-65)
if self.mode == 'rgb':
imgs = load_rgb_frames(self.root, vid, start, self.snippets)
else:
imgs = load_flow_frames(self.root, vid, start, self.snippets)
#label = label[:, :] #start_f:start_f+64]
imgs = self.transforms(imgs)
return vid, start, video_to_tensor(imgs), torch.from_numpy(label)
def __len__(self):
return len(self.data)