如何 运行 在 web worker 中处理 tfjs 模型

How to run handpose tfjs model in web worker

我想使用网络摄像头获取帧和 运行 tensorflow 模型“handpose”来估计手的可见性。正如我们所知,handpose 模型有点慢,所以我尝试将估计转移到 web worker。

问题是HTMLVideoElement object could not be cloned.(我需要将视频传递给estimateHand方法)。

是否可以通过其他方式实现?

网络工作者:

import { getModel } from "../utils/tf-model";

let model: any;

const modelLoading = async () => {
    model = await getModel();
}

export const estimate = async (video: HTMLVideoElement) => {
    if (model) {
        const hands = await model.estimateHands(video);
        return hands;
    }
    return null;
}

modelLoading();

export default {} as typeof Worker & (new () => Worker);

主线程:

import MyWorker from 'comlink-loader!./worker';

const worker = new MyWorker();

...

func = async () => {
        const res = await worker.estimate(this.video);
        ...

编辑 我自己找到了解决方案,可以从 canvas 上下文中获取 ImageData 并将其传递给网络工作者。

...
const canvas = document.createElement('canvas');
// ofc we have to set width and height equal to video sizes ...

const ctx = canvas.getContext('2d')
ctx.drawImage(this.video, 0, 0, this.video.width, this.video.height);
const img = ctx.getImageData(0, 0, this.video.width, this.video.height);
const res = await worker.estimate(img);

好的,我找到了解决方案。很好,我们不能将 HTML 元素作为参数传递给 web worker,但是我们可以使用 canvas 上下文,如下所示:

...
const canvas = document.createElement('canvas');
// ofc we have to set width and height equal to video sizes ...

const ctx = canvas.getContext('2d')
ctx.drawImage(this.video, 0, 0, this.video.width, this.video.height);
const img = ctx.getImageData(0, 0, this.video.width, this.video.height);
const res = await worker.estimate(img);