import numpy as np import mediapipe as mp from typing import Optional, Tuple, Dict import warnings class LandmarkExtractor: def __init__(self, normalize: bool = True, normalization_type: str='palm', add_convidence: bool=True, use_world_coords:bool=False): self.normalize = normalize self.normalization_type = normalization_type self.add_convidence = add_convidence self.use_world_coords = use_world_coords self.mp_hands = mp.solutions.hands self.mp_draw = mp.solutions.drawing_utils self.detector = self.mp_hands.Hands( static_image_mode=False, max_num_hands=2, model_complexity=1, min_detection_confidence=0.5, min_tracking_confidence=0.3 ) def _palm_normalize(self, landmarks: np.ndarray) -> np.ndarray: wrist = landmarks[0] centered = landmarks - wrist mcp_idx = [1,5,9,13,17] mcp_points = landmarks[mcp_idx] distance = np.linalg.norm(mcp_points - wrist, axis=1) palm_size = np.mean(distance) if palm_size < 1e-8: palm_size = 1.0 normalized = centered / palm_size return normalized def _bounding_box_normalize(self, landmarks: np.ndarray) -> np.ndarray: min_coords = np.min(landmarks, axis=0) max_coords = np.max(landmarks, axis=0) center = (min_coords + max_coords) / 2 centered = landmarks - center bbox_size = max_coords - min_coords scale = np.max(bbox_size[:2]) if scale < 1e-8: scale = 1.0 normalized = centered / scale return normalized def _wrist_normalize(self, landmarks: np.ndarray) -> np.ndarray: wrist = landmarks[0] centered = landmarks - wrist max_distance = np.max(np.linalg.norm(centered, axis=1)) if max_distance < 1e-8: max_distance = 1.0 normalized = centered / max_distance return normalized def normalize_landmarks(self, landmarks: np.ndarray) -> np.ndarray: if not self.normalize: return landmarks if self.normalization_type == 'palm': return self._palm_normalize(landmarks) elif self.normalization_type == 'bounding_box': return self._bounding_box_normalize(landmarks) elif self.normalization_type == 'wrist': return self._wrist_normalize(landmarks) else: raise ValueError(f"Unknown normalization type: {self.normalization_type}") def process(self, results) -> Dict: output = { 'left_hand': None, 'right_hand': None, 'left_hand_confidence': 0.0, 'right_hand_confidence': 0.0 } if not results.multi_hand_landmarks: return output for i, hand_landmarks in enumerate(results.multi_hand_landmarks): handedness = results.multi_handedness[i].classification[0] label = handedness.label confidence = handedness.score if self.use_world_coords and hasattr(results, 'multi_hand_world_landmarks'): world_landmarks = results.multi_hand_world_landmarks[i] landmarks = np.array([[lm.x, lm.y, lm.z] for lm in world_landmarks.landmark], dtype=np.float32) else: landmarks = np.array([[lm.x, lm.y, lm.z] for lm in hand_landmarks.landmark], dtype=np.float32) landmarks = self.normalize_landmarks(landmarks) flattened = landmarks.flatten() if label == 'Left': output['left_hand'] = flattened output['left_hand_confidence'] = confidence else: output['right_hand'] = flattened output['right_hand_confidence'] = confidence return output def extract(self, results, strategy='concat') -> np.ndarray: processed = self.process(results) if strategy == 'concat': left = (processed['left_hand'] if processed['left_hand'] is not None else np.zeros(21*3, dtype=np.float32)) right = (processed['right_hand'] if processed['right_hand'] is not None else np.zeros(21*3, dtype=np.float32)) if self.add_convidence: features = np.concatenate([left, right, [processed['left_hand_confidence']], [processed['right_hand_confidence']]]) else: features = np.concatenate([left, right]) elif strategy == 'single': if processed['left_hand'] is not None: features = processed['left_hand'] if self.add_convidence: features = np.concatenate([features, [processed['left_hand_confidence']]]) elif processed['right_hand'] is not None: features = processed['right_hand'] if self.add_convidence: features = np.concatenate([features, [processed['right_hand_confidence']]]) else: features = np.zeros(21*3, dtype=np.float32) elif strategy == 'bolth_with_flags': left = processed['left_hand'] if processed['left_hand'] is not None else np.zeros(21*3, dtype=np.float32) right = processed['right_hand'] if processed['right_hand'] is not None else np.zeros(21*3, dtype=np.float32) left_flag = float(processed['left_hand'] is not None) right_flag = float(processed['right_hand'] is not None) features = np.concatenate([ left, right, [left_flag, right_flag], [processed['left_hand_confidence'], processed['right_hand_confidence']]], dtype=np.float32 ) else: raise ValueError(f"Unknown extraction strategy: {strategy}") return features def extract_batch(self, results: list, strategy='concat') -> np.ndarray: return np.array([self.extract(res, strategy) for res in results]) def draw(self, image: np.ndarray, results, draw_left:bool=True, draw_right:bool=True) -> np.ndarray: if not results.multi_hand_landmarks: return image output = image.copy() for i, hand_landmarks in enumerate(results.multi_hand_landmarks): label = results.multi_handedness[i].classification[0].label if label == 'Left' and not draw_left: continue if label == 'Right' and not draw_right: continue if label == 'Left': landmak_color = (245, 66, 230) connection_color = (245, 66, 230) else: landmak_color = (66, 133, 244) connection_color = (66, 133, 244) self.mp_draw.draw_landmarks( output, hand_landmarks, self.mp_hands.HAND_CONNECTIONS, self.mp_draw.DrawingSpec(color=landmak_color, thickness=2, circle_radius=2), self.mp_draw.DrawingSpec(color=connection_color, thickness=2, circle_radius=2) ) return output def close(self): if hasattr(self.detector, 'hands'): self.detector.close() def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.close()