// demo下载 https://download.csdn.net/download/WWWLSW/88950321
const faceapi = require('@vladmandic/face-api');
const canvas = require('canvas');
const threshold = 0.4; // 可根据实际情况调整
function compareFace(args) {
const {Image, Canvas, ImageData} = canvas;
faceapi.env.monkeyPatch({Image, Canvas, ImageData});
// 加载模型
Promise.all([
faceapi.nets.faceRecognitionNet.loadFromDisk('./models'),
faceapi.nets.faceLandmark68Net.loadFromDisk('./models'),
faceapi.nets.ssdMobilenetv1.loadFromDisk('./models'),
// faceapi.loadSsdMobilenetv1Model
]).then(start());
// 开始人脸识别
async function start() {
try {
// Load the models
// Load the images
const image1 = await canvas.loadImage(args.pathImage1);
const image2 = await canvas.loadImage(args.pathImage2);
// const image1 = await canvas.loadImage(path.join(__dirname,"rr1.png"));
// const image2 = await canvas.loadImage(path.join(__dirname,"rr2.png"));
console.log("begin:"+new Date())
// Detect faces in the images
const face1 = await faceapi.detectSingleFace(image1).withFaceLandmarks().withFaceDescriptor();
console.log("end1:"+new Date())
const face2 = await faceapi.detectSingleFace(image2).withFaceLandmarks().withFaceDescriptor();
console.log("end2:"+new Date())
// Check if faces were detected in both images
if (face1 && face2) {
// Create an array of face descriptors
const faceDescriptors = [face1.descriptor];
// Create a FaceMatcher with the face descriptors
const faceMatcher = new faceapi.FaceMatcher(faceDescriptors, threshold);
// Compare the face descriptors of the second image
const result = faceMatcher.findBestMatch(face2.descriptor);
const person = result.label;
if (person == "person 1") {
console.log('这两张图片可能是同一个人。');
} else {
console.log('这两张图片可能是不同的人。');
}
// Output the result
console.log(`Similarity: ${result.toString()}`);
return result;
} else {
throw new Error('Unable to detect faces in one or both images.');
}
} catch (error) {
console.log('No face detected.');
console.error(`Error occurred: ${error}`);
throw error;
}
}
}
let args = {};
args.pathImage1 = "http://192.168.1.6/documents/renxianqi.png";
args.pathImage2 = "http://192.168.1.6/documents/wubai.png";
compareFace(args)
// demo下载 https://download.csdn.net/download/WWWLSW/88950321