
本教程详细探讨了在浏览器中使用face-api.js构建多人脸识别系统时,如何解决人脸误识别的问题。核心在于正确地为每个用户生成独立的标签化人脸描述符(labeledfacedescriptors),并利用facematcher进行高效准确的匹配。文章提供了完整的svelte代码示例,涵盖模型加载、视频流处理、多脸检测、特征提取及识别匹配等关键环节,旨在帮助开发者构建稳定可靠的浏览器端人脸识别应用。
在现代Web应用中集成人脸识别功能,通常需要利用JavaScript库来处理复杂的计算机视觉任务。face-api.js 是一个强大的库,它基于TensorFlow.js,提供了在浏览器环境中进行人脸检测、面部特征点定位、表情识别和人脸识别等功能。它利用预训练的深度学习模型,可以在客户端直接对图像或视频流进行实时分析,无需将数据发送到服务器,从而提高了隐私性和响应速度。
然而,在构建多人脸识别系统时,开发者可能会遇到一个常见问题:系统能够识别已保存的人脸,但在同一画面中存在多张已知人脸时,却可能将所有人脸都识别为同一个人,尽管它能正确识别出“未知”人脸。这通常是由于人脸描述符的存储和匹配逻辑存在缺陷。
问题的根源在于如何为每个已知用户(例如示例中的customer)创建和管理其人脸描述符。原始代码的getLabeledFaceDescriptions函数存在一个关键逻辑错误:它将所有客户的人脸描述符都累积到一个共享的全局descriptions数组中,然后尝试为每个客户使用这个包含所有人脸描述符的共享数组来创建faceapi.LabeledFaceDescriptors对象。
faceapi.LabeledFaceDescriptors的构造函数期望接收一个标签(例如客户的姓名)和一个只包含该标签对应人脸描述符的数组。当所有LabeledFaceDescriptors对象都引用同一个包含所有描述符的数组时,FaceMatcher在进行匹配时就无法区分不同的人脸,因为它认为所有标签都指向了同一组特征。这导致了无论识别到哪张已知人脸,系统都可能返回第一个或最“突出”的标签。
要解决上述问题,我们需要确保每个LabeledFaceDescriptors实例只包含其对应人物的特征描述符。以下是实现这一目标的步骤和代码优化:
首先,确保所有必要的face-api.js模型已正确加载。这包括用于人脸检测的ssdMobilenetv1模型、用于特征点定位的faceLandmark68Net模型以及用于人脸识别的faceRecognitionNet模型。
import * as faceapi from 'face-api.js';
import { onMount, onDestroy } from 'svelte';
// ... (其他变量定义)
const detectionOptions = {
withLandmarks: true,
withDescriptors: true,
minConfidence: 0.5,
MODEL_URLS: {
Mobilenetv1Model: "https://raw.githubusercontent.com/ml5js/ml5-data-and-models/main/models/faceapi/ssd_mobilenetv1_model-weights_manifest.json",
FaceLandmarkModel: "https://raw.githubusercontent.com/ml5js/ml5-data-and-models/main/models/faceapi/face_landmark_68_model-weights_manifest.json",
FaceRecognitionModel: "https://raw.githubusercontent.com/ml5js/ml5-data-and-models/main/models/faceapi/face_recognition_model-weights_manifest.json",
},
};
// ... (onMount, onDestroy)
async function make() {
video = await getVideo(); // 获取视频流
canvas = createCanvas(width, height);
ctx = canvas.getContext("2d");
// 并行加载所有模型
await Promise.all([
faceapi.nets.ssdMobilenetv1.loadFromUri(detectionOptions.MODEL_URLS.Mobilenetv1Model),
faceapi.nets.faceRecognitionNet.loadFromUri(detectionOptions.MODEL_URLS.FaceRecognitionModel),
faceapi.nets.faceLandmark68Net.loadFromUri(detectionOptions.MODEL_URLS.FaceLandmarkModel),
]);
console.log("Models loaded!");
modelReady(); // 模型加载完成后调用
}这是解决问题的关键步骤。getLabeledFaceDescriptors函数需要修改为为每个客户独立地收集其人脸描述符,并用这些独立的描述符数组来创建LabeledFaceDescriptors对象。为了提高识别的鲁棒性,可以尝试从同一张图片或多张图片中提取多个描述符。
let labeledFaceDescriptors = []; // 存储所有客户的 LabeledFaceDescriptors
async function getLabeledFaceDescriptions() {
const descriptorsPromises = $customers.map(async (customer) => {
if (customer.image_url == null) return;
const descriptorsForThisCustomer = []; // 为每个客户初始化一个独立的描述符数组
// 尝试从同一图片获取多个描述符,增加鲁棒性
for (let i = 0; i < 2; i++) { // 循环次数可调整
try {
const img = await faceapi.fetchImage($baseURL + customer.image_url);
const face_detection = await faceapi
.detectSingleFace(img)
.withFaceLandmarks()
.withFaceDescriptor();
if (face_detection && face_detection.descriptor) {
descriptorsForThisCustomer.push(face_detection.descriptor);
}
} catch (error) {
console.warn(`Failed to process image for ${customer.name}:`, error);
}
}
if (descriptorsForThisCustomer.length > 0) {
// 使用独立的描述符数组创建 LabeledFaceDescriptors
return new faceapi.LabeledFaceDescriptors(customer.name, descriptorsForThisCustomer);
}
return undefined; // 如果没有找到描述符,则返回undefined
});
// 等待所有客户的描述符生成完毕,并过滤掉undefined项
labeledFaceDescriptors = (await Promise.all(descriptorsPromises)).filter(d => d !== undefined);
console.log("Labeled Face Descriptors loaded:", labeledFaceDescriptors);
}在模型和LabeledFaceDescriptors准备就绪后,我们需要在视频流中实时检测所有可见人脸,并对每张人脸进行匹配。
async function modelReady() {
await getLabeledFaceDescriptions(); // 确保加载了标签化人脸描述符
if (labeledFaceDescriptors.length === 0) {
console.warn("No labeled face descriptors found. Recognition will not work.");
return;
}
// 使用所有标签化人脸描述符初始化 FaceMatcher
const faceMatcher = new faceapi.FaceMatcher(labeledFaceDescriptors, 0.6); // 0.6是匹配阈值,可根据需求调整
const displaySize = {
width: video.width,
height: video.height
};
setInterval(async () => {
// 检测视频流中的所有人脸
const detections = await faceapi
.detectAllFaces(video) // 使用 detectAllFaces
.withFaceLandmarks()
.withFaceDescriptors();
// 调整检测结果的大小以适应显示尺寸
const resizedDetections = faceapi.resizeResults(detections, displaySize);
// 对每张检测到的人脸进行匹配
const results = resizedDetections.map((d) =>
faceMatcher.findBestMatch(d.descriptor)
);
// 绘制结果
drawResults(resizedDetections, results);
}, 100); // 每100毫秒检测一次
}drawResults函数负责在Canvas上绘制视频帧、人脸边界框和识别出的姓名。同时,可以根据识别结果触发相应的业务逻辑,例如显示客户信息。
function drawResults(detections, results) {
// 清空Canvas并绘制视频帧
ctx.clearRect(0, 0, width, height);
ctx.drawImage(video, 0, 0, width, height);
if (detections && detections.length > 0) {
for (let i = 0; i < detections.length; i++) {
const detection = detections[i];
const bestMatch = results[i];
// 绘制人脸边界框
const box = detection.detection.box; // 获取边界框信息
ctx.beginPath();
ctx.rect(box.x, box.y, box.width, box.height);
ctx.strokeStyle = "#a15ffb";
ctx.lineWidth = 2;
ctx.stroke();
ctx.closePath();
// 绘制识别出的姓名
const label = bestMatch.label; // 获取匹配到的标签(姓名)
const distance = Math.round(bestMatch.distance * 100) / 100; // 匹配距离
const displayText = `${label} (${distance})`;
const textHeight = 16;
ctx.font = `${textHeight}px Arial`;
const textWidth = ctx.measureText(displayText).width;
ctx.fillStyle = "#a15ffb";
ctx.fillRect(box.x, box.y - textHeight - 8, textWidth + 8, textHeight + 8); // 绘制背景框
ctx.fillStyle = "#000000";
ctx.fillText(displayText, box.x + 4, box.y - 4); // 绘制文本
// 处理匹配到的客户信息
if (label !== "unknown") { // face-api.js默认使用"unknown"
const matchedCustomer = $customers.find(
(customer) => customer.name === label
);
if (matchedCustomer) {
// 这里可以触发业务逻辑,例如调用外部函数显示客户详情
// 注意:频繁调用 view_sales_function 可能会导致性能问题或重复操作,
// 实际应用中可能需要加入去抖动 (debounce) 或只在首次识别时触发。
// view_sales_function(matchedCustomer);
}
}
}
}
}下面是一个集成了上述优化方案的Svelte组件代码示例。
<script>
import * as faceapi from 'face-api.js';
import { onMount, onDestroy } from 'svelte';
// 假设 $customers 和 $baseURL 是 Svelte stores,用于获取客户数据和基础URL
// import { customers, baseURL } from './stores'; // 示例导入,实际项目中可能不同
// 模拟 Svelte stores,实际项目中应从 store.js 等文件导入
let $customers = [{ name: 'Alice', image_url: 'https://i.pravatar.cc/150?img=1' }, { name: 'Bob', image_url: 'https://i.pravatar.cc/150?img=2' }];
let $baseURL = ''; // 假设图片是绝对路径或相对路径,这里可留空或设置
let video;
let width = 640; // 调整视频宽度
let height = 480; // 调整视频高度
let canvas, ctx;
let container;
let labeledFaceDescriptors = []; // 存储所有客户的 LabeledFaceDescriptors
const detectionOptions = {
withLandmarks: true,
withDescriptors: true,
minConfidence: 0.5,
MODEL_URLS: {
Mobilenetv1Model: "https://raw.githubusercontent.com以上就是浏览器端基于face-api.js的多人脸识别系统构建与优化的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号