简体   繁体   English

仅捕获检测到的人脸正方形 JS

[英]Capture Detected Face Square Only JS

I'm running a face detection model via JS in the webcam, it recognises the face and draws the box correctly.我正在通过网络摄像头中的 JS 运行人脸检测 model,它可以识别人脸并正确绘制框。 How can I then go about saving the detected face only as an image locally to my computer?然后,我如何才能将检测到的面部仅作为图像保存到我的计算机本地?

Im grateful for any help!我很感激任何帮助! Im stuck!我卡住了!

The code (from face-api.js) is as follows:代码(来自 face-api.js)如下:

JavaScript 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, 0, canvas.width, canvas.height)
    faceapi.draw.drawDetections(canvas, resizedDetections)
    faceapi.draw.drawFaceExpressions(canvas, resizedDetections)
  }, 100)
})

HTML 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>

You have a canvas.你有一个 canvas。 You can save a canvas: How To Save Canvas As An Image With canvas.toDataURL()?您可以保存 canvas: 如何使用 canvas.toDataURL() 将 Canvas 保存为图像?

Assuming detections is an array:假设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, 0, canvas.width, canvas.height)
faceapi.draw.drawDetections(canvas, resizedDetections)
faceapi.draw.drawFaceExpressions(canvas, resizedDetections)
if (detections.length)
   saveCanvas(canvas);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM