npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

maysstar-face-recognition

v1.0.4

Published

纯方法封装的人脸识别 SDK(基于 MediaPipe + ONNX Runtime Web),支持一键比对、特征提取等能力。

Readme

face-recognition-sdk

纯方法封装的人脸识别 SDK,基于 MediaPipe 和 ONNX Runtime Web 实现。

特性

  • 纯方法封装:仅提供核心 API,不绑定任何 UI 框架
  • 🔧 灵活集成:可在任何前端框架中使用(Vue、React、原生 JS 等)
  • 📦 自动部署:Vite 插件自动将 WASM 和模型文件拷贝到 public 目录
  • 🧠 一键比对:简化的 API 完成人脸特征提取与相似度计算

安装

npm install maysstar-face-recognition

@mediapipe/tasks-visiononnxruntime-web 已作为 dependencies 自动安装,无需手动安装。Vite 插件会自动从 node_modules 拷贝对应的 WASM 资源到 public/ 目录。

使用步骤

1. 配置 Vite 插件

vite.config.ts 中添加插件,自动部署 WASM 和模型资源:

import { defineConfig } from 'vite';
import { faceRecognitionPlugin } from 'face-recognition-sdk/plugins';

export default defineConfig({
  plugins: [faceRecognitionPlugin()],
  optimizeDeps: {
    exclude: ['@mediapipe/tasks-vision', 'onnxruntime-web'],
  },
});

2. 在 index.html 中加载依赖

必须在 <body> 结束前添加以下代码,用于在浏览器中加载 vision_bundle.mjsort.min.mjs

<script type="module">
  (async function () {
    try {
      const [vision, ort] = await Promise.all([
        import('/vendor/tasks-vision/vision_bundle.mjs'),
        import('/vendor/onnxruntime-web/dist/ort.min.mjs'),
      ]);
      window.__faceDeps = { 
        FaceLandmarker: vision.FaceLandmarker, 
        FilesetResolver: vision.FilesetResolver, 
        ort 
      };
    } catch (e) {
      console.error('[face-deps] 加载失败:', e);
      window.__faceDeps = { error: e };
    }
  })();
</script>

3. 初始化引擎并使用

import { FaceCompare } from 'face-recognition-sdk';

// 获取引导脚本加载的依赖
const deps = window.__faceDeps;

// 初始化引擎
const fc = await FaceCompare.init({
  modelsDir: '/models',
  mediapipeWasmDir: '/vendor/tasks-vision/wasm',
  ortWasmDir: '/vendor/onnxruntime-web/dist',
  threshold: 0.363,
  imports: {
    FaceLandmarker: deps.FaceLandmarker,
    FilesetResolver: deps.FilesetResolver,
    ort: deps.ort,
  },
});

// 比对两张照片
const result = await fc.comparePhotos(photo1Url, photo2Url);
console.log('相似度:', result.similarity);
console.log('判定:', result.verdict.label);

// 提取单张照片特征
const embedding = await fc.extractPhotoEmbedding(photoUrl);

// 多张照片两两比对
const matrix = await fc.compareAll([photo1, photo2, photo3]);

API 参考

FaceCompare.init(options)

初始化人脸识别引擎。

参数:

  • modelsDir (string, 默认 './models'): 模型文件目录
  • mediapipeWasmDir (string): MediaPipe WASM 文件目录
  • ortWasmDir (string): ONNX Runtime WASM 文件目录
  • imports (object): 从引导脚本获取的依赖对象
  • threshold (number, 默认 0.363): 通过阈值(余弦相似度)
  • delegate ('GPU' | 'CPU', 默认 'GPU'): MediaPipe 委托
  • executionProviders (string[], 默认 ['webgl']): ONNX 执行后端
  • numFaces (number, 默认 1): 检测的人脸数量

返回: Promise<FaceCompare> 实例

fc.comparePhotos(photoA, photoB)

比对两张照片。

参数: 支持 File | Blob | HTMLImageElement | HTMLCanvasElement | string

返回:

{
  similarity: number,       // 余弦相似度
  verdict: {               // 判定结果
    pass: boolean,         // 是否通过
    gray: boolean,         // 是否疑似
    label: string          // 判定标签
  },
  a: { embedding, landmarks, quality, blur, width, height },
  b: { embedding, landmarks, quality, blur, width, height }
}

fc.extractPhotoEmbedding(input)

从照片中提取人脸特征向量。

返回:

{
  embedding: number[],    // 128 维特征向量(已 L2 归一化)
  landmarks: object[],    // MediaPipe 468 个关键点
  quality: { eyeDist, faceW, faceH, yaw, ok, issues },
  blur: number,           // 模糊度
  width: number,
  height: number
}

fc.compareAll(photos)

多张照片两两比对。

返回:

{
  embeddings: PhotoResult[],
  matrix: CompareResult[][]
}

fc.compareToAll(target, refs)

一张目标照片 vs 多张参考照片。

返回: Array<{id, similarity, verdict}> 按相似度降序排列

fc.createLiveComparator(video, onFrame, opts)

创建实时比对器(摄像头 vs 参考特征)。

const refEmbedding = (await fc.extractPhotoEmbedding(refPhoto)).embedding;

const live = fc.createLiveComparator(videoElement, (info) => {
  if (info.similarity !== null) {
    console.log('实时相似度:', info.similarity);
  }
}, { intervalMs: 200 });

live.setReference(refEmbedding);
live.start();

fc.destroy()

释放资源。

工具函数

import { 
  l2normalize,    // L2 归一化
  cosine,         // 余弦相似度
  similarityTransform, // 相似变换
  pick5,          // 从 468 关键点取 5 点
  alignTo112,     // 对齐裁剪到 112x112
  preprocess,     // SFace 预处理
  faceQuality,    // 人脸质量评估
  blurScore       // 模糊度估计
} from 'face-recognition-sdk';

常见问题

Q: 为什么需要 Vite 插件?

A: WASM 和模型文件必须作为静态资源部署。插件会自动把模型文件(来自本包 assets/models)和 WASM 资源(来自 node_modules 中的 @mediapipe/tasks-visiononnxruntime-web)拷贝到 public/ 目录。

Q: 为什么需要 index.html 中的引导脚本?

A: Vite 的打包机制会破坏 MediaPipe 和 ONNX Runtime 的动态 import() 机制。通过原生 <script> 标签加载可以避开这个问题。

Q: 支持哪些输入类型?

A: FileBlobHTMLImageElementHTMLCanvasElement、URL 字符串。

Q: 支持哪些浏览器?

A: 所有支持 WebAssembly 和 WebGL 的现代浏览器。

License

Apache-2.0