首页 > 解决方案 > TensorflowJS - 在非活动选项卡中执行推理

问题描述

我正在使用 TensorflowJS 对网络摄像头进行推理。代码可以在这里找到。

<script type="text/javascript">
    let model, webcam, labelContainer;

    // Load the image model and setup the webcam
    async function init() {
        const modelURL = URL + "model.json";
        const metadataURL = URL + "metadata.json";

        // load the model and metadata
        // Refer to tmImage.loadFromFiles() in the API to support files from a file picker
        // or files from your local hard drive
        // Note: the pose library adds "tmImage" object to your window (window.tmImage)
        model = await tmImage.load(modelURL, metadataURL);
        maxPredictions = model.getTotalClasses();

        // Convenience function to setup a webcam
        const flip = true; // whether to flip the webcam
        webcam = new tmImage.Webcam(500, 500, flip); // width, height, flip
        await webcam.setup(); // request access to the webcam
        await webcam.play();
        window.requestAnimationFrame(loop);

    }

    async function loop() {
        webcam.update(); // update the webcam frame
        window.requestAnimationFrame(loop);
    }


</script>

即使您没有激活浏览器选项卡,是否有办法进行预测?我的意思是未选择选项卡,并且浏览器窗口可能会最小化。

标签: browserwebcamtensorflow.js

解决方案


问题

requestAnimationFrame在下一次浏览器重绘之前调用。由于选项卡在后台,因此不会发生重绘。引用 Chrome开发者更新

根据文档requestAnimationFrame(),当页面在后台时,Chrome 不会调用。

解决方案

requestAnimationFrame您可以使用setTimeout函数而不是使用:

setTimeout(loop, 20); // fixed 20ms delay

但是,Chrome 也会在 10 秒后开始限制后台标签。可以通过使用 flag 启动 Chrome 来解决该问题--disable-background-timer-throttling。有关此后台限制的更多信息,请查看有关Chrome 开发人员的基于预算的后台计时器限制的信息。


推荐阅读