-
Notifications
You must be signed in to change notification settings - Fork 22
/
app.js
325 lines (285 loc) · 8.66 KB
/
app.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
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
var indicator = null
var VIDEO_SIZE = {
width: 0,
height: 0
}
var DEFAULT_SIZE = {
width: 640,
height: 360,
}
var stats = null;
var loadParams = getLoadParams();
var modelParams = getModelParams();
function loadapp() {
indicator = videoIndicator(getCanvas('outputVideo'));
indicator.loading();
start();
}
function saveVideoSize(mediaStream) {
const s = mediaStream.getVideoTracks()[0].getSettings();
VIDEO_SIZE.width = s.width;
VIDEO_SIZE.height = s.height;
console.log(`Setting webcame size to: ${s.width}x${s.height}`);
camSizeChange(s.width, s.height);
}
function resizeVideo(size, targets) {
targets = targets || ['input', 'output', 'buffer'];
if (targets.includes('input')) {
getVideo().width = size.width;
getVideo().height = size.height;
}
if (targets.includes('output')) {
getCanvas('outputVideo').width = size.width;
getCanvas('outputVideo').height = size.height;
}
if (targets.includes('buffer')) {
getCanvas('bufferVideo').width = size.width;
getCanvas('bufferVideo').height = size.height;
}
}
function getVideo() {
return document.getElementById('inputVideo');
}
function getCanvas(id, getCtx = false) {
const canvas = document.getElementById(id);
return getCtx ? canvas.getContext('2d') : canvas;
}
function errorMessage(message) {
const error = document.getElementById('error');
error.textContent = message;
}
function camSizeChange(width, height) {
const elem = document.getElementById("cam_size");
if (elem) {
elem.textContent = `Webcam size: ${width}x${height}`;
}
}
function setCameraDevices(devices) {
const cameraSelect = document.getElementById('camera');
if (cameraSelect) {
while (cameraSelect.children.length > 1) {
cameraSelect.removeChild(cameraSelect.lastElementChild);
}
for (const device of devices) {
const selectOption = document.createElement("option");
selectOption.innerText = device.label;
selectOption.value = device.label;
cameraSelect.appendChild(selectOption);
}
}
const altCameraSelect = document.getElementById('altCamera');
if (altCameraSelect) {
while (altCameraSelect.children.length > 1) {
altCameraSelect.removeChild(altCameraSelect.lastElementChild);
}
for (const device of devices) {
const selectOption = document.createElement("option");
selectOption.innerText = device.label;
selectOption.value = device.label;
altCameraSelect.appendChild(selectOption);
}
}
}
function setCamera(camera, altCamera) {
const cameraSelect = document.getElementById('camera');
if (cameraSelect) {
cameraSelect.value = camera;
}
const altCameraSelect = document.getElementById('altCamera');
if (altCameraSelect) {
altCameraSelect.value = altCamera;
}
loadParams.camera = camera;
loadParams.altCamera = altCamera;
}
function getLoadParams() {
const urlParams = new URLSearchParams(window.location.search);
return {
camera: urlParams.get('camera') || '',
altCamera: urlParams.get('altCamera') || '',
architecture: urlParams.get('architecture') || 'MobileNetV1',
outputStride: Number(urlParams.get('outputStride')) || 16,
multiplier: Number(urlParams.get('multiplier')) || 0.75,
quantBytes: Number(urlParams.get('quantBytes')) || 2,
};
}
function getModelParams() {
const urlParams = new URLSearchParams(window.location.search);
return {
flipHorizontal: urlParams.get('flipHorizontal') == "true",
internalResolution: urlParams.get('internalResolution') || "medium",
segmentationThreshold: Number(urlParams.get('segmentationThreshold')) || 0.7,
maxDetections: Number(urlParams.get('maxDetections')) || 10,
scoreThreshold: Number(urlParams.get('scoreThreshold')) || 0.3,
nmsRadius: Number(urlParams.get('nmsRadius')) || 20,
maskBlurAmount: Number(urlParams.get('maskBlurAmount')) || 3,
};
}
async function start() {
if (!navigator.mediaDevices.getUserMedia) return;
const videoConstraint = {
audio: false,
video: {
width: { min: 640, ideal: 1280, max: 1920 },
height: { min: 360, ideal: 720, max: 1080 },
},
};
const deviceId = await getDevices();
if (deviceId) {
videoConstraint.video.deviceId = deviceId;
}
let stream;
try {
stream = await navigator.mediaDevices.getUserMedia(videoConstraint);
} catch (err) {
errorMessage(`Couldn't get the webcam object! ${err.message}`);
console.log("Something went wrong!");
console.error(err);
return;
}
errorMessage('');
saveVideoSize(stream);
resizeVideo(VIDEO_SIZE, ['input']);
resizeVideo(VIDEO_SIZE, ['output', 'buffer']);
const video = getVideo();
video.srcObject = stream;
video.play();
video.onloadeddata = () => {
if (deviceId === undefined) {
start();
} else {
initMLModel();
}
};
}
async function getDevices() {
if (!navigator.mediaDevices.enumerateDevices) {
return null;
}
let devices;
try {
devices = await navigator.mediaDevices.enumerateDevices();
} catch (ignored) {
return null;
}
const videoDevices = devices.filter(device => device.kind === 'videoinput');
if (!videoDevices.length || videoDevices[0].deviceId === '' || videoDevices[0].label === '') {
return null;
}
setCameraDevices(videoDevices);
const cameraLabel = loadParams.camera;
const foundDevice = videoDevices.find(device => device.label === cameraLabel);
const altCameraLabel = loadParams.altCamera;
const foundAltDevice = videoDevices.find(device => device.label === altCameraLabel);
setCamera(foundDevice?.label || '', foundAltDevice?.label || '');
return foundDevice?.deviceId || foundAltDevice?.deviceId || null;
}
async function initMLModel() {
const video = getVideo();
const canvas = getCanvas("outputVideo");
console.log('Loading model with params:', loadParams);
await bodyPix.load(loadParams).then(model => {
console.log('BodyPix model loaded.');
indicator.stop();
console.log('Model parameters:', modelParams);
transformFrame(model, video, canvas);
}).catch(err => {
indicator.stop();
errorMessage(err.message);
console.error(err);
})
}
async function transformFrame(model, sourceVideo, targetCanvas) {
const w = VIDEO_SIZE.width;
const h = VIDEO_SIZE.height;
const tempCtx = getCanvas('bufferVideo', true);
tempCtx.drawImage(sourceVideo, 0, 0, w, h);
const frame = getCanvas('bufferVideo');
let segments
try {
segments = await model.segmentPerson(frame, modelParams)
} catch (err) {
console.error(err);
return;
}
const foregroundColor = { r: 0, g: 0, b: 0, a: 0 };
const backgroundColor = { r: 0, g: 255, b: 0, a: 255 };
const maskSegmentation = bodyPix.toMask(segments, foregroundColor, backgroundColor);
bodyPix.drawMask(
targetCanvas,
frame,
maskSegmentation,
1, // opacity
modelParams.maskBlurAmount, // mask blur amount,
modelParams.flipHorizontal, // flip horizontal
);
window.requestAnimationFrame(() => {
if (stats) stats.begin();
transformFrame(model, sourceVideo, targetCanvas)
if (stats) stats.end();
});
}
/**
* Show indicator while waiting for video loaded
* Kudos to Phan Van Linh at https://stackoverflow.com/a/59028935/1235074
* @method videoIndicator
* @param {HTMLCanvasElement} canvas you want to show the indicator
* @return {void}
*/
function videoIndicator(canvas) {
const ctx = canvas.getContext('2d');
const center = {
x: canvas.width / 2,
y: canvas.height / 2
}
const bigCircle = {
center: center,
radius: 50,
speed: 3
}
const smallCirlce = {
center: center,
radius: 30,
speed: 2
}
let isLoading = true;
let progress = 0;
function loading() {
if (isLoading == false)
return 0
progress += 0.01;
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (progress > 1) {
progress = 0;
}
drawText(center.x, center.y);
drawCircle(bigCircle, progress);
drawCircle(smallCirlce, progress);
return window.requestAnimationFrame(loading);
}
function drawText(x, y) {
ctx.font = "12px Arial";
ctx.fillStyle = "grey";
ctx.textAlign = 'center';
ctx.fillText("loading...", x, y);
}
function drawCircle(circle, progress) {
ctx.beginPath();
const start = accelerateInterpolator(progress) * circle.speed;
const end = decelerateInterpolator(progress) * circle.speed;
ctx.arc(circle.center.x, circle.center.y, circle.radius, (start - 0.5) * Math.PI, (end - 0.5) * Math.PI);
ctx.lineWidth = 3;
ctx.strokeStyle = "grey";
ctx.stroke();
}
function accelerateInterpolator(x) {
return x * x;
}
function decelerateInterpolator(x) {
return 1 - ((1 - x) * (1 - x));
}
function stop() {
isLoading = false;
}
return { loading, stop };
}