Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
120 lines (96 loc) · 4.13 KB
/
Copy pathutils.py
File metadata and controls
120 lines (96 loc) · 4.13 KB
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
import os
import cv2
import numpy as np
import torch
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from tqdm import tqdm
class VideoDataset(Dataset):
def __init__(self, root_dir, sequence_length=16, resolution=128, transform=None, train=True):
"""
Args:
root_dir (string): Directory with all the videos.
sequence_length (int): Number of frames to extract from each video.
resolution (int): Target resolution for frames.
transform (callable, optional): Optional transform to be applied on a sample.
train (bool): If True, uses training split, otherwise validation split.
"""
self.root_dir = root_dir
self.sequence_length = sequence_length
self.resolution = resolution
self.transform = transform
self.train = train
# Get all video file paths
self.video_paths = []
for file in os.listdir(root_dir):
if file.endswith(".avi"):
self.video_paths.append(os.path.join(root_dir, file))
# Split into train and validation
self.video_paths.sort() # Ensure deterministic splits
split_idx = int(len(self.video_paths) * 0.9)
if train:
self.video_paths = self.video_paths[:split_idx]
else:
self.video_paths = self.video_paths[split_idx:]
def __len__(self):
return len(self.video_paths)
def __getitem__(self, idx):
video_path = self.video_paths[idx]
# Load video
cap = cv2.VideoCapture(video_path)
frames = []
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# If there are fewer frames than requested, we'll loop the video
if frame_count < self.sequence_length:
# Calculate how many times to loop
num_loops = self.sequence_length // frame_count + 1
for _ in range(num_loops):
cap.set(cv2.CAP_PROP_POS_FRAMES, 0) # Reset to start
for _ in range(frame_count):
ret, frame = cap.read()
if ret:
frames.append(frame)
if len(frames) >= self.sequence_length:
break
if len(frames) >= self.sequence_length:
break
else:
# If we have enough frames, evenly sample the requested number
step = frame_count / self.sequence_length
for i in range(self.sequence_length):
cap.set(cv2.CAP_PROP_POS_FRAMES, int(i * step))
ret, frame = cap.read()
if ret:
frames.append(frame)
cap.release()
# Ensure we got exactly the number of frames we want
frames = frames[:self.sequence_length]
# Process frames
processed_frames = []
for frame in frames:
# Resize to target resolution
frame = cv2.resize(frame, (self.resolution, self.resolution))
# Convert BGR to RGB
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Add to processed frames
processed_frames.append(frame)
# Convert to numpy array
video_np = np.stack(processed_frames)
# Convert from (T, H, W, C) to (C, T, H, W)
video_np = video_np.transpose(3, 0, 1, 2)
# Convert to torch tensor
video_tensor = torch.FloatTensor(video_np)
# Normalize to [-1, 1]
video_tensor = video_tensor / 127.5 - 1.0
# Apply any additional transforms
if self.transform:
video_tensor = self.transform(video_tensor)
return video_tensor
def center_crop_tensor(tensor, target_size):
"""Center crops a 5D tensor (B, C, T, H, W)."""
_, _, _, h, w = tensor.shape
th, tw = target_size, target_size
i = int(round((h - th) / 2.))
j = int(round((w - tw) / 2.))
return tensor[:, :, :, i:i+th, j:j+tw]