How to detect faces in a photo using C# in .NET Framework

Facial recognition has a large number of potential uses, anything from adding tags to images to applying photo filters, and much more. Today, we will be skipping the complex AI programming and deep learning required to implement this crucial feature from scratch. Instead, we will be applying one of our web-based APIs to quickly and easily accomplish this task.

Let’s begin by installing the API Client using NuGet and the following console command:

Install-Package Cloudmersive.APIClient.NET.ImageRecognition -Version 1.3.5

Now all that’s left is to call FaceLocate and provide the image file.

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 FaceLocateExample
{
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 imageFile = new System.IO.Stream(); // System.IO.Stream | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.
try
{
// Find faces in an image
FaceLocateResponse result = apiInstance.FaceLocate(imageFile);
Debug.WriteLine(result);
}
catch (Exception e)
{
Debug.Print("Exception when calling FaceApi.FaceLocate: " + e.Message );
}
}
}
}

That’s it! We will be provided with a return that includes the number of faces and the corner coordinates for each. For example, take the following image:

Image for post
Image for post

Call FaceLocate, and we are given:

{
"ErrorDetails": null,
"Successful": true,
"Faces": [
{
"LeftX": 886,
"TopY": 336,
"RightX": 1196,
"BottomY": 646
},
{
"LeftX": 542,
"TopY": 749,
"RightX": 852,
"BottomY": 1058
}
],
"FaceCount": 2
}

You may also be interested to know that our image processing API includes other functions that cover everything from facial comparison/recognition to license plate detection.

Written by

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store