首页 > 解决方案 > face-api.js 在隐藏视频源上使用面部表情模型

问题描述

刚刚发现了很棒的face-api.js 存储库,我在使用面部表情 API 时玩得很开心。也许是因为我笑得太多了(为了测试)。

无论如何,在我的应用程序中,我想检查用户是否在微笑但没有在屏幕上显示相机视频。

现在,我可以非常准确地检查用户是否在微笑,但视频必须在我的屏幕上。

如何从屏幕上删除视频?

这是js代码:

<video id="video" width="500" height="500" autoplay muted ></video>

async startVideo() {
      let stream = null;
      try {
        stream = await navigator.mediaDevices.getUserMedia({
          audio: false,
          video: { width: 1280, height: 720 },
        });
        this.video.srcObject = stream;
      } catch (e) {
        console.log(e);
      }
    },

this.video = document.getElementById('video');
    Promise.all([
      faceapi.nets.tinyFaceDetector.loadFromUri('/models'),
      faceapi.nets.faceExpressionNet.loadFromUri('/models'),
    ]).then(this.startVideo);
    this.video.addEventListener('play', () => {
      console.log('video started');
      setInterval(async () => {
        const detections = await faceapi.detectAllFaces(
          this.video,
          new faceapi.TinyFaceDetectorOptions(),
        ).withFaceExpressions();
        detections.forEach((detection) => {
          if (detection.expressions.happy >= 0.7) {
            this.isHappy = true;
          } else {
            this.isHappy = false;
          }
        });
      }, 100);
    });

该应用程序位于 vue.js 中,因此我只使用了重要的部分。

非常感谢您的帮助。干杯,

标签: javascriptcanvashtml5-videoface-api

解决方案


我来这里是为了回答我自己的问题,以防将来有人需要它。

The obvious answer should be to add a "display: none;" to the video tag. However, this doesn't work somehow.

Instead, I created the element in javascript, appended it to the DOM, and changed its display to "none", and it worked.

Here is the code that made it work:

this.video = document.createElement('video');
this.video.setAttribute('id', 'video');
this.video.setAttribute('autoplay', 'muted');
document.body.appendChild(this.video);
document.getElementById('video').style.display = 'none';

推荐阅读