id-scanner-lib
Version:
Browser-based ID card, QR code, and face recognition scanner with liveness detection
45 lines (38 loc) • 1.25 kB
text/typescript
/**
* @file Face Comparator
* @description Face comparison using cosine similarity
* @module modules/face/comparator
*/
import { FaceCompareResult, FaceDetectionResult } from '../detector/types';
export class FaceComparator {
private _threshold: number = 0.6;
constructor(threshold: number = 0.6) {
this._threshold = threshold;
}
async compare(
face1: FaceDetectionResult | number[],
face2: FaceDetectionResult | number[]
): Promise<FaceCompareResult> {
// Extract embedding
const emb1 = Array.isArray(face1) ? face1 : face1.embedding ?? [];
const emb2 = Array.isArray(face2) ? face2 : face2.embedding ?? [];
// Compute cosine similarity
const similarity = this._cosineSimilarity(emb1, emb2);
return {
similarity,
isMatch: similarity >= this._threshold,
threshold: this._threshold,
algorithm: 'cosine-similarity',
};
}
private _cosineSimilarity(a: number[], b: number[]): number {
if (a.length !== b.length || a.length === 0) return 0;
let dot = 0, magA = 0, magB = 0;
for (let i = 0; i < a.length; i++) {
dot += a[i] * b[i];
magA += a[i] * a[i];
magB += b[i] * b[i];
}
return dot / (Math.sqrt(magA) * Math.sqrt(magB));
}
}