Spaces:
Sleeping
Sleeping
Upload 9 files
Browse files- data_processing/.DS_Store +0 -0
- data_processing/__init__.py +2 -0
- data_processing/split_train_test.py +168 -0
- extractor/.DS_Store +0 -0
- extractor/__init__.py +2 -0
- extractor/extract_rf_feats.py +317 -0
- extractor/extract_rf_subsampling.py +301 -0
- extractor/extract_slowfast_clip.py +110 -0
- extractor/extract_swint_clip.py +40 -0
data_processing/.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
data_processing/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# __init__.py
|
| 2 |
+
# print("Data processing")
|
data_processing/split_train_test.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
import os
|
| 4 |
+
import torch
|
| 5 |
+
from sklearn.model_selection import train_test_split
|
| 6 |
+
import logging
|
| 7 |
+
|
| 8 |
+
# cross_dataset
|
| 9 |
+
def process_cross_dataset(train_data_name, test_data_name, metadata_path, feature_path, network_name):
|
| 10 |
+
metadata_name1 = f"{train_data_name.replace('_all', '').upper()}_metadata.csv"
|
| 11 |
+
metadata_name2 = f"{test_data_name.replace('_all', '').upper()}_metadata.csv"
|
| 12 |
+
# load CSV data
|
| 13 |
+
train_df = pd.read_csv(f'{metadata_path}/{metadata_name1}')
|
| 14 |
+
test_df = pd.read_csv(f'{metadata_path}/{metadata_name2}')
|
| 15 |
+
|
| 16 |
+
# split videonames into train and test sets
|
| 17 |
+
train_vids = train_df.iloc[:, 0]
|
| 18 |
+
test_vids = test_df.iloc[:, 0]
|
| 19 |
+
|
| 20 |
+
# scores (1-100) map to 1-5
|
| 21 |
+
train_scores = train_df['mos'].tolist()
|
| 22 |
+
test_scores = test_df['mos'].tolist()
|
| 23 |
+
if train_data_name == 'konvid_1k_all' or train_data_name == 'youtube_ugc_all':
|
| 24 |
+
train_mos_list = ((np.array(train_scores) - 1) * (99/4) + 1.0).tolist()
|
| 25 |
+
else:
|
| 26 |
+
train_mos_list = train_scores
|
| 27 |
+
if test_data_name == 'konvid_1k_all' or test_data_name == 'youtube_ugc_all':
|
| 28 |
+
test_mos_list = ((np.array(test_scores) - 1) * (99/4) + 1.0).tolist()
|
| 29 |
+
else:
|
| 30 |
+
test_mos_list = test_scores
|
| 31 |
+
|
| 32 |
+
# reorder columns
|
| 33 |
+
sorted_train_df = pd.DataFrame({'vid': train_df['vid'], 'framerate': train_df['framerate'], 'MOS': train_mos_list, 'MOS_raw': train_df['mos']})
|
| 34 |
+
sorted_test_df = pd.DataFrame({'vid': test_df['vid'], 'framerate': test_df['framerate'], 'MOS': test_mos_list, 'MOS_raw': test_df['mos']})
|
| 35 |
+
|
| 36 |
+
# use indices from the train and test DataFrames to split features
|
| 37 |
+
train_features = torch.load(f"{feature_path}/{network_name}_{train_data_name.replace('_all', '')}_features.pt")
|
| 38 |
+
test_features = torch.load(f"{feature_path}/{network_name}_{test_data_name.replace('_all', '')}_features.pt")
|
| 39 |
+
|
| 40 |
+
# save the files
|
| 41 |
+
sorted_train_df.to_csv(f'{metadata_path}mos_files/{train_data_name}_MOS_train.csv', index=False)
|
| 42 |
+
sorted_test_df.to_csv(f'{metadata_path}mos_files/{test_data_name}_MOS_test.csv', index=False)
|
| 43 |
+
os.makedirs(os.path.join(feature_path, "split_train_test"), exist_ok=True)
|
| 44 |
+
torch.save(train_features, f'{feature_path}/split_train_test/{network_name}_{train_data_name}_cross_train_features.pt')
|
| 45 |
+
torch.save(test_features, f'{feature_path}/split_train_test/{network_name}_{test_data_name}_cross_test_features.pt')
|
| 46 |
+
|
| 47 |
+
return train_features, test_features, test_vids
|
| 48 |
+
|
| 49 |
+
#NR: original
|
| 50 |
+
def process_lsvq(train_data_name, test_data_name, metadata_path, feature_path, network_name):
|
| 51 |
+
train_df = pd.read_csv(f'{metadata_path}/{train_data_name.upper()}_metadata.csv')
|
| 52 |
+
test_df = pd.read_csv(f'{metadata_path}/{test_data_name.upper()}_metadata.csv')
|
| 53 |
+
|
| 54 |
+
# grayscale videos, do not consider them for fair comparison
|
| 55 |
+
# grey_df_train = pd.read_csv(f'{metadata_path}/greyscale_report/{train_data_name.upper()}_greyscale_metadata.csv')
|
| 56 |
+
# grey_df_test = pd.read_csv(f'{metadata_path}/greyscale_report/{test_data_name.upper()}_greyscale_metadata.csv')
|
| 57 |
+
# grey_indices_train = grey_df_train.iloc[:, 0].tolist()
|
| 58 |
+
# grey_indices_test = grey_df_test.iloc[:, 0].tolist()
|
| 59 |
+
# train_df = train_df.drop(index=grey_indices_train).reset_index(drop=True)
|
| 60 |
+
# test_df = test_df.drop(index=grey_indices_test).reset_index(drop=True)
|
| 61 |
+
test_vids = test_df['vid']
|
| 62 |
+
|
| 63 |
+
# mos scores
|
| 64 |
+
train_scores = train_df['mos'].tolist()
|
| 65 |
+
test_scores = test_df['mos'].tolist()
|
| 66 |
+
train_mos_list = train_scores
|
| 67 |
+
test_mos_list = test_scores
|
| 68 |
+
|
| 69 |
+
# reorder columns
|
| 70 |
+
sorted_train_df = pd.DataFrame({'vid': train_df['vid'], 'framerate': train_df['framerate'], 'MOS': train_mos_list, 'MOS_raw': train_df['mos']})
|
| 71 |
+
sorted_test_df = pd.DataFrame({'vid': test_df['vid'], 'framerate': test_df['framerate'], 'MOS': test_mos_list, 'MOS_raw': test_df['mos']})
|
| 72 |
+
|
| 73 |
+
# use indices from the train and test DataFrames to split features
|
| 74 |
+
train_features = torch.load(f'{feature_path}/{network_name}_{train_data_name}_features.pt')
|
| 75 |
+
print(f"loaded {train_data_name}: dimensions are {train_features.shape}")
|
| 76 |
+
test_features = torch.load(f'{feature_path}/{network_name}_{test_data_name}_features.pt')
|
| 77 |
+
|
| 78 |
+
# grayscale videos
|
| 79 |
+
# train_mask = torch.ones(train_features.size(0), dtype=torch.bool, device=train_features.device)
|
| 80 |
+
# test_mask = torch.ones(test_features.size(0), dtype=torch.bool, device=test_features.device)
|
| 81 |
+
# train_mask[grey_indices_train] = False
|
| 82 |
+
# test_mask[grey_indices_test] = False
|
| 83 |
+
# train_features = train_features[train_mask]
|
| 84 |
+
# test_features = test_features[test_mask]
|
| 85 |
+
print(len(train_features))
|
| 86 |
+
print(len(test_features))
|
| 87 |
+
|
| 88 |
+
# save the files
|
| 89 |
+
sorted_train_df.to_csv(f'{metadata_path}mos_files/{train_data_name}_MOS_train.csv', index=False)
|
| 90 |
+
sorted_test_df.to_csv(f'{metadata_path}mos_files/{train_data_name}_MOS_test.csv', index=False)
|
| 91 |
+
os.makedirs(os.path.join(feature_path, "split_train_test"), exist_ok=True)
|
| 92 |
+
torch.save(train_features, f'{feature_path}/split_train_test/{network_name}_{train_data_name}_train_features.pt')
|
| 93 |
+
torch.save(test_features, f'{feature_path}/split_train_test/{network_name}_{test_data_name}_test_features.pt')
|
| 94 |
+
|
| 95 |
+
return train_features, test_features, test_vids
|
| 96 |
+
|
| 97 |
+
def process_other(data_name, test_size, random_state, metadata_path, feature_path, network_name):
|
| 98 |
+
metadata_name = f'{data_name.upper()}_metadata.csv'
|
| 99 |
+
# load CSV data
|
| 100 |
+
df = pd.read_csv(f'{metadata_path}/{metadata_name}')
|
| 101 |
+
|
| 102 |
+
# if data_name == 'youtube_ugc':
|
| 103 |
+
# # grayscale videos, do not consider them for fair comparison
|
| 104 |
+
# grey_df = pd.read_csv(f'{metadata_path}/greyscale_report/{data_name.upper()}_greyscale_metadata.csv')
|
| 105 |
+
# grey_indices = grey_df.iloc[:, 0].tolist()
|
| 106 |
+
# df = df.drop(index=grey_indices).reset_index(drop=True)
|
| 107 |
+
|
| 108 |
+
# get unique vids
|
| 109 |
+
unique_vids = df['vid'].unique()
|
| 110 |
+
|
| 111 |
+
# split videonames into train and test sets
|
| 112 |
+
train_vids, test_vids = train_test_split(unique_vids, test_size=test_size, random_state=random_state)
|
| 113 |
+
|
| 114 |
+
# split all_dfs into train and test based on vids
|
| 115 |
+
train_df = df[df['vid'].isin(train_vids)]
|
| 116 |
+
test_df = df[df['vid'].isin(test_vids)]
|
| 117 |
+
|
| 118 |
+
# mos scores
|
| 119 |
+
train_scores = train_df['mos'].tolist()
|
| 120 |
+
test_scores = test_df['mos'].tolist()
|
| 121 |
+
train_mos_list = train_scores
|
| 122 |
+
test_mos_list = test_scores
|
| 123 |
+
|
| 124 |
+
# reorder columns
|
| 125 |
+
sorted_train_df = pd.DataFrame({'vid': train_df['vid'], 'framerate': train_df['framerate'], 'MOS': train_mos_list, 'MOS_raw': train_df['mos']})
|
| 126 |
+
sorted_test_df = pd.DataFrame({'vid': test_df['vid'], 'framerate': test_df['framerate'], 'MOS': test_mos_list, 'MOS_raw': test_df['mos']})
|
| 127 |
+
|
| 128 |
+
# use indices from the train and test DataFrames to split features
|
| 129 |
+
features = torch.load(f'{feature_path}/{network_name}_{data_name}_features.pt')
|
| 130 |
+
# if data_name == 'youtube_ugc':
|
| 131 |
+
# # features = np.delete(features, grey_indices, axis=0)
|
| 132 |
+
# mask = torch.ones(features.size(0), dtype=torch.bool, device=features.device)
|
| 133 |
+
# mask[grey_indices] = False
|
| 134 |
+
# features = features[mask]
|
| 135 |
+
train_features = features[train_df.index]
|
| 136 |
+
test_features = features[test_df.index]
|
| 137 |
+
|
| 138 |
+
# save the files
|
| 139 |
+
sorted_train_df.to_csv(f'{metadata_path}mos_files/{data_name}_MOS_train.csv', index=False)
|
| 140 |
+
sorted_test_df.to_csv(f'{metadata_path}mos_files/{data_name}_MOS_test.csv', index=False)
|
| 141 |
+
os.makedirs(os.path.join(feature_path, "split_train_test"), exist_ok=True)
|
| 142 |
+
torch.save(train_features, f'{feature_path}/split_train_test/{network_name}_{data_name}_train_features.pt')
|
| 143 |
+
torch.save(test_features, f'{feature_path}/split_train_test/{network_name}_{data_name}_test_features.pt')
|
| 144 |
+
|
| 145 |
+
return train_features, test_features, test_vids
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
if __name__ == '__main__':
|
| 149 |
+
network_name = "slowfast"
|
| 150 |
+
data_name = "test"
|
| 151 |
+
metadata_path = '../../metadata/'
|
| 152 |
+
feature_path = '../../features/konvid_1k_test/slowfast/'
|
| 153 |
+
|
| 154 |
+
# train test split
|
| 155 |
+
test_size = 0.2
|
| 156 |
+
random_state = None
|
| 157 |
+
|
| 158 |
+
if data_name == 'lsvq_train':
|
| 159 |
+
test_data_name = 'lsvq_test'
|
| 160 |
+
process_lsvq(data_name, test_data_name, metadata_path, feature_path, network_name)
|
| 161 |
+
|
| 162 |
+
elif data_name == 'cross_dataset':
|
| 163 |
+
train_data_name = 'youtube_ugc_all'
|
| 164 |
+
test_data_name = 'cvd_2014_all'
|
| 165 |
+
_, _, test_vids = process_cross_dataset(train_data_name, test_data_name, metadata_path, feature_path, network_name)
|
| 166 |
+
|
| 167 |
+
else:
|
| 168 |
+
process_other(data_name, test_size, random_state, metadata_path, feature_path, network_name)
|
extractor/.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
extractor/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# __init__.py
|
| 2 |
+
# print("Initializing extractor")
|
extractor/extract_rf_feats.py
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import cv2
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import time
|
| 5 |
+
import torch
|
| 6 |
+
import matplotlib.pyplot as plt
|
| 7 |
+
import numpy as np
|
| 8 |
+
from torchvision import transforms
|
| 9 |
+
from PIL import Image
|
| 10 |
+
from torch.utils import data
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class VideoDataset_feature(data.Dataset):
|
| 14 |
+
def __init__(self, data_dir, filename_path, transform, resize, database, patch_size=16, target_size=224, top_n=196):
|
| 15 |
+
super(VideoDataset_feature, self).__init__()
|
| 16 |
+
if isinstance(filename_path, str):
|
| 17 |
+
dataInfo = pd.read_csv(filename_path)
|
| 18 |
+
elif isinstance(filename_path, pd.DataFrame):
|
| 19 |
+
dataInfo = filename_path
|
| 20 |
+
else:
|
| 21 |
+
raise ValueError("filename_path: CSV file or DataFrame")
|
| 22 |
+
self.video_names = dataInfo['vid'].tolist()
|
| 23 |
+
self.transform = transform
|
| 24 |
+
self.videos_dir = data_dir
|
| 25 |
+
self.resize = resize
|
| 26 |
+
self.database = database
|
| 27 |
+
self.patch_size = patch_size
|
| 28 |
+
self.target_size = target_size
|
| 29 |
+
self.top_n = top_n
|
| 30 |
+
self.length = len(self.video_names)
|
| 31 |
+
|
| 32 |
+
def __len__(self):
|
| 33 |
+
return self.length
|
| 34 |
+
|
| 35 |
+
def __getitem__(self, idx):
|
| 36 |
+
if self.database == 'konvid_1k' or self.database == 'test':
|
| 37 |
+
video_clip_min = 8
|
| 38 |
+
video_name = str(self.video_names[idx]) + '.mp4'
|
| 39 |
+
elif self.database == 'live_vqc':
|
| 40 |
+
video_clip_min = 10
|
| 41 |
+
video_name = str(self.video_names[idx]) + '.mp4'
|
| 42 |
+
elif self.database == 'cvd_2014':
|
| 43 |
+
video_clip_min = 12
|
| 44 |
+
video_name = str(self.video_names[idx]) + '.avi'
|
| 45 |
+
elif self.database == 'youtube_ugc':
|
| 46 |
+
video_clip_min = 20
|
| 47 |
+
video_name = str(self.video_names[idx]) + '.mkv'
|
| 48 |
+
elif self.database == 'youtube_ugc_h264':
|
| 49 |
+
video_clip_min = 20
|
| 50 |
+
video_name = str(self.video_names[idx]) + '.mp4'
|
| 51 |
+
elif self.database == 'lsvq_test_1080p' or self.database == 'lsvq_test' or self.database == 'lsvq_train':
|
| 52 |
+
video_clip_min = 8
|
| 53 |
+
video_name = str(self.video_names[idx]) + '.mp4'
|
| 54 |
+
|
| 55 |
+
filename = os.path.join(self.videos_dir, video_name)
|
| 56 |
+
|
| 57 |
+
video_capture = cv2.VideoCapture(filename)
|
| 58 |
+
video_capture.set(cv2.CAP_PROP_BUFFERSIZE, 3)
|
| 59 |
+
if not video_capture.isOpened():
|
| 60 |
+
raise RuntimeError(f"Failed to open video: {filename}")
|
| 61 |
+
|
| 62 |
+
video_channel = 3
|
| 63 |
+
video_length = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 64 |
+
video_frame_rate = int(round(video_capture.get(cv2.CAP_PROP_FPS)))
|
| 65 |
+
video_clip = int(video_length / video_frame_rate) if video_frame_rate != 0 else 10
|
| 66 |
+
video_length_clip = 32
|
| 67 |
+
# print(video_length)
|
| 68 |
+
# print(video_frame_rate)
|
| 69 |
+
# print(video_clip)
|
| 70 |
+
|
| 71 |
+
all_frame_tensor = torch.zeros((video_length, video_channel, self.resize, self.resize), dtype=torch.float32)
|
| 72 |
+
all_residual_frag_tensor = torch.zeros((video_length - 1, video_channel, self.resize, self.resize), dtype=torch.float32)
|
| 73 |
+
all_frame_frag_tensor = torch.zeros((video_length - 1, video_channel, self.resize, self.resize), dtype=torch.float32)
|
| 74 |
+
|
| 75 |
+
video_read_index = 0
|
| 76 |
+
prev_frame = None
|
| 77 |
+
for i in range(video_length):
|
| 78 |
+
has_frames, frame = video_capture.read()
|
| 79 |
+
if has_frames:
|
| 80 |
+
curr_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 81 |
+
# save_img(curr_frame, fig_path='original', img_title=f'original_{i}')
|
| 82 |
+
|
| 83 |
+
# frame features
|
| 84 |
+
curr_frame_tensor = self.transform(Image.fromarray(curr_frame))
|
| 85 |
+
all_frame_tensor[video_read_index] = curr_frame_tensor
|
| 86 |
+
|
| 87 |
+
# frame frag features
|
| 88 |
+
if prev_frame is not None:
|
| 89 |
+
residual = cv2.absdiff(curr_frame, prev_frame)
|
| 90 |
+
# save_img(residual, fig_path='residual', img_title=f'residual_{i}')
|
| 91 |
+
|
| 92 |
+
diff = self.get_patch_diff(residual)
|
| 93 |
+
# frame residual fragment
|
| 94 |
+
imp_patches, positions = self.extract_important_patches(residual, diff)
|
| 95 |
+
imp_patches_pil = Image.fromarray(imp_patches.astype('uint8'))
|
| 96 |
+
# save_img(imp_patches_pil, fig_path='residual_frag', img_title=f'residual_frag_{i}')
|
| 97 |
+
|
| 98 |
+
residual_frag_tensor = self.transform(imp_patches_pil)
|
| 99 |
+
all_residual_frag_tensor[video_read_index] = residual_frag_tensor
|
| 100 |
+
|
| 101 |
+
# current frame fragment
|
| 102 |
+
ori_patches = self.get_original_frame_patches(curr_frame, positions)
|
| 103 |
+
ori_patches_pil = Image.fromarray(ori_patches.astype('uint8'))
|
| 104 |
+
# save_img(ori_patches_pil, fig_path='ori_frag', img_title=f'ori_frag_{i}')
|
| 105 |
+
|
| 106 |
+
frame_frag_tensor = self.transform(ori_patches_pil)
|
| 107 |
+
all_frame_frag_tensor[video_read_index] = frame_frag_tensor
|
| 108 |
+
|
| 109 |
+
video_read_index += 1
|
| 110 |
+
prev_frame = curr_frame
|
| 111 |
+
video_capture.release()
|
| 112 |
+
# visualisation
|
| 113 |
+
visualise_image(curr_frame, 'Current Frame')
|
| 114 |
+
visualise_image(imp_patches_pil, 'Residual Fragment')
|
| 115 |
+
visualise_image(ori_patches_pil, 'Frame Fragment')
|
| 116 |
+
|
| 117 |
+
# Unfilled frames
|
| 118 |
+
self.fill_tensor(all_frame_tensor, video_read_index, video_length)
|
| 119 |
+
self.fill_tensor(all_residual_frag_tensor, video_read_index, video_length - 1)
|
| 120 |
+
self.fill_tensor(all_frame_frag_tensor, video_read_index, video_length - 1)
|
| 121 |
+
|
| 122 |
+
video_all = []
|
| 123 |
+
video_res_frag_all = []
|
| 124 |
+
video_frag_all = []
|
| 125 |
+
for i in range(video_clip):
|
| 126 |
+
clip_tensor = torch.zeros([video_length_clip, video_channel, self.resize, self.resize])
|
| 127 |
+
clip_res_frag_tensor = torch.zeros([video_length_clip, video_channel, self.resize, self.resize])
|
| 128 |
+
clip_frag_tensor = torch.zeros([video_length_clip, video_channel, self.resize, self.resize])
|
| 129 |
+
|
| 130 |
+
start_idx = i * video_frame_rate
|
| 131 |
+
end_idx = start_idx + video_length_clip
|
| 132 |
+
# frame features
|
| 133 |
+
if end_idx <= video_length:
|
| 134 |
+
clip_tensor = all_frame_tensor[start_idx:end_idx]
|
| 135 |
+
else:
|
| 136 |
+
clip_tensor[:(video_length - start_idx)] = all_frame_tensor[start_idx:]
|
| 137 |
+
clip_tensor[(video_length - start_idx):video_length_clip] = clip_tensor[video_length - start_idx - 1]
|
| 138 |
+
|
| 139 |
+
# frame frag features
|
| 140 |
+
if end_idx <= (video_length - 1):
|
| 141 |
+
clip_res_frag_tensor = all_residual_frag_tensor[start_idx:end_idx]
|
| 142 |
+
clip_frag_tensor = all_frame_frag_tensor[start_idx:end_idx]
|
| 143 |
+
else:
|
| 144 |
+
clip_res_frag_tensor[:(video_length - 1 - start_idx)] = all_residual_frag_tensor[start_idx:]
|
| 145 |
+
clip_frag_tensor[:(video_length - 1 - start_idx)] = all_frame_frag_tensor[start_idx:]
|
| 146 |
+
clip_res_frag_tensor[(video_length - 1 - start_idx):video_length_clip] = clip_res_frag_tensor[video_length - 1 - start_idx - 1]
|
| 147 |
+
clip_frag_tensor[(video_length - 1 - start_idx):video_length_clip] = clip_frag_tensor[video_length - 1 - start_idx - 1]
|
| 148 |
+
|
| 149 |
+
video_all.append(clip_tensor)
|
| 150 |
+
video_res_frag_all.append(clip_res_frag_tensor)
|
| 151 |
+
video_frag_all.append(clip_frag_tensor)
|
| 152 |
+
|
| 153 |
+
# Underfilling of clips
|
| 154 |
+
if video_clip < video_clip_min:
|
| 155 |
+
for i in range(video_clip, video_clip_min):
|
| 156 |
+
video_all.append(video_all[video_clip - 1])
|
| 157 |
+
video_res_frag_all.append(video_res_frag_all[video_clip - 1])
|
| 158 |
+
video_frag_all.append(video_frag_all[video_clip - 1])
|
| 159 |
+
return video_all, video_res_frag_all, video_frag_all, video_name
|
| 160 |
+
|
| 161 |
+
@staticmethod
|
| 162 |
+
# duplicat the final frames
|
| 163 |
+
def fill_tensor(tensor, read_index, length):
|
| 164 |
+
if read_index < length:
|
| 165 |
+
tensor[read_index:length] = tensor[read_index - 1]
|
| 166 |
+
|
| 167 |
+
def get_patch_diff(self, residual_frame):
|
| 168 |
+
h, w = residual_frame.shape[:2]
|
| 169 |
+
patch_size = self.patch_size
|
| 170 |
+
h_adj = (h // patch_size) * patch_size
|
| 171 |
+
w_adj = (w // patch_size) * patch_size
|
| 172 |
+
residual_frame_adj = residual_frame[:h_adj, :w_adj]
|
| 173 |
+
# calculate absolute patch difference
|
| 174 |
+
diff = np.zeros((h_adj // patch_size, w_adj // patch_size))
|
| 175 |
+
for i in range(0, h_adj, patch_size):
|
| 176 |
+
for j in range(0, w_adj, patch_size):
|
| 177 |
+
patch = residual_frame_adj[i:i+patch_size, j:j+patch_size]
|
| 178 |
+
# absolute sum
|
| 179 |
+
diff[i // patch_size, j // patch_size] = np.sum(np.abs(patch))
|
| 180 |
+
return diff
|
| 181 |
+
|
| 182 |
+
def extract_important_patches(self, residual_frame, diff):
|
| 183 |
+
patch_size = self.patch_size
|
| 184 |
+
target_size = self.target_size
|
| 185 |
+
top_n = self.top_n
|
| 186 |
+
|
| 187 |
+
# find top n patches indices
|
| 188 |
+
patch_idx = np.unravel_index(np.argsort(-diff.ravel()), diff.shape)
|
| 189 |
+
top_patches = list(zip(patch_idx[0][:top_n], patch_idx[1][:top_n]))
|
| 190 |
+
sorted_idx = sorted(top_patches, key=lambda x: (x[0], x[1]))
|
| 191 |
+
|
| 192 |
+
imp_patches_img = np.zeros((target_size, target_size, residual_frame.shape[2]), dtype=residual_frame.dtype)
|
| 193 |
+
patches_per_row = target_size // patch_size # 14
|
| 194 |
+
# order the patch in the original location relation
|
| 195 |
+
positions = []
|
| 196 |
+
for idx, (y, x) in enumerate(sorted_idx):
|
| 197 |
+
patch = residual_frame[y * patch_size:(y + 1) * patch_size, x * patch_size:(x + 1) * patch_size]
|
| 198 |
+
# new patch location
|
| 199 |
+
row_idx = idx // patches_per_row
|
| 200 |
+
col_idx = idx % patches_per_row
|
| 201 |
+
start_y = row_idx * patch_size
|
| 202 |
+
start_x = col_idx * patch_size
|
| 203 |
+
imp_patches_img[start_y:start_y + patch_size, start_x:start_x + patch_size] = patch
|
| 204 |
+
positions.append((y, x))
|
| 205 |
+
return imp_patches_img, positions
|
| 206 |
+
|
| 207 |
+
def get_original_frame_patches(self, original_frame, positions):
|
| 208 |
+
patch_size = self.patch_size
|
| 209 |
+
target_size = self.target_size
|
| 210 |
+
imp_original_patches_img = np.zeros((target_size, target_size, original_frame.shape[2]), dtype=original_frame.dtype)
|
| 211 |
+
patches_per_row = target_size // patch_size
|
| 212 |
+
|
| 213 |
+
for idx, (y, x) in enumerate(positions):
|
| 214 |
+
start_y = y * patch_size
|
| 215 |
+
start_x = x * patch_size
|
| 216 |
+
end_y = start_y + patch_size
|
| 217 |
+
end_x = start_x + patch_size
|
| 218 |
+
|
| 219 |
+
patch = original_frame[start_y:end_y, start_x:end_x]
|
| 220 |
+
row_idx = idx // patches_per_row
|
| 221 |
+
col_idx = idx % patches_per_row
|
| 222 |
+
target_start_y = row_idx * patch_size
|
| 223 |
+
target_start_x = col_idx * patch_size
|
| 224 |
+
|
| 225 |
+
imp_original_patches_img[target_start_y:target_start_y + patch_size,
|
| 226 |
+
target_start_x:target_start_x + patch_size] = patch
|
| 227 |
+
return imp_original_patches_img
|
| 228 |
+
|
| 229 |
+
def visualise_tensor(tensors, num_frames_to_visualise=5, img_title='Frag'):
|
| 230 |
+
np_feat = tensors.numpy()
|
| 231 |
+
fig, axes = plt.subplots(1, num_frames_to_visualise, figsize=(15, 5))
|
| 232 |
+
for i in range(num_frames_to_visualise):
|
| 233 |
+
# move channels to last dimension for visualisation: (height, width, channels)
|
| 234 |
+
frame = np_feat[i].transpose(1, 2, 0)
|
| 235 |
+
# normalize to [0, 1] for visualisation
|
| 236 |
+
frame = (frame - frame.min()) / (frame.max() - frame.min())
|
| 237 |
+
axes[i].imshow(frame)
|
| 238 |
+
axes[i].axis('off')
|
| 239 |
+
axes[i].set_title(f'{img_title} {i + 1}')
|
| 240 |
+
|
| 241 |
+
plt.tight_layout()
|
| 242 |
+
save_path = f'../../figs/{img_title}.png'
|
| 243 |
+
plt.savefig(save_path, dpi=300)
|
| 244 |
+
plt.show()
|
| 245 |
+
|
| 246 |
+
def visualise_image(frame, img_title='Residual Fragment', debug=False):
|
| 247 |
+
if debug:
|
| 248 |
+
plt.figure(figsize=(5, 5))
|
| 249 |
+
plt.imshow(frame)
|
| 250 |
+
plt.axis('off')
|
| 251 |
+
plt.title(img_title)
|
| 252 |
+
plt.show()
|
| 253 |
+
|
| 254 |
+
def save_img(frame, fig_path, img_title):
|
| 255 |
+
from torchvision.transforms import ToPILImage
|
| 256 |
+
save_path = f'../../figs/{fig_path}/{img_title}.png'
|
| 257 |
+
if isinstance(frame, torch.Tensor):
|
| 258 |
+
if frame.dim() == 3 and frame.size(0) in [1, 3]:
|
| 259 |
+
frame = ToPILImage()(frame)
|
| 260 |
+
else:
|
| 261 |
+
raise ValueError("Unsupported tensor shape. Expected shape (C, H, W) with C=1 or C=3.")
|
| 262 |
+
|
| 263 |
+
if save_path:
|
| 264 |
+
if isinstance(frame, torch.Tensor):
|
| 265 |
+
frame = ToPILImage()(frame)
|
| 266 |
+
elif isinstance(frame, np.ndarray):
|
| 267 |
+
frame = Image.fromarray(frame)
|
| 268 |
+
frame.save(save_path)
|
| 269 |
+
print(f"Image saved to {save_path}")
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
if __name__ == "__main__":
|
| 273 |
+
database = 'konvid_1k'
|
| 274 |
+
videos_dir = '../../ugc_original_videos/'
|
| 275 |
+
metadata_csv = '../../metadata/TEST_metadata.csv'
|
| 276 |
+
# videos_dir = '/home/xinyi/video_dataset/KoNViD_1k/KoNViD_1k_videos/'
|
| 277 |
+
# videos_dir = '/media/on23019/server/LSVQ/'
|
| 278 |
+
# metadata_csv = f'../../metadata/{database.upper()}_metadata.csv'
|
| 279 |
+
|
| 280 |
+
resize = 224 # 224, 384
|
| 281 |
+
start_time = time.time()
|
| 282 |
+
resize_transform = transforms.Compose([transforms.Resize([resize, resize]),
|
| 283 |
+
transforms.ToTensor(),
|
| 284 |
+
transforms.Normalize(mean=[0.45, 0.45, 0.45], std=[0.225, 0.225, 0.225])])
|
| 285 |
+
|
| 286 |
+
dataset = VideoDataset_feature(
|
| 287 |
+
data_dir=videos_dir,
|
| 288 |
+
filename_path=metadata_csv,
|
| 289 |
+
transform=resize_transform,
|
| 290 |
+
resize=resize,
|
| 291 |
+
database=database,
|
| 292 |
+
patch_size=16, # 8, 16, 32, 16, 32
|
| 293 |
+
target_size=224, # 224, 224, 224, 384, 384
|
| 294 |
+
top_n=14*14 # 28*28, 14*14, 7*7, 24*24, 12*12
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
# test
|
| 298 |
+
index = 0
|
| 299 |
+
video_segments, video_res_frag_all, video_frag_all, video_name = dataset[index]
|
| 300 |
+
print(f"Video Name: {video_name}")
|
| 301 |
+
print(f"Number of Video Segments: {len(video_segments)}")
|
| 302 |
+
print(f"Number of Video Residual Fragment Segments: {len(video_res_frag_all)}")
|
| 303 |
+
print(f"Number of Video Fragment Segments: {len(video_frag_all)}")
|
| 304 |
+
print(f"Shape of Each Segment: {video_segments[0].shape}") # (video_length_clip, channels, height, width)
|
| 305 |
+
print(f"Shape of Each Residual Fragment Segments: {video_res_frag_all[0].shape}")
|
| 306 |
+
print(f"Shape of Each Fragment Segments: {video_frag_all[0].shape}")
|
| 307 |
+
|
| 308 |
+
# visualisation
|
| 309 |
+
first_segments = video_segments[0]
|
| 310 |
+
visualise_tensor(first_segments, num_frames_to_visualise=5, img_title='Frame')
|
| 311 |
+
|
| 312 |
+
first_segment_residuals = video_res_frag_all[0]
|
| 313 |
+
visualise_tensor(first_segment_residuals, num_frames_to_visualise=6, img_title='Residual Frag')
|
| 314 |
+
|
| 315 |
+
first_segment_fragments = video_frag_all[0]
|
| 316 |
+
visualise_tensor(first_segment_fragments, num_frames_to_visualise=5, img_title='Frame Frag')
|
| 317 |
+
print(f"Processed {time.time() - start_time:.2f} seconds")
|
extractor/extract_rf_subsampling.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import cv2
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import time
|
| 5 |
+
import torch
|
| 6 |
+
import matplotlib.pyplot as plt
|
| 7 |
+
import math
|
| 8 |
+
import numpy as np
|
| 9 |
+
from torchvision import transforms
|
| 10 |
+
from PIL import Image
|
| 11 |
+
from torch.utils import data
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class VideoDataset_feature(data.Dataset):
|
| 15 |
+
def __init__(self, data_dir, filename_path, transform, resize, database, patch_size=16, target_size=224, top_n=196):
|
| 16 |
+
super(VideoDataset_feature, self).__init__()
|
| 17 |
+
dataInfo = pd.read_csv(filename_path)
|
| 18 |
+
self.video_names = dataInfo['vid'].tolist()
|
| 19 |
+
self.transform = transform
|
| 20 |
+
self.videos_dir = data_dir
|
| 21 |
+
self.resize = resize
|
| 22 |
+
self.database = database
|
| 23 |
+
self.patch_size = patch_size
|
| 24 |
+
self.target_size = target_size
|
| 25 |
+
self.top_n = top_n
|
| 26 |
+
self.length = len(self.video_names)
|
| 27 |
+
|
| 28 |
+
def __len__(self):
|
| 29 |
+
return self.length
|
| 30 |
+
|
| 31 |
+
def __getitem__(self, idx):
|
| 32 |
+
if self.database == 'konvid_1k' or self.database == 'test':
|
| 33 |
+
video_clip_min = 4
|
| 34 |
+
video_name = str(self.video_names[idx]) + '.mp4'
|
| 35 |
+
elif self.database == 'live_vqc':
|
| 36 |
+
video_clip_min = 5
|
| 37 |
+
video_name = str(self.video_names[idx]) + '.mp4'
|
| 38 |
+
elif self.database == 'cvd_2014':
|
| 39 |
+
video_clip_min = 6
|
| 40 |
+
video_name = str(self.video_names[idx]) + '.avi'
|
| 41 |
+
elif self.database == 'youtube_ugc':
|
| 42 |
+
video_clip_min = 10
|
| 43 |
+
video_name = str(self.video_names[idx]) + '.mkv'
|
| 44 |
+
elif self.database == 'youtube_ugc_h264':
|
| 45 |
+
video_clip_min = 10
|
| 46 |
+
video_name = str(self.video_names[idx]) + '.mp4'
|
| 47 |
+
elif self.database == 'lsvq_test_1080p' or self.database == 'lsvq_test' or self.database == 'lsvq_train':
|
| 48 |
+
video_clip_min = 4
|
| 49 |
+
video_name = str(self.video_names[idx]) + '.mp4'
|
| 50 |
+
|
| 51 |
+
filename = os.path.join(self.videos_dir, video_name)
|
| 52 |
+
|
| 53 |
+
video_capture = cv2.VideoCapture(filename)
|
| 54 |
+
video_capture.set(cv2.CAP_PROP_BUFFERSIZE, 3)
|
| 55 |
+
if not video_capture.isOpened():
|
| 56 |
+
raise RuntimeError(f"Failed to open video: {filename}")
|
| 57 |
+
|
| 58 |
+
video_channel = 3
|
| 59 |
+
video_length = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 60 |
+
video_frame_rate = int(round(video_capture.get(cv2.CAP_PROP_FPS)))
|
| 61 |
+
video_clip = int(video_length / video_frame_rate) if video_frame_rate != 0 else 10
|
| 62 |
+
video_length_clip = 32
|
| 63 |
+
# print(video_length)
|
| 64 |
+
# print(video_frame_rate)
|
| 65 |
+
# print(video_clip)
|
| 66 |
+
|
| 67 |
+
# reduce FPS by half: every other frame
|
| 68 |
+
sub_video_length = math.ceil(video_length / 2)
|
| 69 |
+
all_frame_tensor = torch.zeros((sub_video_length, video_channel, self.resize, self.resize), dtype=torch.float32)
|
| 70 |
+
all_residual_frag_tensor = torch.zeros((sub_video_length - 1 , video_channel, self.resize, self.resize), dtype=torch.float32)
|
| 71 |
+
all_frame_frag_tensor = torch.zeros((sub_video_length - 1, video_channel, self.resize, self.resize), dtype=torch.float32)
|
| 72 |
+
|
| 73 |
+
video_read_index = 0
|
| 74 |
+
prev_frame = None
|
| 75 |
+
for i in range(0, video_length, 2): # step by 2 to reduce FPS
|
| 76 |
+
video_capture.set(cv2.CAP_PROP_POS_FRAMES, i) # set frame position
|
| 77 |
+
has_frames, frame = video_capture.read()
|
| 78 |
+
if has_frames:
|
| 79 |
+
curr_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 80 |
+
|
| 81 |
+
# frame features
|
| 82 |
+
curr_frame_tensor = self.transform(Image.fromarray(curr_frame))
|
| 83 |
+
all_frame_tensor[video_read_index] = curr_frame_tensor
|
| 84 |
+
|
| 85 |
+
# frame frag features
|
| 86 |
+
if prev_frame is not None:
|
| 87 |
+
residual = cv2.absdiff(curr_frame, prev_frame)
|
| 88 |
+
diff = self.get_patch_diff(residual)
|
| 89 |
+
# frame residual fragment
|
| 90 |
+
imp_patches, positions = self.extract_important_patches(residual, diff)
|
| 91 |
+
imp_patches_pil = Image.fromarray(imp_patches.astype('uint8'))
|
| 92 |
+
residual_frag_tensor = self.transform(imp_patches_pil)
|
| 93 |
+
all_residual_frag_tensor[video_read_index] = residual_frag_tensor
|
| 94 |
+
|
| 95 |
+
# current frame fragment
|
| 96 |
+
ori_patches = self.get_original_frame_patches(curr_frame, positions)
|
| 97 |
+
ori_patches_pil = Image.fromarray(ori_patches.astype('uint8'))
|
| 98 |
+
frame_frag_tensor = self.transform(ori_patches_pil)
|
| 99 |
+
all_frame_frag_tensor[video_read_index] = frame_frag_tensor
|
| 100 |
+
|
| 101 |
+
video_read_index += 1
|
| 102 |
+
prev_frame = curr_frame
|
| 103 |
+
video_capture.release()
|
| 104 |
+
# visualisation
|
| 105 |
+
visualise_image(curr_frame, 'Current Frame')
|
| 106 |
+
visualise_image(imp_patches_pil, 'Residual Fragment')
|
| 107 |
+
visualise_image(ori_patches_pil, 'Frame Fragment')
|
| 108 |
+
|
| 109 |
+
# Unfilled frames
|
| 110 |
+
self.fill_tensor(all_frame_tensor, video_read_index, sub_video_length)
|
| 111 |
+
self.fill_tensor(all_residual_frag_tensor, video_read_index, sub_video_length - 1)
|
| 112 |
+
self.fill_tensor(all_frame_frag_tensor, video_read_index, sub_video_length - 1)
|
| 113 |
+
|
| 114 |
+
# update video length
|
| 115 |
+
sub_video_length = len(all_frame_tensor)
|
| 116 |
+
sub_video_frame_rate = int(round(video_frame_rate/2))
|
| 117 |
+
sub_video_clip = int(video_clip/2)
|
| 118 |
+
# print(sub_video_length)
|
| 119 |
+
# print(sub_video_frame_rate)
|
| 120 |
+
# print(sub_video_clip)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
video_all = []
|
| 124 |
+
video_res_frag_all = []
|
| 125 |
+
video_frag_all = []
|
| 126 |
+
for i in range(sub_video_clip):
|
| 127 |
+
clip_tensor = torch.zeros([video_length_clip, video_channel, self.resize, self.resize])
|
| 128 |
+
clip_res_frag_tensor = torch.zeros([video_length_clip, video_channel, self.resize, self.resize])
|
| 129 |
+
clip_frag_tensor = torch.zeros([video_length_clip, video_channel, self.resize, self.resize])
|
| 130 |
+
|
| 131 |
+
start_idx = i * sub_video_frame_rate * 2
|
| 132 |
+
end_idx = start_idx + video_length_clip
|
| 133 |
+
# frame features
|
| 134 |
+
if end_idx <= sub_video_length:
|
| 135 |
+
clip_tensor = all_frame_tensor[start_idx:end_idx]
|
| 136 |
+
else:
|
| 137 |
+
clip_tensor[:(sub_video_length - start_idx)] = all_frame_tensor[start_idx:]
|
| 138 |
+
clip_tensor[(sub_video_length - start_idx):video_length_clip] = clip_tensor[sub_video_length - start_idx - 1]
|
| 139 |
+
|
| 140 |
+
# frame frag features
|
| 141 |
+
if end_idx <= (sub_video_length - 1):
|
| 142 |
+
clip_res_frag_tensor = all_residual_frag_tensor[start_idx:end_idx]
|
| 143 |
+
clip_frag_tensor = all_frame_frag_tensor[start_idx:end_idx]
|
| 144 |
+
else:
|
| 145 |
+
clip_res_frag_tensor[:(sub_video_length - 1 - start_idx)] = all_residual_frag_tensor[start_idx:]
|
| 146 |
+
clip_frag_tensor[:(sub_video_length - 1 - start_idx)] = all_frame_frag_tensor[start_idx:]
|
| 147 |
+
clip_res_frag_tensor[(sub_video_length - 1 - start_idx):video_length_clip] = clip_res_frag_tensor[sub_video_length - 1 - start_idx - 1]
|
| 148 |
+
clip_frag_tensor[(sub_video_length - 1 - start_idx):video_length_clip] = clip_frag_tensor[sub_video_length - 1 - start_idx - 1]
|
| 149 |
+
|
| 150 |
+
video_all.append(clip_tensor)
|
| 151 |
+
video_res_frag_all.append(clip_res_frag_tensor)
|
| 152 |
+
video_frag_all.append(clip_frag_tensor)
|
| 153 |
+
|
| 154 |
+
# Underfilling of clips
|
| 155 |
+
if sub_video_clip < video_clip_min:
|
| 156 |
+
for i in range(video_clip, video_clip_min):
|
| 157 |
+
video_all.append(video_all[sub_video_clip - 1])
|
| 158 |
+
video_res_frag_all.append(video_res_frag_all[sub_video_clip - 1])
|
| 159 |
+
video_frag_all.append(video_frag_all[sub_video_clip - 1])
|
| 160 |
+
return video_all, video_res_frag_all, video_frag_all, video_name
|
| 161 |
+
|
| 162 |
+
@staticmethod
|
| 163 |
+
# duplicat the final frames
|
| 164 |
+
def fill_tensor(tensor, read_index, length):
|
| 165 |
+
if read_index < length:
|
| 166 |
+
tensor[read_index:length] = tensor[read_index - 1]
|
| 167 |
+
|
| 168 |
+
def get_patch_diff(self, residual_frame):
|
| 169 |
+
h, w = residual_frame.shape[:2]
|
| 170 |
+
patch_size = self.patch_size
|
| 171 |
+
h_adj = (h // patch_size) * patch_size
|
| 172 |
+
w_adj = (w // patch_size) * patch_size
|
| 173 |
+
residual_frame_adj = residual_frame[:h_adj, :w_adj]
|
| 174 |
+
# calculate absolute patch difference
|
| 175 |
+
diff = np.zeros((h_adj // patch_size, w_adj // patch_size))
|
| 176 |
+
for i in range(0, h_adj, patch_size):
|
| 177 |
+
for j in range(0, w_adj, patch_size):
|
| 178 |
+
patch = residual_frame_adj[i:i+patch_size, j:j+patch_size]
|
| 179 |
+
# absolute sum
|
| 180 |
+
diff[i // patch_size, j // patch_size] = np.sum(np.abs(patch))
|
| 181 |
+
return diff
|
| 182 |
+
|
| 183 |
+
def extract_important_patches(self, residual_frame, diff):
|
| 184 |
+
patch_size = self.patch_size
|
| 185 |
+
target_size = self.target_size
|
| 186 |
+
top_n = self.top_n
|
| 187 |
+
|
| 188 |
+
# find top n patches indices
|
| 189 |
+
patch_idx = np.unravel_index(np.argsort(-diff.ravel()), diff.shape)
|
| 190 |
+
top_patches = list(zip(patch_idx[0][:top_n], patch_idx[1][:top_n]))
|
| 191 |
+
sorted_idx = sorted(top_patches, key=lambda x: (x[0], x[1]))
|
| 192 |
+
|
| 193 |
+
imp_patches_img = np.zeros((target_size, target_size, residual_frame.shape[2]), dtype=residual_frame.dtype)
|
| 194 |
+
patches_per_row = target_size // patch_size # 14
|
| 195 |
+
# order the patch in the original location relation
|
| 196 |
+
positions = []
|
| 197 |
+
for idx, (y, x) in enumerate(sorted_idx):
|
| 198 |
+
patch = residual_frame[y * patch_size:(y + 1) * patch_size, x * patch_size:(x + 1) * patch_size]
|
| 199 |
+
# new patch location
|
| 200 |
+
row_idx = idx // patches_per_row
|
| 201 |
+
col_idx = idx % patches_per_row
|
| 202 |
+
start_y = row_idx * patch_size
|
| 203 |
+
start_x = col_idx * patch_size
|
| 204 |
+
imp_patches_img[start_y:start_y + patch_size, start_x:start_x + patch_size] = patch
|
| 205 |
+
positions.append((y, x))
|
| 206 |
+
return imp_patches_img, positions
|
| 207 |
+
|
| 208 |
+
def get_original_frame_patches(self, original_frame, positions):
|
| 209 |
+
patch_size = self.patch_size
|
| 210 |
+
target_size = self.target_size
|
| 211 |
+
imp_original_patches_img = np.zeros((target_size, target_size, original_frame.shape[2]), dtype=original_frame.dtype)
|
| 212 |
+
patches_per_row = target_size // patch_size
|
| 213 |
+
|
| 214 |
+
for idx, (y, x) in enumerate(positions):
|
| 215 |
+
start_y = y * patch_size
|
| 216 |
+
start_x = x * patch_size
|
| 217 |
+
end_y = start_y + patch_size
|
| 218 |
+
end_x = start_x + patch_size
|
| 219 |
+
|
| 220 |
+
patch = original_frame[start_y:end_y, start_x:end_x]
|
| 221 |
+
row_idx = idx // patches_per_row
|
| 222 |
+
col_idx = idx % patches_per_row
|
| 223 |
+
target_start_y = row_idx * patch_size
|
| 224 |
+
target_start_x = col_idx * patch_size
|
| 225 |
+
|
| 226 |
+
imp_original_patches_img[target_start_y:target_start_y + patch_size,
|
| 227 |
+
target_start_x:target_start_x + patch_size] = patch
|
| 228 |
+
return imp_original_patches_img
|
| 229 |
+
|
| 230 |
+
def visualise_tensor(tensors, num_frames_to_visualise=5, img_title='Frag'):
|
| 231 |
+
np_feat = tensors.numpy()
|
| 232 |
+
fig, axes = plt.subplots(1, num_frames_to_visualise, figsize=(15, 5))
|
| 233 |
+
for i in range(num_frames_to_visualise):
|
| 234 |
+
# move channels to last dimension for visualisation: (height, width, channels)
|
| 235 |
+
frame = np_feat[i].transpose(1, 2, 0)
|
| 236 |
+
# normalize to [0, 1] for visualisation
|
| 237 |
+
frame = (frame - frame.min()) / (frame.max() - frame.min())
|
| 238 |
+
axes[i].imshow(frame)
|
| 239 |
+
axes[i].axis('off')
|
| 240 |
+
axes[i].set_title(f'{img_title} {i + 1}')
|
| 241 |
+
|
| 242 |
+
plt.tight_layout()
|
| 243 |
+
save_path = f'../../figs/{img_title}.png'
|
| 244 |
+
plt.savefig(save_path, dpi=300)
|
| 245 |
+
plt.show()
|
| 246 |
+
|
| 247 |
+
def visualise_image(frame, img_title='Residual Fragment', debug=False):
|
| 248 |
+
if debug:
|
| 249 |
+
plt.figure(figsize=(5, 5))
|
| 250 |
+
plt.imshow(frame)
|
| 251 |
+
plt.axis('off')
|
| 252 |
+
plt.title(img_title)
|
| 253 |
+
plt.show()
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
if __name__ == "__main__":
|
| 257 |
+
database = 'konvid_1k'
|
| 258 |
+
videos_dir = '../../ugc_original_videos/'
|
| 259 |
+
metadata_csv = '../../metadata/TEST_metadata.csv'
|
| 260 |
+
# videos_dir = '/home/xinyi/video_dataset/KoNViD_1k/KoNViD_1k_videos/'
|
| 261 |
+
# videos_dir = '/media/on23019/server/LSVQ/'
|
| 262 |
+
# metadata_csv = f'../../metadata/{database.upper()}_metadata.csv'
|
| 263 |
+
|
| 264 |
+
resize = 224 # 224, 384
|
| 265 |
+
start_time = time.time()
|
| 266 |
+
resize_transform = transforms.Compose([transforms.Resize([resize, resize]),
|
| 267 |
+
transforms.ToTensor(),
|
| 268 |
+
transforms.Normalize(mean=[0.45, 0.45, 0.45], std=[0.225, 0.225, 0.225])])
|
| 269 |
+
|
| 270 |
+
dataset = VideoDataset_feature(
|
| 271 |
+
data_dir=videos_dir,
|
| 272 |
+
filename_path=metadata_csv,
|
| 273 |
+
transform=resize_transform,
|
| 274 |
+
resize=resize,
|
| 275 |
+
database=database,
|
| 276 |
+
patch_size=16, # 8, 16, 32, 16, 32
|
| 277 |
+
target_size=224, # 224, 224, 224, 384, 384
|
| 278 |
+
top_n=14*14 # 28*28, 14*14, 7*7, 24*24, 12*12
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
# test
|
| 282 |
+
index = 0
|
| 283 |
+
video_segments, video_res_frag_all, video_frag_all, video_name = dataset[index]
|
| 284 |
+
print(f"Video Name: {video_name}")
|
| 285 |
+
print(f"Number of Video Segments: {len(video_segments)}")
|
| 286 |
+
print(f"Number of Video Residual Fragment Segments: {len(video_res_frag_all)}")
|
| 287 |
+
print(f"Number of Video Fragment Segments: {len(video_frag_all)}")
|
| 288 |
+
print(f"Shape of Each Segment: {video_segments[0].shape}") # (video_length_clip, channels, height, width)
|
| 289 |
+
print(f"Shape of Each Residual Fragment Segments: {video_res_frag_all[0].shape}")
|
| 290 |
+
print(f"Shape of Each Fragment Segments: {video_frag_all[0].shape}")
|
| 291 |
+
|
| 292 |
+
# visualisation
|
| 293 |
+
first_segments = video_segments[0]
|
| 294 |
+
visualise_tensor(first_segments, num_frames_to_visualise=5, img_title='Frame')
|
| 295 |
+
|
| 296 |
+
first_segment_residuals = video_res_frag_all[0]
|
| 297 |
+
visualise_tensor(first_segment_residuals, num_frames_to_visualise=6, img_title='Residual Frag')
|
| 298 |
+
|
| 299 |
+
first_segment_fragments = video_frag_all[0]
|
| 300 |
+
visualise_tensor(first_segment_fragments, num_frames_to_visualise=5, img_title='Frame Frag')
|
| 301 |
+
print(f"Processed {time.time() - start_time:.2f} seconds")
|
extractor/extract_slowfast_clip.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from pytorchvideo.models.hub import slowfast_r50
|
| 4 |
+
|
| 5 |
+
def pack_pathway_output(frames, device):
|
| 6 |
+
fast_pathway = frames
|
| 7 |
+
# temporal sampling from the fast pathway.
|
| 8 |
+
slow_pathway = torch.index_select(
|
| 9 |
+
frames,
|
| 10 |
+
2,
|
| 11 |
+
torch.linspace(0, frames.shape[2] - 1, frames.shape[2] // 4).long(),
|
| 12 |
+
)
|
| 13 |
+
return [slow_pathway.to(device), fast_pathway.to(device)]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class SlowFast(torch.nn.Module):
|
| 17 |
+
def __init__(self):
|
| 18 |
+
super(SlowFast, self).__init__()
|
| 19 |
+
slowfast_pretrained_features = nn.Sequential(*list(slowfast_r50(pretrained=True).children())[0])
|
| 20 |
+
|
| 21 |
+
self.feature_extraction = torch.nn.Sequential()
|
| 22 |
+
self.slow_avg_pool = torch.nn.Sequential()
|
| 23 |
+
self.fast_avg_pool = torch.nn.Sequential()
|
| 24 |
+
self.adp_avg_pool = torch.nn.Sequential()
|
| 25 |
+
|
| 26 |
+
for x in range(0, 5):
|
| 27 |
+
self.feature_extraction.add_module(str(x), slowfast_pretrained_features[x])
|
| 28 |
+
|
| 29 |
+
self.slow_avg_pool.add_module('slow_avg_pool', slowfast_pretrained_features[5].pool[0])
|
| 30 |
+
self.fast_avg_pool.add_module('fast_avg_pool', slowfast_pretrained_features[5].pool[1])
|
| 31 |
+
self.adp_avg_pool.add_module('adp_avg_pool', slowfast_pretrained_features[6].output_pool)
|
| 32 |
+
|
| 33 |
+
def forward(self, x):
|
| 34 |
+
with torch.no_grad():
|
| 35 |
+
x = self.feature_extraction(x)
|
| 36 |
+
slow_feature = self.slow_avg_pool(x[0])
|
| 37 |
+
fast_feature = self.fast_avg_pool(x[1])
|
| 38 |
+
slow_feature = self.adp_avg_pool(slow_feature)
|
| 39 |
+
fast_feature = self.adp_avg_pool(fast_feature)
|
| 40 |
+
return slow_feature, fast_feature
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def extract_features_slowfast(video, model, device):
|
| 44 |
+
slow_features_list = []
|
| 45 |
+
fast_features_list = []
|
| 46 |
+
|
| 47 |
+
with torch.cuda.amp.autocast():
|
| 48 |
+
for idx, segment in enumerate(video):
|
| 49 |
+
segment = segment.permute(0, 2, 1, 3, 4)
|
| 50 |
+
inputs = pack_pathway_output(segment, device)
|
| 51 |
+
# print(f"Inputs shapes: slow={inputs[0].shape}, fast={inputs[1].shape}")
|
| 52 |
+
|
| 53 |
+
# extract features
|
| 54 |
+
slow_feature, fast_feature = model(inputs)
|
| 55 |
+
slow_features_list.append(slow_feature)
|
| 56 |
+
fast_features_list.append(fast_feature)
|
| 57 |
+
|
| 58 |
+
# concatenate and flatten features
|
| 59 |
+
slow_features = torch.cat(slow_features_list, dim=0).flatten()
|
| 60 |
+
fast_features = torch.cat(fast_features_list, dim=0).flatten()
|
| 61 |
+
return slow_features, fast_features
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def extract_features_slowfast_pool(video, model, device):
|
| 65 |
+
slow_features_list = []
|
| 66 |
+
fast_features_list = []
|
| 67 |
+
|
| 68 |
+
with torch.cuda.amp.autocast():
|
| 69 |
+
for idx, segment in enumerate(video):
|
| 70 |
+
segment = segment.permute(0, 2, 1, 3, 4)
|
| 71 |
+
inputs = pack_pathway_output(segment, device)
|
| 72 |
+
# print(f"Inputs shapes: slow={inputs[0].shape}, fast={inputs[1].shape}")
|
| 73 |
+
|
| 74 |
+
# extract features
|
| 75 |
+
slow_feature, fast_feature = model(inputs)
|
| 76 |
+
# global average pooling to reduce dimensions
|
| 77 |
+
slow_feature = slow_feature.mean(dim=[2, 3, 4]) # Pool over spatial and temporal dims
|
| 78 |
+
fast_feature = fast_feature.mean(dim=[2, 3, 4])
|
| 79 |
+
slow_features_list.append(slow_feature)
|
| 80 |
+
fast_features_list.append(fast_feature)
|
| 81 |
+
|
| 82 |
+
# concatenate pooled features
|
| 83 |
+
slow_features = torch.cat(slow_features_list, dim=0)
|
| 84 |
+
fast_features = torch.cat(fast_features_list, dim=0)
|
| 85 |
+
slowfast_features = torch.cat((slow_features, fast_features), dim=1) # along feature dimension
|
| 86 |
+
return slow_features, fast_features, slowfast_features
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# slow_features, fast_features = extract_features_slowfast_pool(video, model, device)
|
| 90 |
+
|
| 91 |
+
# extract_features_slowfast():
|
| 92 |
+
# Segment shape: torch.Size([1, 3, 32, 224, 224])
|
| 93 |
+
# Inputs shapes: slow=torch.Size([1, 3, 8, 224, 224]), fast=torch.Size([1, 3, 32, 224, 224])
|
| 94 |
+
# Slow feature shape: torch.Size([1, 2048, 1, 1, 1])
|
| 95 |
+
# Fast feature shape: torch.Size([1, 256, 1, 1, 1])
|
| 96 |
+
# Slow features shape: torch.Size([16384])
|
| 97 |
+
# Fast features shape: torch.Size([2048])
|
| 98 |
+
# Combined features shape: torch.Size([18432])
|
| 99 |
+
#
|
| 100 |
+
# extract_features_slowfast_pool():
|
| 101 |
+
# Segment shape: torch.Size([1, 3, 32, 224, 224])
|
| 102 |
+
# Inputs shapes: slow=torch.Size([1, 3, 8, 224, 224]), fast=torch.Size([1, 3, 32, 224, 224])
|
| 103 |
+
# Slow feature shape: torch.Size([1, 2048, 1, 1, 1])
|
| 104 |
+
# Fast feature shape: torch.Size([1, 256, 1, 1, 1])
|
| 105 |
+
# Pooled Slow feature shape: torch.Size([1, 2048])
|
| 106 |
+
# Pooled Fast feature shape: torch.Size([1, 256])
|
| 107 |
+
# Pooled Slow features shape: torch.Size([8, 2048])
|
| 108 |
+
# Pooled Fast features shape: torch.Size([8, 256])
|
| 109 |
+
# Combined features shape: torch.Size([8, 2304])
|
| 110 |
+
# Averaged combined features shape: torch.Size([2304])
|
extractor/extract_swint_clip.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from timm import create_model
|
| 4 |
+
|
| 5 |
+
class Identity(nn.Module):
|
| 6 |
+
def __init__(self):
|
| 7 |
+
super(Identity, self).__init__()
|
| 8 |
+
|
| 9 |
+
def forward(self, x):
|
| 10 |
+
return x
|
| 11 |
+
|
| 12 |
+
class SwinT(nn.Module):
|
| 13 |
+
def __init__(self, model_name='swin_base_patch4_window7_224', global_pool='avg', pretrained=True):
|
| 14 |
+
super(SwinT, self).__init__()
|
| 15 |
+
self.swin_model = create_model(
|
| 16 |
+
model_name, pretrained=pretrained, global_pool=global_pool
|
| 17 |
+
)
|
| 18 |
+
self.swin_model.head = Identity() # Remove classification head
|
| 19 |
+
self.global_pool = global_pool
|
| 20 |
+
|
| 21 |
+
def forward(self, x):
|
| 22 |
+
features = self.swin_model(x) # Shape: (batch_size, 7, 7, 1024)
|
| 23 |
+
if self.global_pool == 'avg':
|
| 24 |
+
features = features.mean(dim=[1, 2]) # Global pool
|
| 25 |
+
return features
|
| 26 |
+
|
| 27 |
+
def extract_features_swint_pool(video, model, device):
|
| 28 |
+
swint_feature_list = []
|
| 29 |
+
|
| 30 |
+
with torch.cuda.amp.autocast():
|
| 31 |
+
for segment in video:
|
| 32 |
+
# Flatten the segment into a batch of frames
|
| 33 |
+
frames = segment.squeeze(0).to(device) # Shape: (32, 3, 224, 224)
|
| 34 |
+
|
| 35 |
+
swint_features = model(frames) # Shape: (32, feature_dim)
|
| 36 |
+
swint_feature_list.append(swint_features)
|
| 37 |
+
|
| 38 |
+
# Concatenate features across segments
|
| 39 |
+
features = torch.cat(swint_feature_list, dim=0) # Shape: (num_frames, feature_dim)
|
| 40 |
+
return features
|