Example: Face Registration and Recognition
Introduction
This chapter builds upon the code from the previous Example: Face Detection and Tracking Box by adding a small amount of code to implement a complete face registration and recognition application.
We will focus on the following two points:
- In
faceworker.js:- Set up a callback function to receive recognition results.
- Listen for events from the UI thread to execute the registration process.
- In
uiworker.js:- Add a "Register" button.
- Send a registration request to
faceworker.jsvia the event bus (dxEventBus).
Code Changes
faceworker.js: Adding Recognition Callback and Registration Logic
Add the following code before the std.setInterval in faceworker.js:
// ... import statements ...
// try { face.init() } catch ...
// Set the recognition event callback
face.setCallbacks({
onRecognition: (event) => {
// This callback is triggered when a registered face is recognized
if (event.isRecognition) {
log.info("Recognition successful, User ID:", event.userId);
// Business logic can be added here, e.g., sending the userId to the UI thread via bus
}
},
});
// Listen for the registration event from the UI thread
bus.on("register_facial_recognition", () => {
log.info("Starting the face registration process");
try {
const userId = "testuser"; // Example: hardcode a userId
const timeout = 5000; // 5-second timeout
// To prevent duplicate registration, first try to delete the user
// (in a real application, this should be determined by business logic)
face.deleteFea(userId);
// 1. Capture face from camera and extract feature vector (this is a synchronous blocking operation)
const res = face.getFeaByCap(timeout);
if (res && res.feature) {
log.info("Feature extraction successful");
// 2. Add the feature vector and userId to the face database
face.addFea(userId, res.feature);
log.info("Feature has been successfully added to the face database");
} else {
log.warn(
"Registration failed: Could not extract a valid feature within the timeout"
);
}
} catch (ex) {
log.error("Exception in registration process", ex);
}
});
// std.setInterval(() => { ... });