Xamarin.Forms - Face Detection Using Cognitive Service

Introduction
 
Xamarin.Forms - Face Detection Using Cognitive Service
 
Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.
 
Cognitive Services
 
Xamarin.Forms - Face Detection Using Cognitive Service
 
Infuse your apps, websites, and bots with intelligent algorithms to see, hear, speak, understand and interpret your user needs through natural methods of communication. Transform your business with AI today.
 
Use AI to solve business problems
  • Vision
  • Speech
  • Knowledge
  • Search
  • Language
Face API
  1. Face API provides developers with access to advanced face algorithms. Microsoft Face algorithms enable face attribute detection and face recognition. 
  2. Face API is a cognitive service that provides algorithms for detecting, recognizing, and analyzing human faces in images.
  3. Face API can detect human faces in an image and return the rectangle coordinates of their locations. Optionally, face detection can extract a series of face-related attributes such as pose, gender, age, head pose, facial hair, and glasses.
Prerequisites
  • Visual Studio 2017(Windows or Mac)
  • Face API Key
Setting up a Xamarin.Forms Project
 
Start by creating a new Xamarin.Forms project. you’ll learn more by going through the steps yourself.
 
Choose the Xamarin.Forms App Project type under Cross-platform/App in the New Project dialog.
 
Xamarin.Forms - Face Detection Using Cognitive Service
 
Name your app, select “Use .NET Standard” for shared code, and target both Android and iOS.
 
Xamarin.Forms - Face Detection Using Cognitive Service
 
You probably want your project and solution to use the same name as your app. Put it in your preferred folder for projects and click Create.
 
Xamarin.Forms - Face Detection Using Cognitive Service
 
You now have a basic Xamarin.Forms app. Click the play button to try it out.
 
Xamarin.Forms - Face Detection Using Cognitive Service
 
Get Face API Key
 
In this step, get Face API Key. Go to the following link.
 
https://azure.microsoft.com/en-in/services/cognitive-services/
 
Click "Try Cognitive Services for free".
 
Xamarin.Forms - Face Detection Using Cognitive Service
 
Now, you can choose Face under Vision APIs. Afterward, click "Get API Key".
 
Xamarin.Forms - Face Detection Using Cognitive Service 
 
Read the terms, and select your country/region. Afterward, click "Next".
 
Xamarin.Forms - Face Detection Using Cognitive Service
 
Now, log in using your preferred account.
Xamarin.Forms - Face Detection Using Cognitive Service 
 
Now, the API Key is activated. You can use it now.
 
Xamarin.Forms - Face Detection Using Cognitive Service 
The trial key is available only 7 days. If you want a permanent key, refer to the following article.
Setting up the User Interface
 
Go to MainPage.Xaml and write the following code.
 
MainPage.xaml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:XamarinCognitive" x:Class="XamarinCognitive.MainPage">  
  3.     <StackLayout>  
  4.           
  5.         <StackLayout>        
  6.         <StackLayout HorizontalOptions="Center" VerticalOptions="Start">        
  7.          <Image Margin="0,50,0,0" x:Name="imgBanner" Source="banner.png" ></Image>        
  8.          <Image Margin="0,0,0,10" x:Name="imgEmail" HeightRequest="100" Source="cognitiveservice.png" ></Image>        
  9.          <Label Margin="0,0,0,10" Text="Emotion Recognition" FontAttributes="Bold" FontSize="Large" TextColor="Gray" HorizontalTextAlignment="Center" ></Label>       
  10.          <Image Margin="0,0,0,10" x:Name="imgSelected" HeightRequest="150" Source="defaultimage.png" ></Image>        
  11.          <Button x:Name="btnPick" Text="Pick" Clicked="btnPick_Clicked" />        
  12.          <StackLayout HorizontalOptions="CenterAndExpand" Margin="10,0,0,10">  
  13.             <Label x:Name="lblTotalFace" ></Label>         
  14.             <Label x:Name="lblGender"></Label>         
  15.             <Label x:Name="lblAge"></Label>   
  16.         </StackLayout>  
  17.         </StackLayout>        
  18.     </StackLayout>      
  19.     </StackLayout>  
  20. </ContentPage>  
Click the Play button to try it out.
 
Xamarin.Forms - Face Detection Using Cognitive Service
 
NuGet Packages
 
Now, add the following NuGet Packages. 
  1. Xam.Plugin.Media
  2. Newtonsoft.Json
Add Xam.Plugin.Media NuGet
 
In this step, add Xam.Plugin.Media to your project. You can install Xam.Plugin.Media via NuGet or you can browse the source code on GitHub.
 
Go to Solution Explorer and select your solution. Right-click and select "Manage NuGet Packages for Solution". Search "Xam.Plugin.Media" and add Package. Remember to install it for each project (PCL, Android, iOS, and UWP).
 
Xamarin.Forms - Face Detection Using Cognitive Service
 
Permissions
 
In this step, give the following required permissions to your app.
 
Permissions - for Android
  1. CAMERA
  2. READ_EXTERNAL_STORAGE
  3. WRITE_EXTERNAL_STORAGE
Permissions - for iOS
  1. NSCameraUsageDescription
  2. NSPhotoLibraryUsageDescription
  3. NSMicrophoneUsageDescription
  4. NSPhotoLibraryAddUsageDescription
Create a Model
 
In this step, you can create a model for deserializing your response.
 
ResponseModel.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace XamarinCognitive.Models  
  5. {  
  6.     public class ResponseModel  
  7.     {  
  8.         public string faceId { getset; }  
  9.         public FaceRectangle faceRectangle { getset; }  
  10.         public FaceAttributes faceAttributes { getset; }  
  11.     }  
  12.     public class FaceRectangle  
  13.     {  
  14.         public int top { getset; }  
  15.         public int left { getset; }  
  16.         public int width { getset; }  
  17.         public int height { getset; }  
  18.     }  
  19.   
  20.     public class HeadPose  
  21.     {  
  22.         public double pitch { getset; }  
  23.         public double roll { getset; }  
  24.         public double yaw { getset; }  
  25.     }  
  26.   
  27.     public class FacialHair  
  28.     {  
  29.         public double moustache { getset; }  
  30.         public double beard { getset; }  
  31.         public double sideburns { getset; }  
  32.     }  
  33.   
  34.     public class Emotion  
  35.     {  
  36.         public double anger { getset; }  
  37.         public double contempt { getset; }  
  38.         public double disgust { getset; }  
  39.         public double fear { getset; }  
  40.         public double happiness { getset; }  
  41.         public double neutral { getset; }  
  42.         public double sadness { getset; }  
  43.         public double surprise { getset; }  
  44.     }  
  45.   
  46.     public class Blur  
  47.     {  
  48.         public string blurLevel { getset; }  
  49.         public double value { getset; }  
  50.     }  
  51.   
  52.     public class Exposure  
  53.     {  
  54.         public string exposureLevel { getset; }  
  55.         public double value { getset; }  
  56.     }  
  57.   
  58.     public class Noise  
  59.     {  
  60.         public string noiseLevel { getset; }  
  61.         public double value { getset; }  
  62.     }  
  63.   
  64.     public class Makeup  
  65.     {  
  66.         public bool eyeMakeup { getset; }  
  67.         public bool lipMakeup { getset; }  
  68.     }  
  69.   
  70.     public class Occlusion  
  71.     {  
  72.         public bool foreheadOccluded { getset; }  
  73.         public bool eyeOccluded { getset; }  
  74.         public bool mouthOccluded { getset; }  
  75.     }  
  76.   
  77.     public class HairColor  
  78.     {  
  79.         public string color { getset; }  
  80.         public double confidence { getset; }  
  81.     }  
  82.   
  83.     public class Hair  
  84.     {  
  85.         public double bald { getset; }  
  86.         public bool invisible { getset; }  
  87.         public List<HairColor> hairColor { getset; }  
  88.     }  
  89.   
  90.     public class FaceAttributes  
  91.     {  
  92.         public double smile { getset; }  
  93.         public HeadPose headPose { getset; }  
  94.         public string gender { getset; }  
  95.         public double age { getset; }  
  96.         public FacialHair facialHair { getset; }  
  97.         public string glasses { getset; }  
  98.         public Emotion emotion { getset; }  
  99.         public Blur blur { getset; }  
  100.         public Exposure exposure { getset; }  
  101.         public Noise noise { getset; }  
  102.         public Makeup makeup { getset; }  
  103.         public List<object> accessories { getset; }  
  104.         public Occlusion occlusion { getset; }  
  105.         public Hair hair { getset; }  
  106.     }  
  107. }  
Face Detection
 
In this step, write the following code for face detection.
 
MainPage.xaml.cs
  1. using Plugin.Media;  
  2. using Xamarin.Forms;  
  3. using XamarinCognitive.Models;  
  4. using Newtonsoft.Json;  
  5. namespace XamarinCognitive  
  6. {  
  7.     public partial class MainPage : ContentPage  
  8.     {  
  9.         public string subscriptionKey = "7c85c822a**********4886209ccbb3fb";  
  10.   
  11.         public string uriBase = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect";  
  12.   
  13.         public MainPage()  
  14.         {  
  15.             InitializeComponent();  
  16.         }  
  17.   
  18.         async void btnPick_Clicked(object sender, System.EventArgs e)  
  19.         {  
  20.             await CrossMedia.Current.Initialize();  
  21.             try  
  22.             {  
  23.                 var file = await CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions  
  24.                 {  
  25.                     PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium  
  26.                 });  
  27.                 if (file == nullreturn;  
  28.                 imgSelected.Source = ImageSource.FromStream(() => {  
  29.                     var stream = file.GetStream();  
  30.                     return stream;  
  31.                 });  
  32.                 MakeAnalysisRequest(file.Path);  
  33.             }  
  34.             catch (Exception ex)  
  35.             {  
  36.                 string test = ex.Message;  
  37.             }  
  38.   
  39.         }  
  40.   
  41.   
  42.         public async void MakeAnalysisRequest(string imageFilePath)  
  43.         {  
  44.             HttpClient client = new HttpClient();  
  45.             client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);  
  46.   
  47.             string requestParameters = "returnFaceId=true&returnFaceLandmarks=false" +  
  48.                 "&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses," +  
  49.                 "emotion,hair,makeup,occlusion,accessories,blur,exposure,noise";  
  50.   
  51.             string uri = uriBase + "?" + requestParameters;  
  52.             HttpResponseMessage response;  
  53.             byte[] byteData = GetImageAsByteArray(imageFilePath);  
  54.   
  55.             using (ByteArrayContent content = new ByteArrayContent(byteData))  
  56.             {  
  57.                 content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");  
  58.                 response = await client.PostAsync(uri, content);  
  59.   
  60.                 string contentString = await response.Content.ReadAsStringAsync();  
  61.   
  62.                 List<ResponseModel> faceDetails = JsonConvert.DeserializeObject<List<ResponseModel>>(contentString);  
  63.                 if(faceDetails.Count!=0)  
  64.                 {  
  65.                     lblTotalFace.Text = "Total Faces : " + faceDetails.Count;  
  66.                     lblGender.Text = "Gender : " + faceDetails[0].faceAttributes.gender;  
  67.                     lblAge.Text = "Total Faces : " + faceDetails[0].faceAttributes.age;  
  68.                 }  
  69.   
  70.             }  
  71.         }  
  72.         public byte[] GetImageAsByteArray(string imageFilePath)  
  73.         {  
  74.             using (FileStream fileStream =  
  75.                 new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))  
  76.             {  
  77.                 BinaryReader binaryReader = new BinaryReader(fileStream);  
  78.                 return binaryReader.ReadBytes((int)fileStream.Length);  
  79.             }  
  80.         }  
  81.     }  
  82. }  
Click the Play button to try it out.
 
Xamarin.Forms - Face Detection Using Cognitive Service
 
Happy Coding...!
 
I hope you have understood how to detect human faces using Cognitive Service in Xamarin.Forms.
 
Thanks for reading. Please share comments and feedback.


Similar Articles