OpenCV provides support to perform face recognition (https://docs.opencv.org/4.0.1/dd/d65/classcv_1_1face_1_1FaceRecognizer.html). Indeed, OpenCV provides three different implementations to use:
- Eigenfaces
- Fisherfaces
- Local Binary Patterns Histograms (LBPH)
These implementations perform the recognition in different ways. However, you can use any of them by changing only the way the recognizers are created. More specifically, to create these recognizers, the following code is necessary:
face_recognizer = cv2.face.LBPHFaceRecognizer_create()
face_recognizer = cv2.face.EigenFaceRecognizer_create()
face_recognizer = cv2.face.FisherFaceRecognizer_create()
Once created, and independently of the specific internal algorithm OpenCV is going to use to perform the face recognition, the two key methods, train() and predict(), should be used to perform both the training and the testing of the face recognition system, and it should be noted that the way we use these methods is independent of the recognizer created.
Therefore, it is very easy to try the three recognizers and select the one that offers the best performance for a specific task. Having said that, LBPH should provide better results than the other two methods when recognizing images in the wild, where different environments and lighting conditions are usually involved. Additionally, the LBPH face recognizer supports the update() method, where you can update the face recognizer given new data. For the Eigenfaces and Fisherfaces methods, this functionality is not possible.
In order to train the recognizer, the train() method should be called:
face_recognizer.train(faces, labels)
The cv2.face_FaceRecognizer.train(src, labels) method trains the specific face recognizer, where src corresponds to the training set of images (faces), and parameter labels set the corresponding label for each image in the training set.
To recognize a new face, the predict() method should be called:
label, confidence = face_recognizer.predict(face)
The cv2.face_FaceRecognizer.predict(src) method outputs (predicts) the recognition of the new src image by outputting the predicted label and the associated confidence.
Finally, OpenCV also provides the write() and read() methods to save the created model and to load a previously created model, respectively. For both methods, the filename parameter sets the name of the model to save or load:
cv2.face_FaceRecognizer.write(filename)
cv2.face_FaceRecognizer.read(filename)
As mentioned, the LBPH face recognizer can be updated using the update() method:
cv2.face_FaceRecognizer.update(src, labels)
Here, src and labels set the new training examples that are going to be used to update the LBPH recognizer.