UNPKG

face-guard

Version:

前端轻量级人脸识别与图像采集工具,基于 face-api.js 封装,支持自动检测、用户引导和 Base64 图像输出。

3 lines (2 loc) 2.38 kB
"use strict";const a=require("face-api.js");function n(i){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const t in i)if(t!=="default"){const o=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,o.get?o:{enumerable:!0,get:()=>i[t]})}}return e.default=i,Object.freeze(e)}const s=n(a);class r{constructor(e){this.modelPath=e.modelPath||"/models",this.videoElement=null,this.recognitionInterval=null,this.onError=e.onError||console.error,this.onFaceDetected=e.onFaceDetected||(()=>{}),this.stream=null,this.onFeedback=e.onFeedback||(()=>{})}async loadModels(){try{await s.nets.tinyFaceDetector.loadFromUri(this.modelPath),await s.nets.faceLandmark68Net.loadFromUri(this.modelPath),await s.nets.faceRecognitionNet.loadFromUri(this.modelPath),console.log("模型加载完成")}catch(e){throw this.onError("模型加载失败: "+e.message),e}}async start(e){if(!e)throw new Error("必须传入 video 元素");this.videoElement=e;try{await this.loadModels(),await this.startVideo()}catch(t){this.onError(t)}}async startVideo(){try{const e=await navigator.mediaDevices.getUserMedia({video:{}});this.videoElement.srcObject=e,this.stream=e,this.videoElement.play(),setTimeout(()=>{this.startRecognition()},1e3)}catch(e){this.onError("无法访问摄像头: "+e.message)}}startRecognition(){this.recognitionInterval=setInterval(async()=>{const e=await s.detectAllFaces(this.videoElement,new s.TinyFaceDetectorOptions).withFaceLandmarks().withFaceDescriptors();if(e.length>0){const t=e[0].alignedRect.score;if(t>.9){const o=this.getBase64Image();this.onFaceDetected(o),this.stop()}else{const o=this.getUserFeedback(t);this.onFeedback?.(o)}}else this.onFeedback?.("未检测到人脸,请调整位置")},100)}getBase64Image(){const e=document.createElement("canvas");return e.width=this.videoElement.videoWidth,e.height=this.videoElement.videoHeight,e.getContext("2d").drawImage(this.videoElement,0,0,e.width,e.height),e.toDataURL("image/png")}getUserFeedback(e){return e<.5?"请向前移动":e<.7?"请向左或右移动":"请稍微调整位置"}stop(){this.recognitionInterval&&(clearInterval(this.recognitionInterval),this.recognitionInterval=null),this.stream&&(this.stream.getTracks().forEach(e=>e.stop()),this.stream=null),this.videoElement&&(this.videoElement.srcObject=null)}}module.exports=r; //# sourceMappingURL=face-guard.cjs.js.map