human/demo/index-worker.js

32 lines
1.2 KiB
JavaScript
Raw Normal View History

import Human from '../dist/human.esm.js';
2020-10-14 02:52:30 +02:00
2020-10-18 20:14:05 +02:00
let busy = false;
const human = new Human();
2020-10-15 21:25:58 +02:00
2020-12-08 15:00:44 +01:00
function log(...msg) {
const dt = new Date();
const ts = `${dt.getHours().toString().padStart(2, '0')}:${dt.getMinutes().toString().padStart(2, '0')}:${dt.getSeconds().toString().padStart(2, '0')}.${dt.getMilliseconds().toString().padStart(3, '0')}`;
2020-10-15 21:25:58 +02:00
// eslint-disable-next-line no-console
2020-12-08 15:00:44 +01:00
if (msg) console.log(ts, 'Human:', ...msg);
}
2020-10-15 21:25:58 +02:00
2020-10-14 02:52:30 +02:00
onmessage = async (msg) => {
2020-10-18 20:14:05 +02:00
if (busy) return;
busy = true;
2021-05-30 18:03:34 +02:00
// received from index.js using:
2020-10-16 00:16:05 +02:00
// worker.postMessage({ image: image.data.buffer, width: canvas.width, height: canvas.height, config }, [image.data.buffer]);
const image = new ImageData(new Uint8ClampedArray(msg.data.image), msg.data.width, msg.data.height);
2020-10-15 21:25:58 +02:00
let result = {};
try {
2020-11-09 12:32:11 +01:00
result = await human.detect(image, msg.data.userConfig);
2020-10-15 21:25:58 +02:00
} catch (err) {
result.error = err.message;
2020-11-05 14:21:23 +01:00
log('worker thread error:', err.message);
2020-10-15 21:25:58 +02:00
}
2020-11-05 14:21:23 +01:00
// must strip canvas from return value as it cannot be transfered from worker thread
if (result.canvas) result.canvas = null;
// @ts-ignore tslint wrong type matching for worker
2021-01-03 16:41:56 +01:00
postMessage({ result });
2020-10-18 20:14:05 +02:00
busy = false;
2020-10-14 02:52:30 +02:00
};