FaceRecognitionDotNet
repository·master·Indexed 23 days ago
https://github.com/takuya-takeuchi/facerecognitiondotnetA C# port of the Python face_recognition library providing a simple API for facial recognition, landmark detection, and facial attribute prediction (age, gender, emotion, etc.) on Windows, Linux, and macOS.
What's inside FaceRecognitionDotNet
- FaceRecognitionDotNet provides a simplified facial recognition API for .NET applications. It is designed to work across multiple platforms, including Windows, MacOS, and Linux.
How Head Pose estimation works conceptually
masterThe Head Pose Training program estimates face pose (Roll, Pitch, Yaw) using 68 face landmarks.
The Process:
- Landmark Centering: Point 34 is used as the center of the face.
- Vector Calculation: Calculate the distance from point 34 to all other 67 points (1-68, excluding 34).
- Normalization: Apply z-score normalization to the vectors (except for roll).
- Pattern Extraction:
- Roll: Uses the arc tangent of X and Y distances.
- Pitch: Uses the euclidean distance of Y only.
- Yaw: Uses the euclidean distance of X only.
- Training: The resulting three 67-dimensional vectors are trained using the kernel recursive least squares algorithm.
Handle RGB vs BGR colorspace in FaceRecognitionDotNet
masterWhen working with raw bitmap data, you must ensure the colorspace matches the expected input of the library.
FaceRecognitionDotNet.LoadImageFilereturns aFaceRecognitionDotNet.Imageobject that uses the RGB colorspace, following theface_recognitionspecification anddlibrequirements.FaceRecognitionDotNet.LoadImageaccepts raw bitmap data, but this data may be in BGR colorspace (for example, 24-bit Windows bitmap file data accessed viaSystem.Drawing.Bitmap.LockBitsandScan0).
Warning: Using the wrong colorspace leads to significant errors. Specifically,
FaceRecognitionDotNet.FaceRecognition.FaceEncodingsproduces different results for RGB vs BGR images. Even if the face location is identical, the resultingFaceRecognitionDotNet.FaceEncodingvalues will have an unacceptable distance between them.Train the age classification model
masterRun the training process using the
traincommand. Note that the dataset may contain invalid classes, which will result in fewer training/test samples than expected.Available Arguments:
--dataset: The directory of the dataset to use.--epoch: Total number of epochs.--lr: Initial learning rate.--min-lr: Minimum learning rate.--min-batchsize: Minimum batch size.--validation-interval: Interval for validation.
Build the Age Training tool
masterTo build the Age Training program, navigate to the
<AgeTraining_dir>in your command prompt and execute the following commands to remove existing references, add theFaceRecognitionDotNetpackage, and build in Release mode:Important Requirements:
- You must copy
DlibDotNetNative.dll,DlibDotNetNativeDnn.dll, andDlibDotNetNativeDnnAgeClassification.dllto the output directory:<AgeTraining_dir>\bin\Release\netcoreapp2.0. - For optimal performance, build the required
DlibDotNetNativeDLLs with CUDA support. - If running on Linux or MacOS, you must build
DlibDotNetfirst (refer to the DlibDotNet wiki for platform-specific tutorials).
$ dotnet remove reference ../../src/FaceRecognitionDotNet\FaceRecognitionDotNet.csproj $ dotnet add package FaceRecognitionDotNet $ dotnet build -c Release- You must copy
Install FaceRecognitionDotNet via NuGet
masterFaceRecognitionDotNet provides several NuGet packages depending on your target operating system, CPU architecture, and whether you want to use GPU acceleration (CUDA) or Intel MKL.
Important: Choose the package that matches your hardware and CUDA version if using GPU acceleration.
Package Type OS Support Architecture NuGet Package Name CPU Windows, Linux, OSX x64 FaceRecognitionDotNetCUDA Windows, Linux x64 FaceRecognitionDotNet.CUDA[VERSION](e.g.,FaceRecognitionDotNet.CUDA111)Intel MKL Windows, Linux, OSX x64/x86 FaceRecognitionDotNet.MKLARM Windows, Linux, OSX ARM/ARM64 FaceRecognitionDotNet-ARM(Note: Not yet tested)Train custom datasets for prediction models
masterDue to licensing restrictions, FaceRecognitionDotNet does not provide pretrained model files. You must train the datasets yourself to use features like Age, Emotion, Gender, or Head Pose prediction.
Training tools are provided in the repository under the
tools/directory for the following tasks:AgeTrainingEmotionTraining/EmotionTrainingV2GenderTrainingHeadPoseTrainingHelenTraining(for landmarks)
Prepare Adience dataset and model files
masterThe Age Training tool requires specific datasets and model files to function.
1. Dataset
Download the Adience dataset from this URL (requires registration). You need to extract and copy the following files to
<AgeTraining_dir>:aligned.tar.gzfaces.tar.gzfold_0_data.txtthroughfold_4_data.txtfold_frontal_0_data.txtthroughfold_frontal_4_data.txt
2. Model File
Download and extract the shape predictor file to
<AgeTraining_dir>:http://dlib.net/files/shape_predictor_5_face_landmarks.dat.bz2
Analyze dataset and training statistics
masterThe Gender Training tool provides Python scripts to visualize the dataset distribution and training progress.
Dataset Visualization:
- To check age distribution by gender:
python tools\age-by-gender-hist.py <DatasetDirectory> - To check gender distribution:
python tools\gender-hist.py <DatasetDirectory>
Training Log Visualization:
- To visualize the training log as a graph:
python tools\visualize-log.py <LogFile>
# Check dataset status python tools\age-by-gender-hist.py UTKFaceDataset python tools\gender-hist.py UTKFaceDataset # Check training log python tools\visualize-log.py utkface-gender-network_600_0.001_1E-05_400.log- To check age distribution by gender:
Create an emotion dataset using GenerateTrainTestList.ps1
masterBefore training, you must generate training and testing image lists from your raw data directory (e.g., a 300W-LP directory). Use the
tools/GenerateTrainTestList.ps1PowerShell script to create these lists in your target<dataset_dir>.Use the
-trainingRatioflag to determine the split (e.g.,0.9for 90% training and 10% testing).Build the Custom Classification Demo
masterTo build the project, navigate to the
<CustomClassificationDemo_dir>in your command prompt and execute the following commands to reset references and build in Release mode:- Remove the local project reference.
- Add the
FaceRecognitionDotNetNuGet package. - Build the project.
Important: After building, you must manually copy the following native DLLs to the output directory (
<CustomClassificationDemo_dir>\bin\Release\netcoreapp2.0):DlibDotNetNative.dllDlibDotNetNativeDnn.dllDlibDotNetNativeDnnAgeClassification.dllDlibDotNetNativeDnnGenderClassification.dll
Note: If you are using
FaceRecognitionDotNetwith CUDA support, you must also copy the required CUDA libraries to the same output directory.$ dotnet remove reference ../../src/FaceRecognitionDotNet\FaceRecognitionDotNet.csproj $ dotnet add package FaceRecognitionDotNet $ dotnet build -c ReleaseBuild the OpenCVSharp Sample
masterTo build the OpenCVSharp sample, you must first ensure you have the necessary model files prepared. Then, navigate to the
<OpenCVSharpSample_dir>in your command prompt and execute the following commands to clean up existing references, add theFaceRecognitionDotNetpackage, and build the project in Release mode.$ dotnet remove reference ../../src/FaceRecognitionDotNet\FaceRecognitionDotNet.csproj $ dotnet add package FaceRecognitionDotNet $ dotnet build -c Release