forked from pjbelo/mediapipe-js-demos
-
Notifications
You must be signed in to change notification settings - Fork 1
/
hands.js
174 lines (174 loc) · 6.54 KB
/
hands.js
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
import DeviceDetector from "https://cdn.skypack.dev/device-detector-js@2.2.10";
const mpHands = window;
const drawingUtils = window;
const controls = window;
const controls3d = window;
// Usage: testSupport({client?: string, os?: string}[])
// Client and os are regular expressions.
// See: https://cdn.jsdelivr.net/npm/device-detector-js@2.2.10/README.md for
// legal values for client and os
testSupport([
{ client: 'Chrome' },
]);
function testSupport(supportedDevices) {
const deviceDetector = new DeviceDetector();
const detectedDevice = deviceDetector.parse(navigator.userAgent);
let isSupported = false;
for (const device of supportedDevices) {
if (device.client !== undefined) {
const re = new RegExp(`^${device.client}$`);
if (!re.test(detectedDevice.client.name)) {
continue;
}
}
if (device.os !== undefined) {
const re = new RegExp(`^${device.os}$`);
if (!re.test(detectedDevice.os.name)) {
continue;
}
}
isSupported = true;
break;
}
if (!isSupported) {
alert(`This demo, running on ${detectedDevice.client.name}/${detectedDevice.os.name}, ` +
`is not well supported at this time, continue at your own risk.`);
}
}
// Our input frames will come from here.
const videoElement = document.getElementsByClassName('input_video')[0];
const canvasElement = document.getElementsByClassName('output_canvas')[0];
const controlsElement = document.getElementsByClassName('control-panel')[0];
const canvasCtx = canvasElement.getContext('2d');
const config = { locateFile: (file) => {
return `https://cdn.jsdelivr.net/npm/@mediapipe/hands@${mpHands.VERSION}/${file}`;
} };
// We'll add this to our control panel later, but we'll save it here so we can
// call tick() each time the graph runs.
const fpsControl = new controls.FPS();
// Optimization: Turn off animated spinner after its hiding animation is done.
const spinner = document.querySelector('.loading');
spinner.ontransitionend = () => {
spinner.style.display = 'none';
};
const landmarkContainer = document.getElementsByClassName('landmark-grid-container')[0];
const grid = new controls3d.LandmarkGrid(landmarkContainer, {
connectionColor: 0xCCCCCC,
definedColors: [{ name: 'Left', value: 0xffa500 }, { name: 'Right', value: 0x00ffff }],
range: 0.2,
fitToGrid: false,
labelSuffix: 'm',
landmarkSize: 2,
numCellsPerAxis: 4,
showHidden: false,
centered: false,
});
function onResults(results) {
// Hide the spinner.
document.body.classList.add('loaded');
// Update the frame rate.
fpsControl.tick();
// Draw the overlays.
canvasCtx.save();
canvasCtx.clearRect(0, 0, canvasElement.width, canvasElement.height);
canvasCtx.drawImage(results.image, 0, 0, canvasElement.width, canvasElement.height);
if (results.multiHandLandmarks && results.multiHandedness) {
for (let index = 0; index < results.multiHandLandmarks.length; index++) {
const classification = results.multiHandedness[index];
const isRightHand = classification.label === 'Right';
const landmarks = results.multiHandLandmarks[index];
drawingUtils.drawConnectors(canvasCtx, landmarks, mpHands.HAND_CONNECTIONS, { color: isRightHand ? '#00FF00' : '#FF0000' });
drawingUtils.drawLandmarks(canvasCtx, landmarks, {
color: isRightHand ? '#00FF00' : '#FF0000',
fillColor: isRightHand ? '#FF0000' : '#00FF00',
radius: (data) => {
return drawingUtils.lerp(data.from.z, -0.15, .1, 10, 1);
}
});
}
}
canvasCtx.restore();
if (results.multiHandWorldLandmarks) {
// We only get to call updateLandmarks once, so we need to cook the data to
// fit. The landmarks just merge, but the connections need to be offset.
const landmarks = results.multiHandWorldLandmarks.reduce((prev, current) => [...prev, ...current], []);
const colors = [];
let connections = [];
for (let loop = 0; loop < results.multiHandWorldLandmarks.length; ++loop) {
const offset = loop * mpHands.HAND_CONNECTIONS.length;
const offsetConnections = mpHands.HAND_CONNECTIONS.map((connection) => [connection[0] + offset, connection[1] + offset]);
connections = connections.concat(offsetConnections);
const classification = results.multiHandedness[loop];
colors.push({
list: offsetConnections.map((unused, i) => i + offset),
color: classification.label,
});
}
grid.updateLandmarks(landmarks, connections, colors);
}
else {
grid.updateLandmarks([]);
}
}
const hands = new mpHands.Hands(config);
hands.onResults(onResults);
// Present a control panel through which the user can manipulate the solution
// options.
new controls
.ControlPanel(controlsElement, {
selfieMode: true,
maxNumHands: 2,
modelComplexity: 1,
minDetectionConfidence: 0.5,
minTrackingConfidence: 0.5
})
.add([
new controls.StaticText({ title: 'MediaPipe Hands' }),
fpsControl,
new controls.Toggle({ title: 'Selfie Mode', field: 'selfieMode' }),
new controls.SourcePicker({
onFrame: async (input, size) => {
const aspect = size.height / size.width;
let width, height;
if (window.innerWidth > window.innerHeight) {
height = window.innerHeight;
width = height / aspect;
}
else {
width = window.innerWidth;
height = width * aspect;
}
canvasElement.width = width;
canvasElement.height = height;
await hands.send({ image: input });
},
}),
new controls.Slider({
title: 'Max Number of Hands',
field: 'maxNumHands',
range: [1, 4],
step: 1
}),
new controls.Slider({
title: 'Model Complexity',
field: 'modelComplexity',
discrete: ['Lite', 'Full'],
}),
new controls.Slider({
title: 'Min Detection Confidence',
field: 'minDetectionConfidence',
range: [0, 1],
step: 0.01
}),
new controls.Slider({
title: 'Min Tracking Confidence',
field: 'minTrackingConfidence',
range: [0, 1],
step: 0.01
}),
])
.on(x => {
const options = x;
videoElement.classList.toggle('selfie', options.selfieMode);
hands.setOptions(options);
});