forked from tensorflow/tfjs-models
/
index.js
187 lines (152 loc) · 5.29 KB
/
index.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
175
176
177
178
179
180
181
182
183
184
185
186
187
/**
* @license
* Copyright 2021 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
import '@tensorflow/tfjs-backend-webgl';
import * as mpHands from '@mediapipe/hands';
import * as tfjsWasm from '@tensorflow/tfjs-backend-wasm';
tfjsWasm.setWasmPaths(
`https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${
tfjsWasm.version_wasm}/dist/`);
import * as handdetection from '@tensorflow-models/hand-pose-detection';
import {Camera} from './camera';
import {setupDatGui} from './option_panel';
import {STATE} from './shared/params';
import {setupStats} from './shared/stats_panel';
import {setBackendAndEnvFlags} from './shared/util';
let detector, camera, stats;
let startInferenceTime, numInferences = 0;
let inferenceTimeSum = 0, lastPanelUpdate = 0;
let rafId;
async function createDetector() {
switch (STATE.model) {
case handdetection.SupportedModels.MediaPipeHands:
const runtime = STATE.backend.split('-')[0];
if (runtime === 'mediapipe') {
return handdetection.createDetector(STATE.model, {
runtime,
modelType: STATE.modelConfig.type,
maxHands: STATE.modelConfig.maxNumHands,
solutionPath: `https://cdn.jsdelivr.net/npm/@mediapipe/hands@${mpHands.VERSION}`
});
} else if (runtime === 'tfjs') {
return handdetection.createDetector(STATE.model, {
runtime,
modelType: STATE.modelConfig.type,
maxHands: STATE.modelConfig.maxNumHands
});
}
}
}
async function checkGuiUpdate() {
if (STATE.isTargetFPSChanged || STATE.isSizeOptionChanged) {
camera = await Camera.setupCamera(STATE.camera);
STATE.isTargetFPSChanged = false;
STATE.isSizeOptionChanged = false;
}
if (STATE.isModelChanged || STATE.isFlagChanged || STATE.isBackendChanged) {
STATE.isModelChanged = true;
window.cancelAnimationFrame(rafId);
if (detector != null) {
detector.dispose();
}
if (STATE.isFlagChanged || STATE.isBackendChanged) {
await setBackendAndEnvFlags(STATE.flags, STATE.backend);
}
try {
detector = await createDetector(STATE.model);
} catch (error) {
detector = null;
alert(error);
}
STATE.isFlagChanged = false;
STATE.isBackendChanged = false;
STATE.isModelChanged = false;
}
}
function beginEstimateHandsStats() {
startInferenceTime = (performance || Date).now();
}
function endEstimateHandsStats() {
const endInferenceTime = (performance || Date).now();
inferenceTimeSum += endInferenceTime - startInferenceTime;
++numInferences;
const panelUpdateMilliseconds = 1000;
if (endInferenceTime - lastPanelUpdate >= panelUpdateMilliseconds) {
const averageInferenceTime = inferenceTimeSum / numInferences;
inferenceTimeSum = 0;
numInferences = 0;
stats.customFpsPanel.update(
1000.0 / averageInferenceTime, 120 /* maxValue */);
lastPanelUpdate = endInferenceTime;
}
}
async function renderResult() {
if (camera.video.readyState < 2) {
await new Promise((resolve) => {
camera.video.onloadeddata = () => {
resolve(video);
};
});
}
let hands = null;
// Detector can be null if initialization failed (for example when loading
// from a URL that does not exist).
if (detector != null) {
// FPS only counts the time it takes to finish estimateHands.
beginEstimateHandsStats();
// Detectors can throw errors, for example when using custom URLs that
// contain a model that doesn't provide the expected output.
try {
hands = await detector.estimateHands(
camera.video,
{flipHorizontal: false});
} catch (error) {
detector.dispose();
detector = null;
alert(error);
}
endEstimateHandsStats();
}
camera.drawCtx();
// The null check makes sure the UI is not in the middle of changing to a
// different model. If during model change, the result is from an old model,
// which shouldn't be rendered.
if (hands && hands.length > 0 && !STATE.isModelChanged) {
camera.drawResults(hands);
}
}
async function renderPrediction() {
await checkGuiUpdate();
if (!STATE.isModelChanged) {
await renderResult();
}
rafId = requestAnimationFrame(renderPrediction);
};
async function app() {
// Gui content will change depending on which model is in the query string.
const urlParams = new URLSearchParams(window.location.search);
if (!urlParams.has('model')) {
alert('Cannot find model in the query string.');
return;
}
await setupDatGui(urlParams);
stats = setupStats();
camera = await Camera.setupCamera(STATE.camera);
await setBackendAndEnvFlags(STATE.flags, STATE.backend);
detector = await createDetector();
renderPrediction();
};
app();