仅捕获检测到的人脸正方形 JS
Posted
技术标签:
【中文标题】仅捕获检测到的人脸正方形 JS【英文标题】:Capture Detected Face Square Only JS 【发布时间】:2021-06-23 15:34:38 【问题描述】:我正在通过网络摄像头中的 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, 0, canvas.width, canvas.height)
faceapi.draw.drawDetections(canvas, resizedDetections)
faceapi.draw.drawFaceExpressions(canvas, resizedDetections)
, 100)
)
HTML
<div id="cam">
<video id="video" autoplay muted></video>
</div>
<div class="control">
<button id="snap" class="btn btn-primary">Capture</button>
</div>
<canvas id="canvas" ></canvas>
【问题讨论】:
faceapi
是什么?!
@Marc """"在 tensorflow.js 核心 API 之上实现的用于在浏览器中进行人脸检测和人脸识别的 javascript API""" 添加只是为了确认代码
【参考方案1】:
你有一个画布。你可以保存一个画布:How To Save Canvas As An Image With canvas.toDataURL()?
假设detections
是一个数组:
// Taken from https://***.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);
【讨论】:
非常感谢!!!!我设法保存了画布,但它只是将其下载为“文件”。不像我认为它与八位字节流有关的图像?你能知道原因吗?再次感谢:) @ParisIo 我链接的问题显示了保存画布的所有不同方法,包括重命名它。不要忘记将答案标记为已接受。以上是关于仅捕获检测到的人脸正方形 JS的主要内容,如果未能解决你的问题,请参考以下文章