vue 使用 face-api.js 实现人脸识别
<template>
<div>
<video ref="video" width="640" height="480" autoplay></video>
<canvas ref="canvas" width="640" height="480"></canvas>
<div v-if="lastDetection">
<p>Face found at position: {{ lastDetection.relativeBox }}</p>
</div>
</div>
</template>
<script>
import * as faceapi from 'face-api.js';
export default {
data() {
return {
lastDetection: null
};
},
async mounted() {
await faceapi.loadModels('/models'); // 确保路径指向了正确的模型文件夹
await this.startVideo();
setInterval(this.detectFaces, 100);
},
methods: {
async startVideo() {
const video = this.$refs.video;
const stream = await navigator.mediaDevices.getUserMedia({ video: {} });
video.srcObject = stream;
await video.play();
},
async detectFaces() {
const video = this.$refs.video;
const canvas = this.$refs.canvas;
const context = canvas.getContext('2d');
context.drawImage(video, 0, 0, canvas.width, canvas.height);
const detections = await faceapi.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions());
this.lastDetection = detections.slice(-1)[0];
if (this.lastDetection) {
const resizedDetection = this.lastDetection.forSize(width, height);
faceapi.drawDetection(canvas, resizedDetection, { withScore: false });
}
}
}
};
</script>
这个例子展示了如何在Vue组件中使用face-api.js进行人脸检测。它首先加载必要的模型,然后开始视频流,并每隔100毫秒检测一次视频中的人脸。检测到的人脸位置会被标记在视频的画面上。
评论已关闭