Face API In C# Using Cognitive Services

What are Cognitive Services?

Cognitive Services help us to develop some intelligent applications that work across all the platforms such as iOS, Android and Microsoft. All APIs are available under Cognitive Services, which will help us to develop and work with the interactive environment. At Build 2016, Microsoft released another update for Cognitive Service with Bot Framework.

By using Cognitive Services, the developers are able to develop apps, using available APIs such as, 

  • Vision API
  • Speech API
  • Language API
  • Knowledge API
  • Search API
Some of the requirements are given below to complete this article.
  • Visual Studio 2015 (Community, Professional or Enterprise Edition).
If you don’t have Visual Studio 2015, download the Community Edition, as it is absolutely free. To download Visual Studio 2015, click here.
  • Cognitive Services face API Key 

Here, I am assuming that you have the requirement. Thus, let’s get started

The steps are given below to create a Face API in C#, using Cognitive Services.

Getting key from Cognitive Services

Each user is able to get 2 keys for each product such as Face API, Emotion API, Text Analysis and so on. To activate Cognitive Face API, visit Cognitive service official site.

 

Once key is generated, click copy option to copy the key and make a note of it, as it is used in the future.

Creating a Project

Open up Visual Studio 2015 to start developing a Face API Application, using WPF Application.

Click File -> New -> Project/solution or simply click New Project link, which is available in the starting page of Visual Studio.

 

Now, new project dialog appears. Click Visual C# ->Windows ->classic Desktop ->WPF Application and then name the Application, as per your wish and subsequently click OK.

 

Now, Visual Studio starts creating an application and it takes about a minute to create an Application successfully. Now, you will be navigated to MainWindow.xaml.

Locate Solution Explorer to install Newtonsoft.Json NuGet package. Now, right click on the solution's name and click Manage NuGet Package Manager. Search for “Newtonsoft.Json” and install.

 

Again open Manage NuGet gallery, search for Microsoft.ProjectOxford.Face and install it.

 

After installation, you will be able to find installed reference under the reference tree.

Now, it is a coding part, so open up MainWindow.xaml and add the code given under Grid opening tag.

  1. <Image x:Name="FacePhoto" Stretch="Uniform" Margin="0,0,0,30"/>          
  2.         <Button x:Name="BrowseButton" Margin="20,5" Height="20"           
  3.                 VerticalAlignment="Bottom" Content="Browse..."                  
  4.                 Click="BrowseButton_Click"/>  

Open toolbar, add Image tool and the button too and change the properties such as name, value, content, height and width.

Open MainWindow.Xaml.cs and add the code under button to perform Face detection operation, as shown below.

  1. var openDlg = new Microsoft.Win32.OpenFileDialog();  
  2.     openDlg.Filter = "JPEG Image(*.jpg)|*.jpg";  
  3.     bool? result = openDlg.ShowDialog(this);  
  4.     if (!(bool)result)  
  5.     {  
  6.         return;  
  7.     }  
  8.     string filePath = openDlg.FileName;  
  9.     Uri fileUri = new Uri(filePath);  
  10.     BitmapImage bitmapSource = new BitmapImage();  
  11.     bitmapSource.BeginInit();  
  12.     bitmapSource.CacheOption = BitmapCacheOption.None;  
  13.     bitmapSource.UriSource = fileUri;  
  14.     bitmapSource.EndInit();  
  15.     FacePhoto.Source = bitmapSource;   

Open MainWindow.xaml.cs and add the ProjectOxford.face reference, using the code given below.

  1. using Microsoft.ProjectOxford.Face;   
  2. using Microsoft.ProjectOxford.Face.Contract;  

Insert the code given below in MainWindow class

  1. private readonly IFaceServiceClient faceServiceClient = new FaceServiceClient("Your subscription key");  

 

To start detecting faces, we need to add the synchronous function into the MainWindow class to start detecting.
  1. private async Task<FaceRectangle[]> UploadAndDetectFaces(string imageFilePath)  
  2. {  
  3.     try  
  4.     {  
  5.         using (Stream imageFileStream = File.OpenRead(imageFilePath))  
  6.         {  
  7.             var faces = await faceServiceClient.DetectAsync(imageFileStream);  
  8.             var faceRects = faces.Select(face => face.FaceRectangle);  
  9.             return faceRects.ToArray();  
  10.         }  
  11.     }  
  12.     catch (Exception)  
  13.     {  
  14.         return new FaceRectangle[0];  
  15.     }  
  16. }  

 

Again, add the code given below at the end of button_click handler to start marking the faces.
  1. Title = "Detecting...";  
  2.             FaceRectangle[] faceRects = await UploadAndDetectFaces(filePath);  
  3.             Title = String.Format("Detection Finished. {0} face(s) detected", faceRects.Length);  
  4.   
  5.             if (faceRects.Length > 0)  
  6.             {  
  7.                 DrawingVisual visual = new DrawingVisual();  
  8.                 DrawingContext drawingContext = visual.RenderOpen();  
  9.                 drawingContext.DrawImage(bitmapSource,  
  10.                     new Rect(0, 0, bitmapSource.Width, bitmapSource.Height));  
  11.                 double dpi = bitmapSource.DpiX;  
  12.                 double resizeFactor = 96 / dpi;  
  13.   
  14.                 foreach (var faceRect in faceRects)  
  15.                 {  
  16.                     drawingContext.DrawRectangle(  
  17.                         Brushes.Transparent,  
  18.                         new Pen(Brushes.Red, 2),  
  19.                         new Rect(  
  20.                             faceRect.Left * resizeFactor,  
  21.                             faceRect.Top * resizeFactor,  
  22.                             faceRect.Width * resizeFactor,  
  23.                             faceRect.Height * resizeFactor  
  24.                             )  
  25.                     );  
  26.                 }  
  27.   
  28.                 drawingContext.Close();  
  29.                 RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap(  
  30.                     (int)(bitmapSource.PixelWidth * resizeFactor),  
  31.                     (int)(bitmapSource.PixelHeight * resizeFactor),  
  32.                     96,  
  33.                     96,  
  34.                     PixelFormats.Pbgra32);  
  35.   
  36.                 faceWithRectBitmap.Render(visual);  
  37.                 FacePhoto.Source = faceWithRectBitmap;  
  38.             }  

Now, our front-end and back-end coding is completed, so deploy an application by clicking F5. Finally, our output is displayed, as shown below.

 
 
 

Summary

In this article, we have discussed Cognitive Services and building a Face API, using C#.

I hope, you enjoyed reading this article. Thanks for reading.


Similar Articles