hand-guest-control 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +87 -0
- package/package.json +43 -0
- package/src/HandGestureDetector.js +192 -0
- package/src/HandStateManager.js +276 -0
- package/src/constants.js +52 -0
- package/src/index.js +9 -0
- package/src/mediapipe.js +59 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 HoloLab
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# hand-guest-control
|
|
2
|
+
|
|
3
|
+
Hand gesture detection and state management using MediaPipe landmarks. Extracted from `mn-hand-control`.
|
|
4
|
+
|
|
5
|
+
## Demo UI (test package in browser)
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
cd npm/hand-guest-control
|
|
9
|
+
npm install
|
|
10
|
+
npm run demo
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Open **http://localhost:5180** — webcam + live hand state overlay.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install hand-guest-control @mediapipe/tasks-vision
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Or local workspace link during development:
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npm install ../npm/hand-guest-control
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Usage
|
|
28
|
+
|
|
29
|
+
### Core — gesture state machine
|
|
30
|
+
|
|
31
|
+
```javascript
|
|
32
|
+
import { HandStateManager, HAND_STATES } from 'hand-guest-control';
|
|
33
|
+
|
|
34
|
+
const manager = new HandStateManager({
|
|
35
|
+
rotationSensitivity: 4,
|
|
36
|
+
waitingTimeout: 10000,
|
|
37
|
+
startingDelay: 3000,
|
|
38
|
+
debug: false
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
// landmarks from MediaPipe HandLandmarker
|
|
42
|
+
const { state, rotation } = manager.processLandmarks(landmarks);
|
|
43
|
+
|
|
44
|
+
if (state === HAND_STATES.OPEN) {
|
|
45
|
+
// zoom in
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
if (state === HAND_STATES.SWIPE_NEXT) {
|
|
49
|
+
// next item
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
### MediaPipe helper
|
|
54
|
+
|
|
55
|
+
```javascript
|
|
56
|
+
import { createHandLandmarker } from 'hand-guest-control/mediapipe';
|
|
57
|
+
|
|
58
|
+
const landmarker = await createHandLandmarker({
|
|
59
|
+
minHandDetectionConfidence: 0.6
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
const results = await landmarker.detectForVideo(videoElement, Date.now());
|
|
63
|
+
const { state, rotation } = manager.processLandmarks(results.landmarks?.[0]);
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## API
|
|
67
|
+
|
|
68
|
+
| Export | Description |
|
|
69
|
+
|--------|-------------|
|
|
70
|
+
| `HandStateManager` | Main state machine — `processLandmarks(landmarks)` → `{ state, rotation }` |
|
|
71
|
+
| `HandGestureDetector` | Low-level gesture detection |
|
|
72
|
+
| `HAND_STATES` | State constants (`open`, `closed`, `swipe_next`, …) |
|
|
73
|
+
| `LANDMARKS` | MediaPipe landmark indices |
|
|
74
|
+
| `HAND_CONNECTIONS` | Landmark pairs for debug drawing |
|
|
75
|
+
| `DEFAULT_CONFIG` | Default configuration object |
|
|
76
|
+
| `createHandLandmarker` | MediaPipe setup with GPU→CPU fallback |
|
|
77
|
+
|
|
78
|
+
## Hand states
|
|
79
|
+
|
|
80
|
+
- `not_detected` — no hand in frame
|
|
81
|
+
- `waiting` — hand lost for extended period
|
|
82
|
+
- `starting` — cooldown after re-detection
|
|
83
|
+
- `open` — open palm (zoom)
|
|
84
|
+
- `closed` — closed fist
|
|
85
|
+
- `pointing` — index finger extended
|
|
86
|
+
- `flipping` — middle finger gesture
|
|
87
|
+
- `swipe_next` / `swipe_previous` — horizontal swipe while pointing
|
package/package.json
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "hand-guest-control",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Hand gesture detection and state management using MediaPipe landmarks",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"author": "HoloLab",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"keywords": [
|
|
9
|
+
"hand-gesture",
|
|
10
|
+
"mediapipe",
|
|
11
|
+
"hand-tracking",
|
|
12
|
+
"gesture-control",
|
|
13
|
+
"hand-landmarks"
|
|
14
|
+
],
|
|
15
|
+
"sideEffects": false,
|
|
16
|
+
"exports": {
|
|
17
|
+
".": "./src/index.js",
|
|
18
|
+
"./mediapipe": "./src/mediapipe.js"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"src",
|
|
22
|
+
"LICENSE",
|
|
23
|
+
"README.md"
|
|
24
|
+
],
|
|
25
|
+
"scripts": {
|
|
26
|
+
"test": "node --test test/*.test.js",
|
|
27
|
+
"prepublishOnly": "npm test",
|
|
28
|
+
"demo": "vite",
|
|
29
|
+
"demo:build": "vite build"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@mediapipe/tasks-vision": "^0.10.0",
|
|
33
|
+
"vite": "^7.0.0"
|
|
34
|
+
},
|
|
35
|
+
"peerDependencies": {
|
|
36
|
+
"@mediapipe/tasks-vision": "^0.10.0"
|
|
37
|
+
},
|
|
38
|
+
"peerDependenciesMeta": {
|
|
39
|
+
"@mediapipe/tasks-vision": {
|
|
40
|
+
"optional": true
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { LANDMARKS } from './constants.js';
|
|
2
|
+
|
|
3
|
+
export class HandGestureDetector {
|
|
4
|
+
constructor(config) {
|
|
5
|
+
this.config = config;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
static getDistance(p1, p2) {
|
|
9
|
+
const dx = p1.x - p2.x;
|
|
10
|
+
const dy = p1.y - p2.y;
|
|
11
|
+
return Math.sqrt(dx * dx + dy * dy);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
static getAngle(p1, p2, p3) {
|
|
15
|
+
const v1x = p2.x - p1.x;
|
|
16
|
+
const v1y = p2.y - p1.y;
|
|
17
|
+
const v2x = p3.x - p2.x;
|
|
18
|
+
const v2y = p3.y - p2.y;
|
|
19
|
+
const dot = v1x * v2x + v1y * v2y;
|
|
20
|
+
const det = v1x * v2y - v1y * v2x;
|
|
21
|
+
let angle = (Math.atan2(det, dot) * 180) / Math.PI;
|
|
22
|
+
return angle < 0 ? angle + 360 : angle;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
computeDistances(landmarks) {
|
|
26
|
+
const wrist = landmarks[LANDMARKS.WRIST];
|
|
27
|
+
const tips = [
|
|
28
|
+
LANDMARKS.THUMB_TIP,
|
|
29
|
+
LANDMARKS.INDEX_TIP,
|
|
30
|
+
LANDMARKS.MIDDLE_TIP,
|
|
31
|
+
LANDMARKS.RING_TIP,
|
|
32
|
+
LANDMARKS.PINKY_TIP
|
|
33
|
+
];
|
|
34
|
+
|
|
35
|
+
const distances = {};
|
|
36
|
+
const fingerNames = ['Thumb', 'Index', 'Middle', 'Ring', 'Pinky'];
|
|
37
|
+
const adjacentNames = ['thumbToIndex', 'indexToMiddle', 'middleToRing', 'ringToPinky'];
|
|
38
|
+
|
|
39
|
+
tips.forEach((tip, i) => {
|
|
40
|
+
distances[`palmTo${fingerNames[i]}`] = HandGestureDetector.getDistance(wrist, landmarks[tip]);
|
|
41
|
+
|
|
42
|
+
if (i > 0) {
|
|
43
|
+
distances[adjacentNames[i - 1]] = HandGestureDetector.getDistance(
|
|
44
|
+
landmarks[tips[i - 1]],
|
|
45
|
+
landmarks[tip]
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
return distances;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
checkOpenHand(distances, histories, indices) {
|
|
54
|
+
const handSize = (distances.palmToThumb + distances.palmToMiddle) / 2 || 0.15;
|
|
55
|
+
const normalized = {
|
|
56
|
+
thumb: distances.palmToThumb / handSize,
|
|
57
|
+
index: distances.palmToIndex / handSize,
|
|
58
|
+
middle: distances.palmToMiddle / handSize,
|
|
59
|
+
ring: distances.palmToRing / handSize,
|
|
60
|
+
pinky: distances.palmToPinky / handSize,
|
|
61
|
+
thumbToIndex: distances.thumbToIndex / handSize
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
if (this.config.debug) {
|
|
65
|
+
console.log(`Hand state check (open): thumb=${normalized.thumb.toFixed(2)}, ` +
|
|
66
|
+
`index=${normalized.index.toFixed(2)}, middle=${normalized.middle.toFixed(2)}, ` +
|
|
67
|
+
`ring=${normalized.ring.toFixed(2)}, pinky=${normalized.pinky.toFixed(2)}, ` +
|
|
68
|
+
`thumbToIndex=${normalized.thumbToIndex.toFixed(2)}`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const fingers = ['index', 'middle', 'ring', 'pinky'];
|
|
72
|
+
const extended = fingers.filter((finger) => normalized[finger] > normalized.thumb).length;
|
|
73
|
+
|
|
74
|
+
const isCandidate = extended >= this.config.openHandThresholds.minExtendedFingers;
|
|
75
|
+
histories.open[indices.open] = isCandidate;
|
|
76
|
+
indices.open = (indices.open + 1) % this.config.minOpenConfidence;
|
|
77
|
+
|
|
78
|
+
return histories.open.filter(Boolean).length >= Math.ceil(this.config.minOpenConfidence * 0.7);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
checkClosedHand(distances, histories, indices) {
|
|
82
|
+
const handSize = (distances.palmToThumb + distances.palmToMiddle) / 2 || 0.15;
|
|
83
|
+
const normalized = {
|
|
84
|
+
thumb: distances.palmToThumb / handSize,
|
|
85
|
+
index: distances.palmToIndex / handSize,
|
|
86
|
+
middle: distances.palmToMiddle / handSize,
|
|
87
|
+
ring: distances.palmToRing / handSize,
|
|
88
|
+
pinky: distances.palmToPinky / handSize,
|
|
89
|
+
thumbToIndex: distances.thumbToIndex / handSize
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
if (this.config.debug) {
|
|
93
|
+
console.log(`Hand state check (closed): thumb=${normalized.thumb.toFixed(2)}, ` +
|
|
94
|
+
`index=${normalized.index.toFixed(2)}, middle=${normalized.middle.toFixed(2)}, ` +
|
|
95
|
+
`ring=${normalized.ring.toFixed(2)}, pinky=${normalized.pinky.toFixed(2)}, ` +
|
|
96
|
+
`thumbToIndex=${normalized.thumbToIndex.toFixed(2)}`);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const fingers = ['index', 'middle', 'ring', 'pinky'];
|
|
100
|
+
const closedFingers = fingers.filter((finger) => normalized[finger] < normalized.thumb).length;
|
|
101
|
+
|
|
102
|
+
const isCandidate = closedFingers >= this.config.openHandThresholds.minExtendedFingers;
|
|
103
|
+
histories.closed[indices.closed] = isCandidate;
|
|
104
|
+
indices.closed = (indices.closed + 1) % this.config.minClosedConfidence;
|
|
105
|
+
|
|
106
|
+
return histories.closed.filter(Boolean).length >= Math.ceil(this.config.minClosedConfidence * 0.7);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
isPointing(distances, histories, indices) {
|
|
110
|
+
const handSize = distances.palmToIndex || 0.15;
|
|
111
|
+
const normalized = {
|
|
112
|
+
index: distances.palmToIndex / handSize,
|
|
113
|
+
middle: distances.palmToMiddle / handSize,
|
|
114
|
+
ring: distances.palmToRing / handSize,
|
|
115
|
+
pinky: distances.palmToPinky / handSize,
|
|
116
|
+
thumb: distances.palmToThumb / handSize
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
const otherFingers = [normalized.middle, normalized.ring, normalized.pinky, normalized.thumb];
|
|
120
|
+
const isIndexExtended = 0.5 > Math.max(...otherFingers) && normalized.thumb < 0.7;
|
|
121
|
+
|
|
122
|
+
histories.pointing[indices.pointing] = isIndexExtended;
|
|
123
|
+
indices.pointing = (indices.pointing + 1) % this.config.minPointingConfidence;
|
|
124
|
+
|
|
125
|
+
return histories.pointing.filter(Boolean).length >= Math.ceil(this.config.minPointingConfidence * 0.9);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
isFlipping(distances, histories, indices) {
|
|
129
|
+
const handSize = distances.palmToIndex || 0.15;
|
|
130
|
+
const normalized = {
|
|
131
|
+
index: distances.palmToIndex / handSize,
|
|
132
|
+
middle: distances.palmToMiddle / handSize,
|
|
133
|
+
ring: distances.palmToRing / handSize,
|
|
134
|
+
pinky: distances.palmToPinky / handSize,
|
|
135
|
+
thumb: distances.palmToThumb / handSize
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
if (this.config.debug) {
|
|
139
|
+
console.log(`Hand state check (flip): index=${normalized.index.toFixed(2)}, ` +
|
|
140
|
+
`middle=${normalized.middle.toFixed(2)}, ring=${normalized.ring.toFixed(2)}, ` +
|
|
141
|
+
`pinky=${normalized.pinky.toFixed(2)}, thumb=${normalized.thumb.toFixed(2)}`);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const isFlippingGesture = normalized.middle > 0.8 &&
|
|
145
|
+
Math.max(normalized.ring, normalized.pinky, normalized.thumb) < 0.5;
|
|
146
|
+
|
|
147
|
+
histories.flipping[indices.flipping] = isFlippingGesture;
|
|
148
|
+
indices.flipping = (indices.flipping + 1) % this.config.minFlippingConfidence;
|
|
149
|
+
|
|
150
|
+
return histories.flipping.filter(Boolean).length >= Math.ceil(this.config.minFlippingConfidence * 0.9);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
checkSwipeNext(landmarks, distances, histories, indices, pointingCount, lastActionTime) {
|
|
154
|
+
if (
|
|
155
|
+
!this.isPointing(distances, histories, indices) ||
|
|
156
|
+
!landmarks ||
|
|
157
|
+
histories.landmark0.filter(Boolean).length < 6 ||
|
|
158
|
+
pointingCount < this.config.minPointingCount ||
|
|
159
|
+
Date.now() - lastActionTime < 2000
|
|
160
|
+
) {
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const entries = histories.landmark0.filter(Boolean);
|
|
165
|
+
const xPositions = entries.map((e) => e.x);
|
|
166
|
+
const xRange = Math.max(...xPositions) - Math.min(...xPositions);
|
|
167
|
+
const firstX = entries[0].x;
|
|
168
|
+
const lastX = entries[entries.length - 1].x;
|
|
169
|
+
|
|
170
|
+
return xRange > 0.03 && lastX - firstX > 0.03;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
checkSwipePrevious(landmarks, distances, histories, indices, pointingCount, lastActionTime) {
|
|
174
|
+
if (
|
|
175
|
+
!this.isPointing(distances, histories, indices) ||
|
|
176
|
+
!landmarks ||
|
|
177
|
+
histories.landmark0.filter(Boolean).length < 6 ||
|
|
178
|
+
pointingCount < this.config.minPointingCount ||
|
|
179
|
+
Date.now() - lastActionTime < 2000
|
|
180
|
+
) {
|
|
181
|
+
return false;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const entries = histories.landmark0.filter(Boolean);
|
|
185
|
+
const xPositions = entries.map((e) => e.x);
|
|
186
|
+
const xRange = Math.max(...xPositions) - Math.min(...xPositions);
|
|
187
|
+
const firstX = entries[0].x;
|
|
188
|
+
const lastX = entries[entries.length - 1].x;
|
|
189
|
+
|
|
190
|
+
return xRange > 0.03 && firstX - lastX > 0.03;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { HAND_STATES, LANDMARKS, DEFAULT_CONFIG } from './constants.js';
|
|
2
|
+
import { HandGestureDetector } from './HandGestureDetector.js';
|
|
3
|
+
|
|
4
|
+
export class HandStateManager {
|
|
5
|
+
constructor(config = {}) {
|
|
6
|
+
this.config = { ...DEFAULT_CONFIG, ...config };
|
|
7
|
+
this.gestureDetector = new HandGestureDetector(this.config);
|
|
8
|
+
|
|
9
|
+
this.initializeState();
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
initializeState() {
|
|
13
|
+
this.histories = {
|
|
14
|
+
centroid: new Array(this.config.maxCentroidHistorySize).fill(null),
|
|
15
|
+
landmark0: new Array(this.config.maxHistorySize).fill(null),
|
|
16
|
+
open: new Array(this.config.minOpenConfidence).fill(false),
|
|
17
|
+
pointing: new Array(this.config.minPointingConfidence).fill(false),
|
|
18
|
+
flipping: new Array(this.config.minFlippingConfidence).fill(false),
|
|
19
|
+
closed: new Array(this.config.minClosedConfidence).fill(false)
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
this.indices = {
|
|
23
|
+
history: 0,
|
|
24
|
+
centroid: 0,
|
|
25
|
+
open: 0,
|
|
26
|
+
pointing: 0,
|
|
27
|
+
flipping: 0,
|
|
28
|
+
closed: 0
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
this.resetTrackingState();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
resetTrackingState() {
|
|
35
|
+
this.prevLandmark0 = null;
|
|
36
|
+
this.lastActionTime = 0;
|
|
37
|
+
this.pointingCount = 0;
|
|
38
|
+
this.flippingCount = 0;
|
|
39
|
+
this.detectionPausedUntil = 0;
|
|
40
|
+
this.noDetectionStartTime = 0;
|
|
41
|
+
this.lastDetectionTime = 0;
|
|
42
|
+
this.lastState = null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
calculateCentroid(landmarks, now) {
|
|
46
|
+
if (!landmarks?.length) {
|
|
47
|
+
return { x: 0, y: 0 };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const landmark0 = landmarks[LANDMARKS.WRIST] || landmarks[0];
|
|
51
|
+
this.histories.landmark0[this.indices.history] = {
|
|
52
|
+
x: landmark0.x,
|
|
53
|
+
y: landmark0.y,
|
|
54
|
+
time: now
|
|
55
|
+
};
|
|
56
|
+
this.indices.history = (this.indices.history + 1) % this.config.maxHistorySize;
|
|
57
|
+
|
|
58
|
+
const validPoints = this.histories.landmark0.filter(Boolean);
|
|
59
|
+
if (!validPoints.length) {
|
|
60
|
+
return { x: landmark0.x, y: landmark0.y };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const sum = validPoints.reduce(
|
|
64
|
+
(acc, p) => ({ x: acc.x + p.x, y: acc.y + p.y }),
|
|
65
|
+
{ x: 0, y: 0 }
|
|
66
|
+
);
|
|
67
|
+
|
|
68
|
+
return {
|
|
69
|
+
x: sum.x / validPoints.length,
|
|
70
|
+
y: sum.y / validPoints.length
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
getRotation(landmarks, centroid) {
|
|
75
|
+
if (!landmarks?.[LANDMARKS.MIDDLE_TIP]) {
|
|
76
|
+
return [0, 0, 0];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const handSize = HandGestureDetector.getDistance(
|
|
80
|
+
landmarks[LANDMARKS.WRIST],
|
|
81
|
+
landmarks[LANDMARKS.THUMB_TIP]
|
|
82
|
+
) || 0.15;
|
|
83
|
+
|
|
84
|
+
const scaleFactor = 0.15 / handSize;
|
|
85
|
+
const delta = this.prevLandmark0 ? {
|
|
86
|
+
x: (centroid.x - this.prevLandmark0.x) * scaleFactor,
|
|
87
|
+
y: (centroid.y - this.prevLandmark0.y) * scaleFactor
|
|
88
|
+
} : { x: 0, y: 0 };
|
|
89
|
+
|
|
90
|
+
this.prevLandmark0 = { x: centroid.x, y: centroid.y };
|
|
91
|
+
|
|
92
|
+
return [
|
|
93
|
+
delta.y * this.config.rotationSensitivity,
|
|
94
|
+
delta.x * this.config.rotationSensitivity,
|
|
95
|
+
0
|
|
96
|
+
];
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
handleNoDetection(now) {
|
|
100
|
+
this.pointingCount = 0;
|
|
101
|
+
this.flippingCount = 0;
|
|
102
|
+
|
|
103
|
+
if (!this.noDetectionStartTime) {
|
|
104
|
+
this.noDetectionStartTime = now;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const noDetectionDuration = now - this.noDetectionStartTime;
|
|
108
|
+
|
|
109
|
+
if (noDetectionDuration < this.config.detectionTolerance) {
|
|
110
|
+
return { state: this.lastState || HAND_STATES.NOT_DETECTED, rotation: [0, 0, 0] };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (noDetectionDuration >= this.config.waitingTimeout) {
|
|
114
|
+
this.lastState = HAND_STATES.WAITING;
|
|
115
|
+
if (this.config.debug) {
|
|
116
|
+
console.log(`Transitioned to WAITING after ${this.config.waitingTimeout / 1000}s`);
|
|
117
|
+
}
|
|
118
|
+
return { state: HAND_STATES.WAITING, rotation: [0, 0, 0] };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
this.lastState = HAND_STATES.NOT_DETECTED;
|
|
122
|
+
if (this.config.debug) {
|
|
123
|
+
console.log(`Transitioned to NOT_DETECTED after ${this.config.detectionTolerance / 1000}s`);
|
|
124
|
+
}
|
|
125
|
+
return { state: HAND_STATES.NOT_DETECTED, rotation: [0, 0, 0] };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
handleDetectionReconnection(now) {
|
|
129
|
+
const isWaitingOrNotDetected = [HAND_STATES.WAITING, HAND_STATES.NOT_DETECTED].includes(this.lastState);
|
|
130
|
+
const isReconnection = ![HAND_STATES.WAITING, HAND_STATES.NOT_DETECTED, HAND_STATES.STARTING].includes(this.lastState) &&
|
|
131
|
+
now - this.lastDetectionTime <= this.config.detectionTolerance;
|
|
132
|
+
|
|
133
|
+
if (isReconnection) {
|
|
134
|
+
if (this.config.debug) {
|
|
135
|
+
console.log(`Short reconnection (${(now - this.lastDetectionTime) / 1000}s), continuing with last state: ${this.lastState}`);
|
|
136
|
+
}
|
|
137
|
+
} else if (isWaitingOrNotDetected) {
|
|
138
|
+
this.detectionPausedUntil = now + this.config.startingDelay;
|
|
139
|
+
this.noDetectionStartTime = 0;
|
|
140
|
+
this.lastState = HAND_STATES.STARTING;
|
|
141
|
+
return { state: HAND_STATES.STARTING, rotation: [0, 0, 0] };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
determineHandState(distances) {
|
|
148
|
+
if (this.gestureDetector.checkSwipeNext(
|
|
149
|
+
this.histories.landmark0, distances, this.histories, this.indices,
|
|
150
|
+
this.pointingCount, this.lastActionTime
|
|
151
|
+
)) {
|
|
152
|
+
this.resetSwipeState();
|
|
153
|
+
return HAND_STATES.SWIPE_NEXT;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (this.gestureDetector.checkSwipePrevious(
|
|
157
|
+
this.histories.landmark0, distances, this.histories, this.indices,
|
|
158
|
+
this.pointingCount, this.lastActionTime
|
|
159
|
+
)) {
|
|
160
|
+
this.resetSwipeState();
|
|
161
|
+
return HAND_STATES.SWIPE_PREVIOUS;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (this.gestureDetector.isFlipping(distances, this.histories, this.indices)) {
|
|
165
|
+
return HAND_STATES.FLIPPING;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (this.gestureDetector.checkClosedHand(distances, this.histories, this.indices)) {
|
|
169
|
+
return HAND_STATES.CLOSED;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
if (this.gestureDetector.checkOpenHand(distances, this.histories, this.indices)) {
|
|
173
|
+
return HAND_STATES.OPEN;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (this.gestureDetector.isPointing(distances, this.histories, this.indices)) {
|
|
177
|
+
return HAND_STATES.POINTING;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
return HAND_STATES.CLOSED;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
resetSwipeState() {
|
|
184
|
+
this.histories.landmark0.fill(null);
|
|
185
|
+
this.indices.history = 0;
|
|
186
|
+
this.lastActionTime = Date.now();
|
|
187
|
+
this.pointingCount = 0;
|
|
188
|
+
this.flippingCount = 0;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
validateStateTransition(newState) {
|
|
192
|
+
const validTransitionStates = [HAND_STATES.OPEN, HAND_STATES.POINTING, HAND_STATES.CLOSED, HAND_STATES.FLIPPING];
|
|
193
|
+
|
|
194
|
+
if (newState === this.lastState || !validTransitionStates.includes(newState)) {
|
|
195
|
+
return newState;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const historyKeys = {
|
|
199
|
+
[HAND_STATES.OPEN]: 'open',
|
|
200
|
+
[HAND_STATES.POINTING]: 'pointing',
|
|
201
|
+
[HAND_STATES.CLOSED]: 'closed',
|
|
202
|
+
[HAND_STATES.FLIPPING]: 'flipping'
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
const historyKey = historyKeys[newState];
|
|
206
|
+
if (!historyKey) return newState;
|
|
207
|
+
|
|
208
|
+
const requiredConfidence = this.config[`min${historyKey.charAt(0).toUpperCase() + historyKey.slice(1)}Confidence`];
|
|
209
|
+
const actualConfidence = this.histories[historyKey].filter(Boolean).length;
|
|
210
|
+
|
|
211
|
+
if (actualConfidence < requiredConfidence * 0.9) {
|
|
212
|
+
return this.lastState;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
return newState;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
clearAllHistory() {
|
|
219
|
+
Object.values(this.histories).forEach((history) => history.fill(null));
|
|
220
|
+
Object.keys(this.indices).forEach((key) => { this.indices[key] = 0; });
|
|
221
|
+
this.resetTrackingState();
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
processLandmarks(landmarks) {
|
|
225
|
+
const now = Date.now();
|
|
226
|
+
|
|
227
|
+
if (this.detectionPausedUntil > now) {
|
|
228
|
+
if (this.config.debug) {
|
|
229
|
+
console.log(`In STARTING state until ${new Date(this.detectionPausedUntil).toLocaleTimeString()}`);
|
|
230
|
+
}
|
|
231
|
+
return { state: HAND_STATES.STARTING, rotation: [0, 0, 0] };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
if (!landmarks?.[LANDMARKS.PINKY_TIP]) {
|
|
235
|
+
return this.handleNoDetection(now);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
this.lastDetectionTime = now;
|
|
239
|
+
const reconnectionResult = this.handleDetectionReconnection(now);
|
|
240
|
+
if (reconnectionResult) {
|
|
241
|
+
return reconnectionResult;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
this.noDetectionStartTime = 0;
|
|
245
|
+
this.detectionPausedUntil = 0;
|
|
246
|
+
|
|
247
|
+
const distances = this.gestureDetector.computeDistances(landmarks);
|
|
248
|
+
const centroid = this.calculateCentroid(landmarks, now);
|
|
249
|
+
|
|
250
|
+
this.histories.centroid[this.indices.centroid] = { x: centroid.x, y: centroid.y, time: now };
|
|
251
|
+
this.indices.centroid = (this.indices.centroid + 1) % this.config.maxCentroidHistorySize;
|
|
252
|
+
|
|
253
|
+
const rotation = this.getRotation(landmarks, centroid);
|
|
254
|
+
|
|
255
|
+
this.pointingCount += this.gestureDetector.isPointing(distances, this.histories, this.indices) ? 1 : 0;
|
|
256
|
+
this.flippingCount += this.gestureDetector.isFlipping(distances, this.histories, this.indices) ? 1 : 0;
|
|
257
|
+
|
|
258
|
+
let newState = this.determineHandState(distances);
|
|
259
|
+
newState = this.validateStateTransition(newState);
|
|
260
|
+
|
|
261
|
+
this.lastState = newState;
|
|
262
|
+
|
|
263
|
+
const rotationDisabledStates = [
|
|
264
|
+
HAND_STATES.POINTING,
|
|
265
|
+
HAND_STATES.SWIPE_NEXT,
|
|
266
|
+
HAND_STATES.SWIPE_PREVIOUS,
|
|
267
|
+
HAND_STATES.FLIPPING
|
|
268
|
+
];
|
|
269
|
+
|
|
270
|
+
if (rotationDisabledStates.includes(newState)) {
|
|
271
|
+
rotation.fill(0);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
return { state: newState, rotation };
|
|
275
|
+
}
|
|
276
|
+
}
|
package/src/constants.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
export const HAND_STATES = {
|
|
2
|
+
NOT_DETECTED: 'not_detected',
|
|
3
|
+
WAITING: 'waiting',
|
|
4
|
+
STARTING: 'starting',
|
|
5
|
+
OPEN: 'open',
|
|
6
|
+
CLOSED: 'closed',
|
|
7
|
+
POINTING: 'pointing',
|
|
8
|
+
FLIPPING: 'flipping',
|
|
9
|
+
SWIPE_NEXT: 'swipe_next',
|
|
10
|
+
SWIPE_PREVIOUS: 'swipe_previous'
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export const LANDMARKS = {
|
|
14
|
+
WRIST: 0,
|
|
15
|
+
THUMB_TIP: 4,
|
|
16
|
+
INDEX_TIP: 8,
|
|
17
|
+
MIDDLE_TIP: 12,
|
|
18
|
+
RING_TIP: 16,
|
|
19
|
+
PINKY_TIP: 20
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export const HAND_CONNECTIONS = [
|
|
23
|
+
[0, 1], [1, 2], [2, 3], [3, 4],
|
|
24
|
+
[0, 5], [5, 6], [6, 7], [7, 8],
|
|
25
|
+
[0, 9], [9, 10], [10, 11], [11, 12],
|
|
26
|
+
[0, 13], [13, 14], [14, 15], [15, 16],
|
|
27
|
+
[0, 17], [17, 18], [18, 19], [19, 20],
|
|
28
|
+
[5, 9], [9, 13], [13, 17]
|
|
29
|
+
];
|
|
30
|
+
|
|
31
|
+
export const DEFAULT_CONFIG = {
|
|
32
|
+
maxHistorySize: 10,
|
|
33
|
+
maxCentroidHistorySize: 10,
|
|
34
|
+
rotationSensitivity: 4,
|
|
35
|
+
detectionTolerance: 2000,
|
|
36
|
+
startingDelay: 1000,
|
|
37
|
+
waitingTimeout: 3000,
|
|
38
|
+
minOpenConfidence: 5,
|
|
39
|
+
minPointingConfidence: 25,
|
|
40
|
+
minFlippingConfidence: 25,
|
|
41
|
+
minClosedConfidence: 5,
|
|
42
|
+
minPointingCount: 5,
|
|
43
|
+
pointingThreshold: 0.3,
|
|
44
|
+
openHandThresholds: {
|
|
45
|
+
fingerSpread: 0.2,
|
|
46
|
+
indexToMiddle: 0.15,
|
|
47
|
+
minExtendedFingers: 4,
|
|
48
|
+
maxExtendedFingers: 6,
|
|
49
|
+
middleAngle: 50
|
|
50
|
+
},
|
|
51
|
+
debug: false
|
|
52
|
+
};
|
package/src/index.js
ADDED
package/src/mediapipe.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { HandLandmarker, FilesetResolver } from '@mediapipe/tasks-vision';
|
|
2
|
+
|
|
3
|
+
export const DEFAULT_MEDIAPIPE_CONFIG = {
|
|
4
|
+
wasmPath: 'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.0/wasm',
|
|
5
|
+
modelPath: 'https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task'
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
export const DEFAULT_DETECTION_CONFIG = {
|
|
9
|
+
runningMode: 'VIDEO',
|
|
10
|
+
numHands: 1,
|
|
11
|
+
minHandDetectionConfidence: 0.6,
|
|
12
|
+
minHandPresenceConfidence: 0.6,
|
|
13
|
+
minTrackingConfidence: 0.5
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Create a MediaPipe HandLandmarker with GPU fallback to CPU.
|
|
18
|
+
* @param {object} [options]
|
|
19
|
+
* @param {string} [options.wasmPath]
|
|
20
|
+
* @param {string} [options.modelPath]
|
|
21
|
+
* @param {import('@mediapipe/tasks-vision').RunningMode} [options.runningMode]
|
|
22
|
+
* @param {number} [options.numHands]
|
|
23
|
+
* @param {number} [options.minHandDetectionConfidence]
|
|
24
|
+
* @param {number} [options.minHandPresenceConfidence]
|
|
25
|
+
* @param {number} [options.minTrackingConfidence]
|
|
26
|
+
*/
|
|
27
|
+
export async function createHandLandmarker(options = {}) {
|
|
28
|
+
const config = {
|
|
29
|
+
...DEFAULT_MEDIAPIPE_CONFIG,
|
|
30
|
+
...DEFAULT_DETECTION_CONFIG,
|
|
31
|
+
...options
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const vision = await FilesetResolver.forVisionTasks(config.wasmPath);
|
|
35
|
+
|
|
36
|
+
const landmarkerOptions = {
|
|
37
|
+
baseOptions: {
|
|
38
|
+
modelAssetPath: config.modelPath,
|
|
39
|
+
delegate: 'GPU'
|
|
40
|
+
},
|
|
41
|
+
runningMode: config.runningMode,
|
|
42
|
+
numHands: config.numHands,
|
|
43
|
+
minHandDetectionConfidence: config.minHandDetectionConfidence,
|
|
44
|
+
minHandPresenceConfidence: config.minHandPresenceConfidence,
|
|
45
|
+
minTrackingConfidence: config.minTrackingConfidence
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
try {
|
|
49
|
+
return await HandLandmarker.createFromOptions(vision, landmarkerOptions);
|
|
50
|
+
} catch (gpuError) {
|
|
51
|
+
console.warn('GPU delegate failed, falling back to CPU:', gpuError);
|
|
52
|
+
return HandLandmarker.createFromOptions(vision, {
|
|
53
|
+
...landmarkerOptions,
|
|
54
|
+
baseOptions: {
|
|
55
|
+
modelAssetPath: config.modelPath
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
}
|