maystar-facescan
v1.2.0
Published
二开的web人脸识别库,支持 FaceAPI(轻量)和 MediaPipe(高精度+活体)双引擎
Maintainers
Readme
FaceScan
浏览器端人脸检测与识别库,基于 face-api.js 封装。
纯逻辑封装,不包含 UI —— 各项目可自行实现界面。
功能
- 摄像头管理 — 初始化、释放摄像头资源
- 人脸检测 — 检测画面中的人脸数量及位置
- 人脸完整性检查 — 校验 68 个关键特征点是否完整
- 人脸匹配 — 基于欧氏距离比对两张人脸相似度
- FaceScanner 类 — 封装完整识别流程的连续扫描器
安装
npm install maystar-facescan模型文件已内置在包中,安装时会自动复制到 public/models/,无需额外配置。
使用方式
方式一:函数式调用(灵活)
import { initCamera, loadModels, detectAllFaces, matchFaces } from 'maystar-facescan';
// 1. 加载模型
const ok = await loadModels();
if (!ok) throw new Error('模型加载失败');
// 2. 打开摄像头
const { success, stream, error } = await initCamera({ width: 640, height: 480 });
if (!success) throw new Error(error);
videoElement.srcObject = stream;
// 3. 检测人脸
const result = await detectAllFaces(videoElement);
console.log(`检测到 ${result.count} 张人脸`);
// 4. 检查人脸完整性
import { checkFaceCompleteness } from 'maystar-facescan';
const completeness = checkFaceCompleteness(result.detections[0].landmarks);
console.log(completeness.complete ? '完整' : `缺失: ${completeness.missing}`);
// 5. 比对人脸
const match = await matchFaces('/candidate.jpg', cameraFile, 0.4);
if (match.pass) {
console.log('识别通过!距离:', match.distance);
}方式二:FaceScanner 类(开箱即用)
import { FaceScanner } from 'maystar-facescan';
const scanner = new FaceScanner({
camera: { width: 640, height: 480 },
detectionInterval: 3000, // 检测间隔 ms
matchThreshold: 0.4, // 匹配阈值
});
// 注册回调
scanner.setCallbacks({
onStatusChange: (status) => {
tipText.value = status;
},
onFaceDetected: (result) => {
console.log(`检测到 ${result.count} 张人脸`);
},
onMatchComplete: (result) => {
if (result.pass) {
ElMessage.success('人脸识别通过!');
} else {
ElMessage.error(result.details || '识别失败');
}
},
onError: (err) => {
console.error(err);
},
});
// 初始化并开始扫描
await scanner.init(videoElement);
scanner.startScanning('/candidate-photo.jpg');
// 停止
scanner.stopScanning();
// 销毁(释放摄像头)
scanner.destroy();API 参考
initCamera(options?)
初始化摄像头,返回 { success, stream, error }。
| 参数 | 类型 | 默认值 | 说明 | | ------------------ | -------- | -------- | ------------ | | options.width | number | 640 | 视频宽度 | | options.height | number | 480 | 视频高度 | | options.frameRate | number | 15 | 帧率 | | options.facingMode | string | 'user' | 前/后置摄像头 |
loadModels(modelPath?)
加载 face-api.js 模型文件。默认从 /models 加载,模型文件会在 npm install 时自动复制。
| 参数 | 类型 | 默认值 | 说明 | | ---------- | ------ | --------- | ------------ | | modelPath | string | '/models' | 模型目录路径 |
detectAllFaces(input)
从视频或图片中检测所有人脸。
checkFaceCompleteness(landmarks)
检查 68 个特征点是否完整。
matchFaces(img1, img2, threshold?)
比对两张人脸图片的相似度。
| 参数 | 类型 | 默认值 | 说明 | | --------- | ------------------ | ------ | -------------------------- | | img1 | string | File | - | 参照图片 | | img2 | string | File | - | 待比对图片 | | threshold | number | 0.4 | 欧氏距离阈值,越小越严格 |
stopCamera(stream)
停止摄像头并释放资源。
License
MIT
