仅捕获检测到的方脸 JS

问题描述

我正在网络摄像头中通过 JS 运行人脸检测模型,它可以识别人脸并正确绘制框。那么我如何将检测到的人脸仅作为图像保存到我的计算机本地?

我很感激任何帮助!我卡住了!

代码(来自face-api.js)如下:

JavaScript

const video = document.getElementById('video')
const snap = document.getElementById('snap')
const canvas = document.getElementById('canvas')



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

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



video.addEventListener('play',() => {
  const 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()).withFaceExpressions()
    const resizedDetections = faceapi.resizeResults(detections,displaySize)
    canvas.getContext('2d').clearRect(0,canvas.width,canvas.height)
    faceapi.draw.drawDetections(canvas,resizedDetections)
    faceapi.draw.drawFaceExpressions(canvas,resizedDetections)
  },100)
})

HTML

<div id="cam">
    <video id="video" width="720" height="560" autoplay muted></video>
</div>
<div class="control">
    <button id="snap" class="btn btn-primary">Capture</button>
</div>
<canvas id="canvas" width="197" height="197"></canvas>

解决方法

你有一张画布。您可以保存画布:How To Save Canvas As An Image With canvas.toDataURL()?

假设 detections 是一个数组:

// Taken from https://stackoverflow.com/a/15685544/4088472
function saveCanvas(canvas) {
  const image = canvas.toDataURL("image/png").replace("image/png","image/octet-stream");  
  window.location.href=image; // it will save locally
}


// ... in your code ...
canvas.getContext('2d').clearRect(0,canvas.width,canvas.height)
faceapi.draw.drawDetections(canvas,resizedDetections)
faceapi.draw.drawFaceExpressions(canvas,resizedDetections)
if (detections.length)
   saveCanvas(canvas);