How to compare and match faces using C# in .NET Framework
Facial comparison has useful applications in everything from app user login to sorting photos. Whatever your intent, there exists a hard way and an easy way to implement this functionality. You can start from scratch and learn how to train an AI, or you can harness an already trained AI using a web API. I think you can guess which is easier, and that is what we will be looking at in today’s post. Let’s get started.
First off, install the API client using NuGet:
Install-Package Cloudmersive.APIClient.NET.ImageRecognition -Version 1.3.5
Now call FaceCompare and provide an inputImage and matchFace for it to be compared to.
using System;
using System.Diagnostics;
using Cloudmersive.APIClient.NET.ImageRecognition.Api;
using Cloudmersive.APIClient.NET.ImageRecognition.Client;
using Cloudmersive.APIClient.NET.ImageRecognition.Model;namespace Example
{
public class FaceCompareExample
{
public void main()
{
// Configure API key authorization: Apikey
Configuration.Default.AddApiKey("Apikey", "YOUR_API_KEY");
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// Configuration.Default.AddApiKeyPrefix("Apikey", "Bearer");var apiInstance = new FaceApi();
var inputImage = new System.IO.Stream(); // System.IO.Stream | Image file to perform the operation on; this image can contain one or more faces which will be matched against face provided in the second image. Common file formats such as PNG, JPEG are supported.
var matchFace = new System.IO.Stream(); // System.IO.Stream | Image of a single face to compare and match against.try
{
// Compare and match faces
FaceCompareResponse result = apiInstance.FaceCompare(inputImage, matchFace);
Debug.WriteLine(result);
}
catch (Exception e)
{
Debug.Print("Exception when calling FaceApi.FaceCompare: " + e.Message );
}
}
}
}
That was easy, wasn’t it! Let’s look at an example output for these two images:
Our response:
{
"Successful": true,
"Faces": [
{
"LeftX": 582,
"TopY": 403,
"RightX": 1117,
"BottomY": 938,
"HighConfidenceMatch": true,
"MatchScore": 0.8268518596887589
}
],
"FaceCount": 1,
"ErrorDetails": null
}