Skip to content

Instantly share code, notes, and snippets.

@maxdevjs
Created March 25, 2018 18:24
Show Gist options
  • Save maxdevjs/1c7921bb9cd798d457254f92a7e33584 to your computer and use it in GitHub Desktop.
Save maxdevjs/1c7921bb9cd798d457254f92a7e33584 to your computer and use it in GitHub Desktop.
Adds parametric and random selection from an image's directory ('img') to Get started with Face detecting in nodejs ( https://medium.com/@AbderrahimSE/get-started-with-face-detecting-in-nodejs-d3c5fd97e701 ) code
const path = require('path'),
fs = require('fs');
const fr = require('face-recognition');
// load image from local
const IMAGE_BANK_SRC = 'img';
let pathImage = '';
//Grabs a random index between 0 and length
function randomIndex(length) {
return Math.floor(Math.random() * (length));
}
if (process.argv[2]) {
// pathImage = path.join(IMAGE_BANK_SRC, process.argv[2]);
pathImage = process.argv[2];
} else {
//Read the directory and get the files
const dirs = fs.readdirSync(IMAGE_BANK_SRC)
.map(file => {
return path.join(IMAGE_BANK_SRC, file);
});
pathImage = dirs[randomIndex(dirs.length-1)];
console.log(randomIndex(dirs.length-1), pathImage);
}
//const image = fr.loadImage('img.png');
const image = fr.loadImage(pathImage);
// intialize the window to showup your image
const win = new fr.ImageWindow();
// intialize face detector
const detector = new fr.FrontalFaceDetector();
// get the upscaled version of the supplied image
const sacaledimg = fr.pyramidUp(image);
// detect faces and returns all rects object (faces dimensions)
const gotFaceRects = detector.detect(sacaledimg);
// supply image to the window
win.setImage(image)
// draw rectangles over the image
const f = 0.5;
const faceRects = gotFaceRects.map(rect => new fr.Rect(rect.left * f, rect.top * f, rect.right * f, rect.bottom * f));
faceRects.forEach((r) => {
win.addOverlay(r);
});
// pause the program until you hit Enter
fr.hitEnterToContinue();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment