You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用@vladmandic/face-api人脸比对时遇loadImage is not a function错误

解决@vladmandic/face-api中TypeError: loadImage is not a function及人脸比对实现

问题原因

  • loadImage并非@vladmandic/face-api的直接导出项,你错误地尝试直接导入它。该库在Node.js环境下依赖canvas处理图片,图片加载需通过canvas提供的方法或初始化后的faceApi实例完成。
  • 代码还存在其他逻辑问题:loadFaceApi是函数需调用(loadFaceApi()而非loadFaceApi),人脸检测未提取特征描述符(FaceMatcher必须依赖descriptor才能完成比对),检测方法的参数传递也不符合要求。

解决方案步骤

  1. 安装必要依赖
    Node.js环境下必须安装canvas以支持图片处理能力:
npm install @vladmandic/face-api canvas
  1. 修正代码逻辑
  • 移除错误的loadImage导入,改用canvas的loadImage方法加载本地图片。
  • 正确调用loadFaceApi()初始化face-api,并配置canvas运行环境。
  • 使用detectAllFaces配合withFaceLandmarks和withFaceDescriptors提取人脸特征描述符,这是实现人脸比对的核心前提。
  • 确保检测方法传入正确的图片对象而非路径字符串。

修正后的完整代码

const { loadFaceApi, FaceMatcher } = require('@vladmandic/face-api');
const { loadImage } = require('canvas'); // 从canvas导入合法的loadImage

exports.compareImages = async (sourcePath, uploadedPath) => {
  // 初始化Face API并绑定canvas环境
  const faceApi = await loadFaceApi({ canvas: require('canvas') });

  // 加载预训练模型(必须先加载模型才能执行检测)
  await faceApi.nets.ssdMobilenetv1.loadFromDisk('./models');
  await faceApi.nets.faceLandmark68Net.loadFromDisk('./models');
  await faceApi.nets.faceRecognitionNet.loadFromDisk('./models');

  // 加载待比对的两张图片
  const image1 = await loadImage(sourcePath);
  const image2 = await loadImage(uploadedPath);

  // 检测人脸并提取特征描述符
  const detections1 = await faceApi.detectAllFaces(image1)
    .withFaceLandmarks()
    .withFaceDescriptors();
  const detections2 = await faceApi.detectAllFaces(image2)
    .withFaceLandmarks()
    .withFaceDescriptors();

  if (detections1.length === 0 || detections2.length === 0) {
    throw new Error('其中一张图片未检测到人脸');
  }

  // 创建FaceMatcher实例,以第一张图片的人脸作为比对基准
  const faceMatcher = new FaceMatcher(detections1);

  // 对第二张图片的人脸进行比对
  const bestMatches = detections2.map(detection => faceMatcher.findBestMatch(detection.descriptor));

  // 输出比对结果并返回结论
  bestMatches.forEach((match, index) => {
    console.log(`第${index + 1}张人脸比对结果: ${match.toString()}`);
    // 阈值说明:distance小于0.6通常认为是同一人,可根据需求调整
    const isSamePerson = match.distance < 0.6;
    console.log(`是否为同一人: ${isSamePerson ? '是' : '否'}`);
  });

  return bestMatches;
};

// 调用示例(需确保models目录存在并放入对应预训练模型文件)
// compareImages('./uploads/pic1.jpg', './uploads/pic2.jpg').catch(err => console.error(err));

关键说明

  • 模型文件:需从face-api官方资源下载预训练模型,放入项目的models目录,所需模型包括ssd_mobilenetv1、face_landmark_68、face_recognition三类文件。
  • 比对阈值:match.distance值越小表示人脸相似度越高,默认0.6的阈值可根据业务场景灵活调整。
  • 图片输入:若处理上传的文件Buffer,可直接将Buffer传入loadImage方法,无需转换为路径。

内容的提问来源于stack exchange,提问作者Titus jusu Nabieu lUCKY

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 22:22:54