Repository navigation
Expand file tree
/
Copy pathflame_filter_parameters.py
More file actions
253 lines (205 loc) · 7.87 KB
/
Copy pathflame_filter_parameters.py
File metadata and controls
253 lines (205 loc) · 7.87 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
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
"""
FLAME Parameter Filtering Script
===============================
Filters facial expression parameters into high, mid, and low frequency components
using Butterworth filters. Input and output structures match the MEAD dataset format.
Usage:
python flame_filter_parameters.py
"""
import numpy as np
from scipy.signal import butter, filtfilt
from pathlib import Path
import hickle as hkl
from tqdm import tqdm
import warnings
warnings.filterwarnings('ignore')
# Dataset configuration
EMOTIONS = ['angry', 'contempt', 'disgusted', 'fear', 'happy', 'neutral', 'sad', 'surprised']
INTENSITIES = ['level_1', 'level_2', 'level_3']
DATA_ROOT = Path("/hpc2hdd/home/ntang745/workspace/inferno/assets/reconstruction_v0/EMICA_mead_mp_lr_mse_15")
OUTPUT_ROOT = Path("EMICA_mead_mp_lr_mse_15_filtered")
FPS = 30 # Frame rate for filtering
# =============================================================================
# Butterworth Filter Functions
# =============================================================================
def butter_lowpass(x, cutoff, fs, order=4):
"""
Low-pass filter for 1D signal
x: (T,)
"""
nyq = fs / 2
norm_cutoff = cutoff / nyq
b, a = butter(order, norm_cutoff, btype='low')
return filtfilt(b, a, x)
def butter_bandpass(x, lowcut, highcut, fs, order=4):
"""
Band-pass filter for 1D signal
x: (T,)
"""
nyq = fs / 2
low = lowcut / nyq
high = highcut / nyq
b, a = butter(order, [low, high], btype='band')
return filtfilt(b, a, x)
def butter_highpass(x, cutoff, fs, order=4):
"""
High-pass filter for 1D signal
x: (T,)
"""
nyq = fs / 2
norm_cutoff = cutoff / nyq
b, a = butter(order, norm_cutoff, btype='high')
return filtfilt(b, a, x)
def butterworth_decompose_expression(X, fps=25):
"""
Decompose 56-dimensional expression parameters into frequency components.
Parameters
----------
X : np.ndarray
Shape (T, 50), facial expression parameters (FLAME has 50, not 56)
fps : int
Video frame rate
Returns
-------
low : np.ndarray, shape (T, 50)
mid : np.ndarray, shape (T, 50)
high : np.ndarray, shape (T, 50)
"""
T, D = X.shape
if D != 50:
message = "Expected 50-dimensional expression parameters, got {}".format(D)
raise ValueError(message)
low = np.zeros_like(X)
mid = np.zeros_like(X)
high = np.zeros_like(X)
for d in range(D):
signal_1d = X[:, d]
# Low-frequency: expression baseline / affect trend
low[:, d] = butter_lowpass(
signal_1d, cutoff=0.5, fs=fps
)
# Mid-frequency: primary facial motion
mid[:, d] = butter_bandpass(
signal_1d, lowcut=0.5, highcut=5.0, fs=fps
)
# High-frequency: micro-expression + noise
high[:, d] = butter_highpass(
signal_1d, cutoff=5.0, fs=fps
)
return low, mid, high
# =============================================================================
# Processing Functions
# =============================================================================
def process_single_file(pkl_path):
"""
Process a single .pkl file and return filtered components.
Returns:
dict: Original data + low/mid/high frequency components
str: Person ID
str: Emotion
str: Intensity
str: Text ID
"""
try:
# Load original data
data = hkl.load(str(pkl_path))
# Extract parameters
exp = data['exp'][0] # (frames, 50)
jaw = data['jaw_pose'][0] # (frames, 3)
pose = data['global_pose'][0] # (frames, 3)
# Apply filtering to expression parameters only
low_exp, mid_exp, high_exp = butterworth_decompose_expression(exp, fps=FPS)
# Combine all parameters
result = {
'exp': [exp], # Keep original as first element
'exp_low': [low_exp],
'exp_mid': [mid_exp],
'exp_high': [high_exp],
'jaw': [jaw],
'global_pose': [pose]
}
# Extract metadata from path
path_parts = pkl_path.parts
person_id = path_parts[-5] # M003, W001, etc.
emotion = path_parts[-4] # angry, happy, etc.
intensity = path_parts[-3] # level_1, level_2, level_3
text_id = path_parts[-2] # 001, 002, etc.
return result, person_id, emotion, intensity, text_id
except Exception as e:
print("Error processing")
print(pkl_path)
return None, None, None, None, None
def create_output_structure():
"""Create output directory structure matching input."""
# Create main output directory
OUTPUT_ROOT.mkdir(exist_ok=True)
# Create person directories and subdirectories
for person_dir in DATA_ROOT.iterdir():
if person_dir.is_dir() and person_dir.name not in ['.claude', '__pycache__']:
# Create person directory
person_output = OUTPUT_ROOT / person_dir.name
person_output.mkdir(exist_ok=True)
# Create front directory
front_dir = person_dir / 'front'
if front_dir.exists():
front_output = person_output / 'front'
front_output.mkdir(exist_ok=True)
# Create emotion directories
for emotion in EMOTIONS:
emotion_dir = front_dir / emotion
if emotion_dir.exists():
emotion_output = front_output / emotion
emotion_output.mkdir(exist_ok=True)
# Create intensity directories
for intensity in INTENSITIES:
intensity_dir = emotion_dir / intensity
if intensity_dir.exists():
intensity_output = emotion_output / intensity
intensity_output.mkdir(exist_ok=True)
def main():
"""Main processing function."""
print("Starting FLAME parameter filtering...")
print("Input: {DATA_ROOT}")
print("Output: {OUTPUT_ROOT}")
print()
# Create output structure
create_output_structure()
# Get all .pkl files
pkl_files = []
for person_dir in DATA_ROOT.iterdir():
if person_dir.is_dir() and person_dir.name not in ['.claude', '__pycache__']:
front_dir = person_dir / 'front'
if not front_dir.exists():
continue
for emotion in EMOTIONS:
emotion_dir = front_dir / emotion
if not emotion_dir.exists():
continue
for intensity in INTENSITIES:
intensity_dir = emotion_dir / intensity
if not intensity_dir.exists():
continue
for text_dir in sorted(intensity_dir.iterdir()):
if text_dir.is_dir():
pkl_path = text_dir / 'shape_pose_cam.pkl'
if pkl_path.exists():
pkl_files.append(pkl_path)
print("Found {len(pkl_files)} .pkl files to process")
# Process files
success_count = 0
for pkl_path in tqdm(pkl_files, desc="Processing files"):
result, person_id, emotion, intensity, text_id = process_single_file(pkl_path)
if result is not None:
# Determine output path
output_path = (OUTPUT_ROOT / person_id / 'front' / emotion /
intensity / text_id / 'shape_pose_cam.pkl')
# Save filtered data
try:
hkl.dump(result, str(output_path))
success_count += 1
except Exception as e:
print("Error saving {output_path}: {e}")
print("\nCompleted! Successfully processed {success_count}/{len(pkl_files)} files")
print("Filtered data saved to: {OUTPUT_ROOT}")
if __name__ == "__main__":
main()