Face Detection API
一个针对图像中的人脸进行识别的底层加速平台组件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0" />
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.img,
.canvas {
width: 320px;
}
</style>
</head>
<body>
<img src="./people.jpg" alt="" class="img" hidden />
<hr />
<canvas class="canvas"></canvas>
<script>
init();
function init() {
if (!Reflect.has(globalThis, 'FaceDetector')) {
document.body.innerHTML = `<h1>不支持人脸检测</h1>`;
return;
}
const img = document.querySelector('.img');
/** @type {HTMLCanvasElement} */
const canvas = document.querySelector('.canvas');
const ctx = canvas.getContext('2d');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
ctx.save();
const faceDetector = new FaceDetector({
fastMode: true /* 是否开启速度优先(于精确度)模式,将通过更小的比例尺(更靠近目标图形)或寻找更大的目标图形的办法进行识别 */,
maxDetectedFaces: 5 /* 当前场景中已识别的人脸数的最大值 */,
});
faceDetector
.detect(canvas)
.then((faces) => {
console.log(faces);
ctx.lineWidth = 3;
ctx.strokeStyle = 'yellow';
faces.forEach((face) => {
const { x, y, width, height } = face.boundingBox;
ctx.beginPath();
ctx.rect(x, y, width, height);
ctx.stroke();
});
ctx.closePath();
})
.catch((error) => {
console.log(error);
});
}
</script>
</body>
</html>