File size: 9,710 Bytes
4853e68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
"""Data preprocessing with MediaPipe"""

import cv2
import numpy as np
try:
    import mediapipe as mp
    MEDIAPIPE_AVAILABLE = True
except ImportError:
    MEDIAPIPE_AVAILABLE = False
    mp = None

from typing import Optional, Dict, List, Tuple
from pathlib import Path
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class MediaPipePreprocessor:
    """Extract landmarks from videos using MediaPipe Holistic"""
    
    def __init__(self, 

                 min_detection_confidence: float = 0.5,

                 min_tracking_confidence: float = 0.5):
        """

        Initialize MediaPipe Holistic

        

        Args:

            min_detection_confidence: Minimum confidence for detection

            min_tracking_confidence: Minimum confidence for tracking

        """
        self.min_detection_confidence = min_detection_confidence
        self.min_tracking_confidence = min_tracking_confidence
        self.holistic = None
        self.mp_holistic = None
        
        # Landmark dimensions
        self.pose_dim = 33 * 4  # 33 landmarks * (x, y, z, visibility)
        self.hand_dim = 21 * 3  # 21 landmarks * (x, y, z)
        self.face_dim = 468 * 3  # 468 landmarks * (x, y, z)
        self.total_dim = self.pose_dim + 2 * self.hand_dim + self.face_dim
        
        # Initialize MediaPipe
        self._initialize_mediapipe()
    
    def _initialize_mediapipe(self):
        """Initialize or reinitialize MediaPipe"""
        if not MEDIAPIPE_AVAILABLE or mp is None:
            logger.warning("MediaPipe not available - using dummy preprocessor")
            return
        
        try:
            # Close existing instance if any
            if self.holistic is not None:
                try:
                    self.holistic.close()
                except:
                    pass
            
            # Create new instance
            self.mp_holistic = mp.solutions.holistic
            self.holistic = self.mp_holistic.Holistic(
                min_detection_confidence=self.min_detection_confidence,
                min_tracking_confidence=self.min_tracking_confidence,
                model_complexity=1,
                static_image_mode=False,
                smooth_landmarks=True
            )
            logger.info("MediaPipe initialized successfully")
            
        except Exception as e:
            logger.error(f"Failed to initialize MediaPipe: {e}")
            self.holistic = None
            self.mp_holistic = None
            raise RuntimeError(f"MediaPipe initialization failed: {e}")
    
    def extract_landmarks_from_frame(self, frame: np.ndarray) -> Optional[np.ndarray]:
        """

        Extract landmarks from a single frame

        

        Args:

            frame: RGB image frame

            

        Returns:

            Flattened landmark array of shape (total_dim,) or None if detection fails

        """
        if self.holistic is None:
            logger.error("MediaPipe not initialized! Call _initialize_mediapipe() first")
            raise RuntimeError("MediaPipe not initialized. Please check MediaPipe installation.")
        
        # Convert BGR to RGB if needed
        if len(frame.shape) == 3 and frame.shape[2] == 3:
            frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        else:
            frame_rgb = frame
        
        # Process frame
        results = self.holistic.process(frame_rgb)
        
        # Extract landmarks
        landmarks = []
        
        # Pose landmarks (33 * 4 = 132)
        if results.pose_landmarks:
            pose = np.array([[lm.x, lm.y, lm.z, lm.visibility] 
                           for lm in results.pose_landmarks.landmark]).flatten()
        else:
            pose = np.zeros(self.pose_dim)
        landmarks.append(pose)
        
        # Left hand landmarks (21 * 3 = 63)
        if results.left_hand_landmarks:
            left_hand = np.array([[lm.x, lm.y, lm.z] 
                                for lm in results.left_hand_landmarks.landmark]).flatten()
        else:
            left_hand = np.zeros(self.hand_dim)
        landmarks.append(left_hand)
        
        # Right hand landmarks (21 * 3 = 63)
        if results.right_hand_landmarks:
            right_hand = np.array([[lm.x, lm.y, lm.z] 
                                 for lm in results.right_hand_landmarks.landmark]).flatten()
        else:
            right_hand = np.zeros(self.hand_dim)
        landmarks.append(right_hand)
        
        # Face landmarks (468 * 3 = 1404) - optional, can be excluded for efficiency
        # Uncomment if you want to include face landmarks
        # if results.face_landmarks:
        #     face = np.array([[lm.x, lm.y, lm.z] 
        #                    for lm in results.face_landmarks.landmark]).flatten()
        # else:
        #     face = np.zeros(self.face_dim)
        # landmarks.append(face)
        
        # Concatenate all landmarks
        landmarks_array = np.concatenate(landmarks)
        
        return landmarks_array
    
    def extract_landmarks_from_video(self, 

                                    video_path: str, 

                                    max_frames: int = 64,

                                    target_fps: Optional[int] = None) -> Optional[np.ndarray]:
        """

        Extract landmarks from video file

        

        Args:

            video_path: Path to video file

            max_frames: Maximum number of frames to extract

            target_fps: Target FPS for frame sampling (None = use all frames)

            

        Returns:

            Landmark sequence of shape (num_frames, total_dim) or None if failed

        """
        cap = cv2.VideoCapture(video_path)
        
        if not cap.isOpened():
            logger.error(f"Failed to open video: {video_path}")
            return None
        
        # Get video properties
        fps = cap.get(cv2.CAP_PROP_FPS)
        total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        
        # Calculate frame sampling rate
        if target_fps and target_fps < fps:
            frame_skip = int(fps / target_fps)
        else:
            frame_skip = 1
        
        landmarks_sequence = []
        frame_idx = 0
        
        while len(landmarks_sequence) < max_frames:
            ret, frame = cap.read()
            
            if not ret:
                break
            
            # Sample frames
            if frame_idx % frame_skip == 0:
                landmarks = self.extract_landmarks_from_frame(frame)
                
                if landmarks is not None:
                    landmarks_sequence.append(landmarks)
            
            frame_idx += 1
        
        cap.release()
        
        if not landmarks_sequence:
            logger.warning(f"No landmarks extracted from: {video_path}")
            return None
        
        # Convert to numpy array
        landmarks_array = np.array(landmarks_sequence)
        
        # Pad or truncate to max_frames
        if len(landmarks_array) < max_frames:
            # Pad with zeros
            padding = np.zeros((max_frames - len(landmarks_array), landmarks_array.shape[1]))
            landmarks_array = np.vstack([landmarks_array, padding])
        else:
            # Truncate
            landmarks_array = landmarks_array[:max_frames]
        
        return landmarks_array
    
    def normalize_landmarks(self, landmarks: np.ndarray) -> np.ndarray:
        """

        Normalize landmarks to zero mean and unit variance

        

        Args:

            landmarks: Landmark array of shape (num_frames, total_dim)

            

        Returns:

            Normalized landmarks

        """
        # Calculate mean and std (excluding zero-padded frames)
        non_zero_mask = np.any(landmarks != 0, axis=1)
        
        if np.sum(non_zero_mask) > 0:
            mean = landmarks[non_zero_mask].mean(axis=0)
            std = landmarks[non_zero_mask].std(axis=0) + 1e-8
            
            # Normalize
            landmarks_normalized = landmarks.copy()
            landmarks_normalized[non_zero_mask] = (landmarks[non_zero_mask] - mean) / std
            
            return landmarks_normalized
        
        return landmarks
    
    def close(self):
        """Explicitly close MediaPipe resources"""
        if self.holistic is not None:
            try:
                self.holistic.close()
                logger.info("MediaPipe closed successfully")
            except Exception as e:
                logger.warning(f"Error closing MediaPipe: {e}")
            finally:
                self.holistic = None
    
    def __del__(self):
        """Cleanup"""
        self.close()


def preprocess_video(video_path: str, 

                    max_frames: int = 64,

                    normalize: bool = True) -> Optional[np.ndarray]:
    """

    Convenience function to preprocess a single video

    

    Args:

        video_path: Path to video file

        max_frames: Maximum number of frames

        normalize: Whether to normalize landmarks

        

    Returns:

        Preprocessed landmarks array

    """
    preprocessor = MediaPipePreprocessor()
    landmarks = preprocessor.extract_landmarks_from_video(video_path, max_frames)
    
    if landmarks is not None and normalize:
        landmarks = preprocessor.normalize_landmarks(landmarks)
    
    return landmarks