Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ishan-marikar/1b9a3c7ef905fe55df9a076a1bafb92c to your computer and use it in GitHub Desktop.
Save ishan-marikar/1b9a3c7ef905fe55df9a076a1bafb92c to your computer and use it in GitHub Desktop.
Facial recognition and training with node js
// Starkflow comments + github project node js
// + https://github.com/jrgcubano/face-detection-node-opencv
// + http://blog.stevenedouard.com/stroll-node-facial-recognition-3rd-party-apis
/*I believe that you're using the node-opencv library ? You will need some more steps. You have to train your opencv system which than allows you to use the method "predictSync" from FaceRecongizer().
The node-opencv library has a FaceRecognizer Object which you first initialize.
Initialize FaceRecognizer: var FaceRecognizer = new cv.FaceRecognizer();
You have to read all the images, create a specific array and train your FaceRecognizer with that. For my purpose, I'm saving each user in a DB and they get a unique ID which I'm using to create a specific subfolder and this is later used. Here is my code:
*/
const path = require("path");
const fs = require("fs");
const cv = require("opencv");
const FaceRecognizer = new cv.FaceRecognizer();
let cvImages = [];
var uploadDir = path.join(".", "/uploads");
fs.readdir(uploadDir, function(err, files) {
if (err) throw new Error(err);
if (files.length > 0) {
//There are some user related image folders
files.forEach(function(subfolder, index, array) {
if (subfolder != ".DS_Store") {
//Issue with Mac, test on Linux-VM
//We are now iterating over each subfolder
var subFolderDir = path.join(uploadDir, "/" + subfolder);
var images = fs.readdirSync(subFolderDir);
//console.log(images);
images.forEach(function(image, index, array) {
//Get Matrix Objekt for each image to train OpenCV
if (image != ".DS_Store") {
var imageDir = path.join(subFolderDir, "/" + image);
cv.readImage(imageDir, function(err, im) {
var channels = im.channels();
if (channels >= 3) {
var labelNumber = parseInt(subfolder); //Create labelnumber; Account-Id starts by 1, labels for openCV start with 0
cvImages.push(new Array(labelNumber, im)); //Add image to Array
}
});
}
});
}
});
if (cvImages.length > 3) {
console.log("Training images (we have at least 3 images)", cvImages);
FaceRecognizer.trainSync(cvImages);
} else {
console.log("Not enough images uploaded yet", cvImages);
}
} else {
console.log("There are no images uploaded yet!");
}
});
setTimeout(() => {
cv.readImage("./test/ishii.jpg", function(err, im) {
if (err) res.send(err);
var whoisit = FaceRecognizer.predictSync(im);
console.log("Identified image", whoisit);
});
}, 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment