justadudewhohacks / face-api.js

JavaScript API for face detection and face recognition in the browser and nodejs with tensorflow.js
MIT License
16.68k stars 3.71k forks source link

Return the name of the highest value expresion #903

Open Caroljpeg opened 1 year ago

Caroljpeg commented 1 year ago

For an interactive installation I need to start a different function depending on the emotion detected by face-api. This is the code I wrote for the moment: `let angry = resizedDetectionData.expressions.angry; let disgusted = resizedDetectionData.expressions.disgusted; let fearful = resizedDetectionData.expressions.fearful; let happy = resizedDetectionData.expressions.happy; let neutral = resizedDetectionData.expressions.neutral; let sad = resizedDetectionData.expressions.sad; let surprised = resizedDetectionData.expressions.surprised;

let expression = (Math.max(angry, disgusted, fearful, happy, neutral, sad, surprised)); console.log(expression);`

but in this way the console log the value of the highest variable, not its name. Can anyone help me?

mo-alaa commented 1 year ago

Hi @Caroljpeg , I saw the issue while surfing the web, so please correct me if this isn't what you need.

I assume you will need to combine those emotions in an object to access later with the expression score, you will iterate over the key values using the Object.keys and ES6 findmethod as follows:

let angry = resizedDetectionData.expressions.angry;
let disgusted = resizedDetectionData.expressions.disgusted;
let fearful = resizedDetectionData.expressions.fearful;
let happy = resizedDetectionData.expressions.happy;
let neutral = resizedDetectionData.expressions.neutral;
let sad = resizedDetectionData.expressions.sad;
let surprised = resizedDetectionData.expressions.surprised;

const emotions = { 
    angry,
    disgusted,
    fearful,
    happy,
    neutral,
    sad,
    surprised
};

const getEmotionByScore = (obj, score) =>
    Object.keys(obj).find(key => obj[key] === score);

const score = (Math.max(angry, disgusted, fearful, happy, neutral, sad, surprised));
const emotion = getEmotionByScore(emotions, score);
console.log(emotion);

What do you think about this ?