vue实现人脸识别
Vue 实现人脸识别的方法
在 Vue 项目中实现人脸识别功能,通常需要结合第三方库或 API。以下是几种常见的实现方式:
使用 TensorFlow.js
TensorFlow.js 是一个 JavaScript 机器学习库,可以在浏览器中运行。结合人脸识别模型(如 Face-api.js),可以实现在 Vue 中的人脸检测。
安装依赖:
npm install face-api.js
示例代码:
<template>
<div>
<video ref="video" width="600" height="450" autoplay></video>
<canvas ref="canvas" width="600" height="450"></canvas>
</div>
</template>
<script>
import * as faceapi from 'face-api.js';
export default {
mounted() {
this.loadModels();
this.startVideo();
},
methods: {
async loadModels() {
await faceapi.nets.tinyFaceDetector.loadFromUri('/models');
await faceapi.nets.faceLandmark68Net.loadFromUri('/models');
},
async startVideo() {
const video = this.$refs.video;
navigator.mediaDevices.getUserMedia({ video: true })
.then(stream => {
video.srcObject = stream;
this.detectFaces();
});
},
async detectFaces() {
const video = this.$refs.video;
const canvas = this.$refs.canvas;
const displaySize = { width: video.width, height: video.height };
setInterval(async () => {
const detections = await faceapi.detectAllFaces(video,
new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks();
faceapi.matchDimensions(canvas, displaySize);
const resizedDetections = faceapi.resizeResults(detections, displaySize);
faceapi.draw.drawDetections(canvas, resizedDetections);
faceapi.draw.drawFaceLandmarks(canvas, resizedDetections);
}, 100);
}
}
};
</script>
使用百度 AI 开放平台
百度 AI 提供人脸识别 API,可以通过 HTTP 请求调用。
安装 axios:
npm install axios
示例代码:
<template>
<div>
<input type="file" @change="handleFileUpload" accept="image/*">
<img :src="imageUrl" v-if="imageUrl" width="300">
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
imageUrl: ''
};
},
methods: {
handleFileUpload(event) {
const file = event.target.files[0];
this.imageUrl = URL.createObjectURL(file);
this.detectFace(file);
},
async detectFace(file) {
const formData = new FormData();
formData.append('image', file);
try {
const response = await axios.post(
'https://aip.baidubce.com/rest/2.0/face/v3/detect',
formData,
{
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
}
}
);
console.log('识别结果:', response.data);
} catch (error) {
console.error('识别失败:', error);
}
}
}
};
</script>
使用 OpenCV.js
OpenCV.js 是 OpenCV 的 JavaScript 版本,可以在浏览器中进行图像处理和人脸检测。
引入 OpenCV.js:
<script async src="https://docs.opencv.org/4.5.5/opencv.js" onload="onOpenCvReady();"></script>
示例代码:
<template>
<div>
<video ref="video" width="600" height="450" autoplay></video>
<canvas ref="canvas" width="600" height="450"></canvas>
</div>
</template>
<script>
export default {
mounted() {
this.startVideo();
},
methods: {
startVideo() {
const video = this.$refs.video;
navigator.mediaDevices.getUserMedia({ video: true })
.then(stream => {
video.srcObject = stream;
this.processVideo();
});
},
processVideo() {
const video = this.$refs.video;
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
function processFrame() {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
const src = cv.imread(canvas);
const gray = new cv.Mat();
cv.cvtColor(src, gray, cv.COLOR_RGBA2GRAY);
const faces = new cv.RectVector();
const faceCascade = new cv.CascadeClassifier();
faceCascade.load('haarcascade_frontalface_default.xml');
faceCascade.detectMultiScale(gray, faces);
for (let i = 0; i < faces.size(); ++i) {
const face = faces.get(i);
const point1 = new cv.Point(face.x, face.y);
const point2 = new cv.Point(face.x + face.width, face.y + face.height);
cv.rectangle(src, point1, point2, [255, 0, 0, 255]);
}
cv.imshow(canvas, src);
requestAnimationFrame(processFrame);
}
setTimeout(processFrame, 0);
}
}
};
</script>
注意事项
- 使用摄像头需要 HTTPS 环境或 localhost
- 人脸识别模型文件需要正确加载
- 第三方 API 通常需要申请 access token
- 性能优化对于实时视频处理很重要
以上方法可以根据项目需求选择适合的方案,TensorFlow.js 和 OpenCV.js 适合纯前端实现,而百度 AI 等 API 方案则依赖后端服务。







