Face Detection Using Microsoft Cognitive Service

In this article, I want to demonstrate face detection, using Microsoft Cognitive Service. You all know that Microsoft Cognitive Service is becoming more flexible day by day.

Lets get started.

First of all, go to Azure portal and create a Cognitive Service API for Face Detection. Choose pricing tier. You can choose any tier from the available list. I am choosing S0 Standard.

At the resource group field, you can either create a new resource or choose an existing one. Here, I am creating a new resource group. Subsequently, agree with the legal terms. Check the pin to dashboard, so that it will be easier to access and click on create. It will take some time to create, as shown below.



After successful deployment of API, go to keys in the Resource Management and copy the key from there, as shown below.



Now, lets open Visual Studio. Create new project as choose WPF Application inside Classic Desktop in Visual C#.

In MainWindow.xaml, add an Image holder and a button inside the grid or simply replace the grid with the code, mentioned below.

  1. <Grid x:Name="BackPanel">  
  2.     <Image x:Name="FacePhoto" Stretch="Uniform" Margin="0,0,0,30" />  
  3.     <Button x:Name="BrowseButton" Margin="20,5" Height="20" VerticalAlignment="Bottom" Content="Browse Image..." Click="BrowseButton_Click" />  
  4. </Grid>  
Install Newtonsoft.Json and Microsoft.ProjectOxford.Face via NuGet Package Manager. Go to MainWindow.xaml.cs and replace the button click event with the code, mentioned below.
  1. private async void BrowseButton_Click(object sender, RoutedEventArgs e) {  
  2.     var openDlg = new Microsoft.Win32.OpenFileDialog();  
  3.     openDlg.Filter = "JPEG Image(*.jpg)|*.jpg";  
  4.     bool ? result = openDlg.ShowDialog(this);  
  5.     if (!(bool) result) {  
  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;  
  16.     Title = "Detecting...";  
  17.     FaceRectangle[] faceRects = await UploadAndDetectFaces(filePath);  
  18.     Title = String.Format("Detection Finished. {0} face(s) detected", faceRects.Length);  
  19.     if (faceRects.Length > 0) {  
  20.         DrawingVisual visual = new DrawingVisual();  
  21.         DrawingContext drawingContext = visual.RenderOpen();  
  22.         drawingContext.DrawImage(bitmapSource,  
  23.             new Rect(0, 0, bitmapSource.Width, bitmapSource.Height));  
  24.         double dpi = bitmapSource.DpiX;  
  25.         double resizeFactor = 96 / dpi;  
  26.         foreach(var faceRect in faceRects) {  
  27.             drawingContext.DrawRectangle(  
  28.                 Brushes.Transparent,  
  29.                 new Pen(Brushes.Red, 2),  
  30.                 new Rect(  
  31.                     faceRect.Left * resizeFactor,  
  32.                     faceRect.Top * resizeFactor,  
  33.                     faceRect.Width * resizeFactor,  
  34.                     faceRect.Height * resizeFactor  
  35.                 )  
  36.             );  
  37.         }  
  38.         drawingContext.Close();  
  39.         RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap(  
  40.             (int)(bitmapSource.PixelWidth * resizeFactor),  
  41.             (int)(bitmapSource.PixelHeight * resizeFactor),  
  42.             96,  
  43.             96,  
  44.             PixelFormats.Pbgra32);  
  45.         faceWithRectBitmap.Render(visual);  
  46.         FacePhoto.Source = faceWithRectBitmap;  
  47.     }  
  48. }  
Now, add the code, mentioned below inside the MainWindow Class. Don't forget to replace the "PASTE_THE_KEY_HERE" field with the key, which you had copied earlier from Azure.
  1. private readonly IFaceServiceClient faceServiceClient = new FaceServiceClient("PASTE_THE_KEY_HERE");  
  2. private async Task < FaceRectangle[] > UploadAndDetectFaces(string imageFilePath) {  
  3.     try {  
  4.         using(Stream imageFileStream = File.OpenRead(imageFilePath)) {  
  5.             var faces = await faceServiceClient.DetectAsync(imageFileStream);  
  6.             var faceRects = faces.Select(face => face.FaceRectangle);  
  7.             return faceRects.ToArray();  
  8.         }  
  9.     } catch (Exception) {  
  10.         return new FaceRectangle[0];  
  11.     }  
  12. }  
Finally, run the Application and click on Browse Image. Choose the image. Within a moment, it shows how many faces are detected in the image by rounding the detected face with Red rectangle, as shown below.



Happy coding.

 

Up Next
    Ebook Download
    View all
    Learn
    View all