face-api的github链接:face-api.js
里面的readme写的有点难以理解,再附一个讲解的网址:讲解如何使用webcam实现人脸检测:Build Real Time Face Detection With JavaScript
本文代码基本就是这个视频里的代码扒过来的,看不了视频的直接看这篇文章就可以了。
1. 准备
- 下载face-api:
https://github.com/justadudewhohacks/face-api.js.git
- 新建一个自己的文件夹,将刚才下好的face-api.js目录里的/dist/face-api.min.js复制到自己的文件夹下,然后再把/weights文件夹直接全部拖到自己的目录下,新建index.html和face_detect.js。这里的目录设置如图所示:
2. 代码文件
- index.html的代码如下:
<!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>Face Detection</title>
<script defer src="face-api.min.js"></script>
<script defer src="face_detect.js"></script>
<style>
body {
margin: 0;
padding: 0;
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
canvas {
position: absolute;
}
</style>
</head>
<body>
<video id="video" width="720" height="560" autoplay muted></video>
</body>
</html>
- face_detect.js的代码如下:
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", () => {
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())
.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);
});
大功告成~似乎是不能直接点击index.html运行的,会报404的错误(找不到face-api的model),可以用vscode之类的服务端来打开。配合python下的tornado网络框架使用也可。