human/demo/index-worker.js

39 lines
1.7 KiB
JavaScript
Raw Normal View History

2021-10-26 21:08:05 +02:00
/**
* Web worker used by main demo app
* Loaded from index.js
*/
/// <reference lib="webworker"/>
2021-08-17 14:51:17 +02:00
// load Human using IIFE script as Chome Mobile does not support Modules as Workers
self.importScripts('../dist/human.js');
2020-10-14 02:52:30 +02:00
2020-10-18 20:14:05 +02:00
let busy = false;
// @ts-ignore
// eslint-disable-next-line new-cap, no-undef
const human = new Human.default();
2020-10-15 21:25:58 +02:00
2021-09-17 17:23:00 +02:00
onmessage = async (msg) => { // receive message from main thread
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 = {};
2021-09-17 17:23:00 +02:00
result = await human.detect(image, msg.data.userConfig);
result.tensors = human.tf.engine().state.numTensors; // append to result object so main thread get info
result.backend = human.tf.getBackend(); // append to result object so main thread get info
2021-06-04 19:51:01 +02:00
if (result.canvas) { // convert canvas to imageData and send it by reference
2021-06-05 21:10:28 +02:00
const canvas = new OffscreenCanvas(result.canvas.width, result.canvas.height);
const ctx = canvas.getContext('2d');
if (ctx) ctx.drawImage(result.canvas, 0, 0);
const img = ctx ? ctx.getImageData(0, 0, result.canvas.width, result.canvas.height) : null;
2021-06-04 19:51:01 +02:00
result.canvas = null; // must strip original canvas from return value as it cannot be transfered from worker thread
2021-06-05 21:10:28 +02:00
if (img) postMessage({ result, image: img.data.buffer, width: msg.data.width, height: msg.data.height }, [img.data.buffer]);
2021-09-17 17:23:00 +02:00
else postMessage({ result }); // send message back to main thread with canvas
2021-06-04 19:51:01 +02:00
} else {
2021-09-17 17:23:00 +02:00
postMessage({ result }); // send message back to main thread without canvas
2021-06-04 19:51:01 +02:00
}
2020-10-18 20:14:05 +02:00
busy = false;
2020-10-14 02:52:30 +02:00
};