-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
260 lines (220 loc) · 7.18 KB
/
index.html
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
<head>
<script src="https://cdn.jsdelivr.net/npm/three@0.117.1/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/scatter-gl@0.0.5/lib/scatter-gl.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/facemesh@0.0.3"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@2.0.0/dist/tf-backend-wasm.js"></script>
<script src="triangulation.js"></script>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lobster&effect=shadow-multiple">
<style>
.canvas-wrapper, #scatter-gl-container {
display: inline-block;
vertical-align: top;
}
.w3-lobster {
font-family: "Lobster", Sans-serif;
}
#scatter-gl-container {
border: solid 1px black;
position: relative;
}
/* center the canvas within its wrapper */
#scatter-gl-container canvas {
transform: translate3d(-50%, -50%, 0);
left: 50%;
top: 50%;
position: absolute;
}
.container {
display: flex;
flex-wrap: wrap;
justify-content: center;
border: solid 10px black;
}
}
</style>
</head>
<body>
<div id="main">
<div class="w3-container w3-lobster">
<p class="w3-xlarge font-effect-shadow-multiple">Face tracker by Ishaan S.</p>
</div>
<div class="container" width='100%'>
<div class="canvas-wrapper">
<canvas id="output"></canvas>
<video id="video" playsinline style="
-webkit-transform: scaleX(-1);
transform: scaleX(-1);
visibility: hidden;
width: auto;
height: auto;
">
</video>
</div>
<div id="scatter-gl-container"></div>
</div>
</div>
<div id="myDiv01">...</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.6/dat.gui.min.js"></script>
<script>
function isMobile() {
const isAndroid = /Android/i.test(navigator.userAgent);
const isiOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);
return isAndroid || isiOS;
}
function drawPath(ctx, points, closePath) {
const region = new Path2D();
region.moveTo(points[0][0], points[0][1]);
for (let i = 1; i < points.length; i++) {
const point = points[i];
region.lineTo(point[0], point[1]);
}
if (closePath) {
region.closePath();
}
ctx.stroke(region);
}
let model, ctx, videoWidth, videoHeight, video, canvas,
scatterGLHasInitialized = false, scatterGL;
const VIDEO_SIZE = 500;
const mobile = isMobile();
const renderPointcloud = true;//mobile === false;
const state = {
backend: 'wasm',
maxFaces: 10,
triangulateMesh: false
};
if (renderPointcloud) {
state.renderPointcloud = true;
}
function setupDatGui() {
const gui = new dat.GUI();
gui.add(state, 'backend', ['wasm', 'webgl', 'cpu'])
.onChange(async backend => {
await tf.setBackend(backend);
});
gui.add(state, 'maxFaces', 1, 20, 1).onChange(async val => {
model = await facemesh.load({maxFaces: val});
});
gui.add(state, 'triangulateMesh');
if (renderPointcloud) {
gui.add(state, 'renderPointcloud').onChange(render => {
document.querySelector('#scatter-gl-container').style.display =
render ? 'inline-block' : 'none';
});
}
}
async function setupCamera() {
video = document.getElementById('video');
const stream = await navigator.mediaDevices.getUserMedia({
'audio': false,
'video': {
facingMode: 'user',
// Only setting the video to a specified size in order to accommodate a
// point cloud, so on mobile devices accept the default size.
width: mobile ? undefined : VIDEO_SIZE,
height: mobile ? undefined : VIDEO_SIZE
},
});
video.srcObject = stream;
return new Promise((resolve) => {
video.onloadedmetadata = () => {
resolve(video);
};
});
}
async function renderPrediction() {
// stats.begin();
const predictions = await model.estimateFaces(video);
// console.log(predictions[0].faceInViewConfidence)
ctx.drawImage(
video, 0, 0, videoWidth, videoHeight, 0, 0, canvas.width, canvas.height);
document.getElementById('myDiv01').innerHTML = ''
if (predictions.length > 0) {
predictions.forEach(prediction => {
try {
//document.getElementById('myDiv01').innerHTML += 'Confidence: ' + prediction.faceInViewConfidence.toFixed(4) + '<br>'
console.log(prediction.faceInViewConfidence.toFixed(4))
}
catch(err){
//document.getElementById('myDiv01').innerHTML = err.message;
console.log(err.message)
}
const keypoints = prediction.scaledMesh;
// console.log(keypoints[0][2])
if (state.triangulateMesh) {
for (let i = 0; i < TRIANGULATION.length / 3; i++) {
const points = [
TRIANGULATION[i * 3], TRIANGULATION[i * 3 + 1],
TRIANGULATION[i * 3 + 2]
].map(index => keypoints[index]);
drawPath(ctx, points, true);
}
} else {
for (let i = 0; i < keypoints.length; i++) {
const x = keypoints[i][0];
const y = keypoints[i][1];
ctx.beginPath();
ctx.arc(x, y, 1 /* radius */, 0, 2 * Math.PI);
ctx.fill();
}
}
});
if (renderPointcloud && state.renderPointcloud && scatterGL != null) {
const pointsData = predictions.map(prediction => {
let scaledMesh = prediction.scaledMesh;
return scaledMesh.map(point => ([-point[0], -point[1], -point[2]]));
});
let flattenedPointsData = [];
for (let i = 0; i < pointsData.length; i++) {
flattenedPointsData = flattenedPointsData.concat(pointsData[i]);
}
const dataset = new ScatterGL.Dataset(flattenedPointsData);
if (!scatterGLHasInitialized) {
scatterGL.render(dataset);
} else {
scatterGL.updateDataset(dataset);
}
scatterGLHasInitialized = true;
}
}
// stats.end();
requestAnimationFrame(renderPrediction);
};
async function main() {
await tf.setBackend(state.backend);
//setupDatGui();
//stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
// document.getElementById('main').appendChild(stats.dom);
await setupCamera();
video.play();
videoWidth = video.videoWidth;
videoHeight = video.videoHeight;
video.width = videoWidth;
video.height = videoHeight;
canvas = document.getElementById('output');
canvas.width = videoWidth;
canvas.height = videoHeight;
const canvasContainer = document.querySelector('.canvas-wrapper');
canvasContainer.style = `width: ${videoWidth}px; height: ${videoHeight}px`;
ctx = canvas.getContext('2d');
ctx.translate(canvas.width, 0);
ctx.scale(-1, 1);
ctx.fillStyle = '#32EEDB';
ctx.strokeStyle = '#32EEDB';
ctx.lineWidth = 0.5;
model = await facemesh.load({maxFaces: state.maxFaces});
// console.log(model)
renderPrediction();
if (renderPointcloud) {
document.querySelector('#scatter-gl-container').style =
`width: ${VIDEO_SIZE}px; height: ${VIDEO_SIZE}px;`;
scatterGL = new ScatterGL(
document.querySelector('#scatter-gl-container'),
{'rotateOnStart': false, 'selectEnabled': false});
}
};
main();
</script>