Recently I have added the face recognition algorithms from OpenCV contrib to opencv4nodejs, an npm package, which allows you to use OpenCV in your Node.js application. Today we are going to take a look at the Fisher-, Eigen- and LBPH FaceRecognizers implemented in the OpenCVs’ face module and build a simple Node.js face recognition example. As always the source code for the examples can be found on my github repo. Let’s not waste any more time and get started!
Before we can train the recognizers we have to collect some image data with faces. If you are as excited about The Walking Dead as I am, then you are probably familar with our test subjects. I collected 4 images of Daryl, Rick and evil boy Negan, 12 in total.
The CascadeClassifier can be used for object detection and is created from an xml file containing the representation of a trained model. OpenCV provides some pre-trained models for different use cases such as face detection, eye detection, full body detection and others. To detect the faces we will use the HAAR_FRONTALFACE_ALT2 model. Given a gray scale image, detectMultiScale will return the bounding rectangles of potential faces in the image. We can simply take the first best detection result and return the subimage covered by the rectangle.
You can also pass some parameters to the constructors of the recognizers to fine-tune them, but for the sake of simplicity we will go with the default settings. Logically, the train method expects the trainImages and labels arrays to be of the same length and the labels array has to contain atleast 2 different labels.
Using only 3 images per class (character) we can already obtain pretty good results. Okay the eigen recognizer made a single mistake and assumed Ricks face to belong to Negan, but I think you get the idea how to implement face recognition with OpenCV. There is also a second face recognition example in the repo, which produces the result shown in the title image, just in case your interested.
If you liked this article feel free to clap and comment. I would also highly appreciate supporting the opencv4nodejs project by leaving a star on github. Furthermore feel free to contribute or get in touch if you are interested :).