Created
January 15, 2023 07:49
-
-
Save AnthonyLzq/7d36c3ed0b4e2439fb8909bdb2897e30 to your computer and use it in GitHub Desktop.
Node similarity script in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as tfjs from '@tensorflow/tfjs-node' | |
import { Human, Config } from '@vladmandic/human' | |
import { existsSync, readFileSync } from 'fs' | |
const humanConfig: Partial<Config> = { | |
modelBasePath: 'node_modules/@vladmandic/human/models', | |
debug: true, | |
face: { emotion: { enabled: false } }, | |
body: { enabled: false }, | |
hand: { enabled: false }, | |
gesture: { enabled: false } | |
} | |
const human = new Human(humanConfig) | |
async function init() { | |
await human.tf.ready() | |
console.info('Human:', human.version, 'TF:', tfjs.version_core) | |
await human.load() | |
console.info('Loaded:', human.models.loaded()) | |
console.info('Memory state:', human.tf.engine().memory()) | |
} | |
async function detect(input: string) { | |
if (!existsSync(input)) throw new Error(`Cannot load image: ${input}`) | |
const buffer = readFileSync(input) | |
const tensor = human.tf.node.decodeImage(buffer, 3) | |
console.info('Loaded image:', input, tensor.shape) | |
const result = await human.detect(tensor, humanConfig) | |
human.tf.dispose(tensor) | |
console.info('Detected faces:', result.face.length) | |
return result | |
} | |
async function main() { | |
if (process.argv.length !== 4) { | |
console.error('Parameters: <first image> <second image> missing') | |
return | |
} | |
await init() | |
const res1 = await detect(process.argv[2]) | |
const res2 = await detect(process.argv[3]) | |
if ( | |
!res1 || | |
!res1.face || | |
res1.face.length === 0 || | |
!res1.face[0].embedding || | |
!res2 || | |
!res2.face || | |
res2.face.length === 0 || | |
!res2.face[0].embedding | |
) | |
throw new Error('Could not detect face descriptors') | |
const similarity = human.match.similarity( | |
res1.face[0].embedding, | |
res2.face[0].embedding, | |
{ order: 2 } | |
) | |
console.info('Similarity: ', similarity) | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment