File size: 7,545 Bytes
9950952
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()