【问题标题】:Using face-api.js how do I flip the pixels horizontally to achieve a mirror image?使用 face-api.js 如何水平翻转像素以实现镜像?
【发布时间】:2019-11-23 19:39:21
【问题描述】:

我正在使用我的网络摄像头和面部识别进行一个项目,我需要视频源是一个镜像,而不是水平翻转,这是默认情况下的。我想出了如何翻转视频,使其看起来使用 CSS 镜像,但实际像素和面部跟踪仍然水平翻转。这是我的代码,我知道我需要翻译和缩放画布,但我尝试过的一切都没有奏效。

const video = document.getElementById('video')

Promise.all([
  faceapi.nets.tinyFaceDetector.loadFromUri('/models'),
  faceapi.nets.faceLandmark68Net.loadFromUri('/models'),
  faceapi.nets.faceRecognitionNet.loadFromUri('/models'),
  faceapi.nets.faceExpressionNet.loadFromUri('/models')
]).then(startVideo)

function startVideo() {
  navigator.getUserMedia(
    { video: {} },
    stream => video.srcObject = stream,
    err => console.error(err)
  )
}

video.addEventListener('play', () => {
  canvas = faceapi.createCanvasFromMedia(video)
  document.body.append(canvas)
  const displaySize = { width: video.width, height: video.height }
  faceapi.matchDimensions(canvas, displaySize)
  setInterval(async () => {
    const detections = await faceapi.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks().withFaceExpressions()
    const resizedDetections = faceapi.resizeResults(detections, displaySize)
    canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height)
    faceapi.draw.drawDetections(canvas, resizedDetections)
    faceapi.draw.drawFaceLandmarks(canvas, resizedDetections)
    faceapi.draw.drawFaceExpressions(canvas, resizedDetections)
  }, 100)
})
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script defer src="face-api.min.js"></script>
  <script defer src="script.js"></script>
  <style>
    body {
      margin: 0;
      padding: 0;
      width: 100vw;
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    canvas {
      position: absolute;
    }

    /* flips the video horizontally so its accurate with your movements left and right */
    video {
      -webkit-transform: scaleX(-1);
      transform: scaleX(-1);
    }

  </style>
</head>
<body>
  <video id="video" width="1600" height="800" autoplay muted></video>
</body>
</html>

【问题讨论】:

    标签: javascript scale translate webcam-capture face-api


    【解决方案1】:

    canvas CSS 元素中添加翻转代码(转换):

    canvas {
        position: absolute;
        -webkit-transform: scaleX(-1);
        transform: scaleX(-1);
    }
    

    然后,canvas 元素被翻转为video 元素。

    注意:此解决方案仅适用于您的画布不包含可能容易获得镜像效果的文本或其他内容(请参阅翻转)。在这种情况下,您必须水平映射返回的框坐标。

    【讨论】:

      猜你喜欢
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      • 2018-05-31
      • 2014-06-06
      相关资源
      最近更新 更多