Face Detection Using Microsoft Cognitive Services (by Nishan Aryal)

In this article, you will learn how to create a simple desktop WPF Application that uses Face API to detect the number of faces in an image and mark the faces in the images.

What we will learn?

  1. How to subscribe Face API
  2. Generate Face API subscription key.
  3. Create new WPF Application (Classic Desktop).
  4. Configuring Face API library.
  5. Upload Image and detect no of Faces in Image.

Subscribe To Face API

Step 1Go to https://www.microsoft.com/cognitive-services/en-us/

Signup with your email address to subscribe to Face API in Microsoft Cognitive Services.

Step 2 Once you are logged in, navigate to get started for free.


Step 3

Now, choose face API to subscribe to Microsoft Cognitive Services Face API. Proceed further with subscribe


Step 4

Now, generate your subscription key.


Create Application (Classic Desktop)

Step 1Create new Project, as shown below.

Visual C# > Windows Desktop > WPF Application.


Step 2

Name the project as FaceDetectionDemo and click OK.

You will be able to see the screen given below.


Step 3 

Now, we need to reference Newtonsoft.JSON in our Application.

For this, right click on Project and select Manage NuGget Package.

Browse for Newtonsoft.JSON and install.

Now, browse for Microsoft.ProjectOxford.Face and install.


Adding File Browser to Upload Image.

Step 1Add a button on MainWindow.xaml, using designer or code. Here, I prefer adding the button, using code.

Replace <Grid></Grid> with the lines of code given below.

  1. <Grid x:Name="BackPanel">  
  2.     <Label x:Name="Label" FontStretch="Normal" Margin="0,0,0,0" Content="Please Upload Image to detect faces in Image" />  
  3.     <Image x:Name="FacePhoto" Stretch="Uniform" Margin="0,0,0,30" Source="http://ajaxuploader.com/images/drag-drop-file- upload.png" />  
  4.     <Button x:Name="BrowseButton" Margin="20,0,20,5" Height="35" Background="Blue" VerticalAlignment="Bottom" Content="Browse Image" Click="BrowseButton_Click" /> 
  5. </Grid>  

 

Step 2 Add the codes to upload an image and detect the faces.

Now, go to MainWindow.xaml.cs

Add this, using Directive to the beginning of the file.

 

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

 


Also add line of codes given below to MainWindows class, as shown below.

  1. private readonly IFaceServiceClient faceServiceClient = new
  2. FaceServiceClient("XXXXXXXXXXXXXXXXXXXXXXXXX");

Add lines of code given below to click event of Browse button.

  1. private async void BrowseButton_Click(object sender, RoutedEventArgs e)    
  2.        {    
  3.            //Window to select Image     
  4.            var openDlg = new Microsoft.Win32.OpenFileDialog();    
  5.     
  6.            //Allow to select only files with .jpg extensions    
  7.            openDlg.Filter = "JPEG Image(*.jpg)|*.jpg";    
  8.            bool? result = openDlg.ShowDialog(this);    
  9.     
  10.            if (!(bool)result)    
  11.            {    
  12.                return;    
  13.            }    
  14.     
  15.            string filePath = openDlg.FileName;    
  16.     
  17.            Uri fileUri = new Uri(filePath);    
  18.            BitmapImage bitmapSource = new BitmapImage();    
  19.     
  20.            bitmapSource.BeginInit();    
  21.            bitmapSource.CacheOption = BitmapCacheOption.None;    
  22.            bitmapSource.UriSource = fileUri;    
  23.            bitmapSource.EndInit();    
  24.     
  25.            FacePhoto.Source = bitmapSource;    
  26.     
  27.            //rewrite Text on mainWindow with Detecting status    
  28.            Label.Content = "Detecting…";    
  29.            Title = "Detecting…";    
  30.            //Call awaitble UploadAndDetectFaces Function to detect faces and return.     
  31.            FaceRectangle[] faceRects = await UploadAndDetectFaces(filePath);    
  32.            Title = String.Format("Detection Finished. {0} face(s) detected", faceRects.Length);    
  33.            Label.Content = String.Format("Detection Finished. {0} face(s) detected", faceRects.Length);    
  34.     
  35.            if (faceRects.Length > 0)    
  36.            {    
  37.                DrawingVisual visual = new DrawingVisual();    
  38.                DrawingContext drawingContext = visual.RenderOpen();    
  39.                drawingContext.DrawImage(bitmapSource,    
  40.                    new Rect(0, 0, bitmapSource.Width, bitmapSource.Height));    
  41.                double dpi = bitmapSource.DpiX;    
  42.                double resizeFactor = 96 / dpi;    
  43.     
  44.                //Mark Detected faces with Blue Rectanglar shape.     
  45.                foreach (var faceRect in faceRects)    
  46.                {    
  47.                    drawingContext.DrawRectangle(    
  48.                        Brushes.Transparent,    
  49.                        new Pen(Brushes.Blue, 2),    
  50.                        new Rect(    
  51.                            faceRect.Left * resizeFactor,    
  52.                            faceRect.Top * resizeFactor,    
  53.                            faceRect.Width * resizeFactor,    
  54.                            faceRect.Height * resizeFactor    
  55.                            )    
  56.                    );    
  57.                }    
  58.     
  59.                drawingContext.Close();    
  60.                RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap(    
  61.                    (int)(bitmapSource.PixelWidth * resizeFactor),    
  62.                    (int)(bitmapSource.PixelHeight * resizeFactor),    
  63.                    96,    
  64.                    96,    
  65.                    PixelFormats.Pbgra32);    
  66.     
  67.                faceWithRectBitmap.Render(visual);    
  68.                FacePhoto.Source = faceWithRectBitmap;    
  69.            }    
  70.     
  71.        }  

Add a new awaitable function named UploadAndDetectFaces(), which accepts imageFilePath as an object parameter.

  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.         }    

Application Execution

Step 1 Build the Application and run.

Step 2 Browse the image.



Conclusion

You can use Microsoft Cognitive Servies Face API to detect the faces.

Bir Cevap Yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir

TOP