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.
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.         <StackLayout>
  5.         <StackLayout HorizontalOptions=“Center” VerticalOptions=“Start”>
  6.          <Image Margin=“0,50,0,0” x:Name=“imgBanner” Source=“banner.png” ></Image>
  7.          <Image Margin=“0,0,0,10” x:Name=“imgEmail” HeightRequest=“100” Source=“cognitiveservice.png” ></Image>
  8.          <Label Margin=“0,0,0,10” Text=“Emotion Recognition” FontAttributes=“Bold” FontSize=“Large” TextColor=“Gray” HorizontalTextAlignment=“Center” ></Label>
  9.          <Image Margin=“0,0,0,10” x:Name=“imgSelected” HeightRequest=“150” Source=“defaultimage.png” ></Image>
  10.          <Button x:Name=“btnPick” Text=“Pick” Clicked=“btnPick_Clicked” />
  11.          <StackLayout HorizontalOptions=“CenterAndExpand” Margin=“10,0,0,10”>
  12.             <Label x:Name=“lblTotalFace” ></Label>
  13.             <Label x:Name=“lblGender”></Label>
  14.             <Label x:Name=“lblAge”></Label>
  15.         </StackLayout>
  16.         </StackLayout>
  17.     </StackLayout>
  18.     </StackLayout>
  19. </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. namespace XamarinCognitive.Models
  4. {
  5.     public class ResponseModel
  6.     {
  7.         public string faceId { getset; }
  8.         public FaceRectangle faceRectangle { getset; }
  9.         public FaceAttributes faceAttributes { getset; }
  10.     }
  11.     public class FaceRectangle
  12.     {
  13.         public int top { getset; }
  14.         public int left { getset; }
  15.         public int width { getset; }
  16.         public int height { getset; }
  17.     }
  18.     public class HeadPose
  19.     {
  20.         public double pitch { getset; }
  21.         public double roll { getset; }
  22.         public double yaw { getset; }
  23.     }
  24.     public class FacialHair
  25.     {
  26.         public double moustache { getset; }
  27.         public double beard { getset; }
  28.         public double sideburns { getset; }
  29.     }
  30.     public class Emotion
  31.     {
  32.         public double anger { getset; }
  33.         public double contempt { getset; }
  34.         public double disgust { getset; }
  35.         public double fear { getset; }
  36.         public double happiness { getset; }
  37.         public double neutral { getset; }
  38.         public double sadness { getset; }
  39.         public double surprise { getset; }
  40.     }
  41.     public class Blur
  42.     {
  43.         public string blurLevel { getset; }
  44.         public double value { getset; }
  45.     }
  46.     public class Exposure
  47.     {
  48.         public string exposureLevel { getset; }
  49.         public double value { getset; }
  50.     }
  51.     public class Noise
  52.     {
  53.         public string noiseLevel { getset; }
  54.         public double value { getset; }
  55.     }
  56.     public class Makeup
  57.     {
  58.         public bool eyeMakeup { getset; }
  59.         public bool lipMakeup { getset; }
  60.     }
  61.     public class Occlusion
  62.     {
  63.         public bool foreheadOccluded { getset; }
  64.         public bool eyeOccluded { getset; }
  65.         public bool mouthOccluded { getset; }
  66.     }
  67.     public class HairColor
  68.     {
  69.         public string color { getset; }
  70.         public double confidence { getset; }
  71.     }
  72.     public class Hair
  73.     {
  74.         public double bald { getset; }
  75.         public bool invisible { getset; }
  76.         public List<HairColor> hairColor { getset; }
  77.     }
  78.     public class FaceAttributes
  79.     {
  80.         public double smile { getset; }
  81.         public HeadPose headPose { getset; }
  82.         public string gender { getset; }
  83.         public double age { getset; }
  84.         public FacialHair facialHair { getset; }
  85.         public string glasses { getset; }
  86.         public Emotion emotion { getset; }
  87.         public Blur blur { getset; }
  88.         public Exposure exposure { getset; }
  89.         public Noise noise { getset; }
  90.         public Makeup makeup { getset; }
  91.         public List<object> accessories { getset; }
  92.         public Occlusion occlusion { getset; }
  93.         public Hair hair { getset; }
  94.     }
  95. }
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.         public string uriBase = “https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect”;
  11.         public MainPage()
  12.         {
  13.             InitializeComponent();
  14.         }
  15.         async void btnPick_Clicked(object sender, System.EventArgs e)
  16.         {
  17.             await CrossMedia.Current.Initialize();
  18.             try
  19.             {
  20.                 var file = await CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
  21.                 {
  22.                     PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium
  23.                 });
  24.                 if (file == nullreturn;
  25.                 imgSelected.Source = ImageSource.FromStream(() => {
  26.                     var stream = file.GetStream();
  27.                     return stream;
  28.                 });
  29.                 MakeAnalysisRequest(file.Path);
  30.             }
  31.             catch (Exception ex)
  32.             {
  33.                 string test = ex.Message;
  34.             }
  35.         }
  36.         public async void MakeAnalysisRequest(string imageFilePath)
  37.         {
  38.             HttpClient client = new HttpClient();
  39.             client.DefaultRequestHeaders.Add(“Ocp-Apim-Subscription-Key”, subscriptionKey);
  40.             string requestParameters = “returnFaceId=true&returnFaceLandmarks=false” +
  41.                 “&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses,” +
  42.                 “emotion,hair,makeup,occlusion,accessories,blur,exposure,noise”;
  43.             string uri = uriBase + “?” + requestParameters;
  44.             HttpResponseMessage response;
  45.             byte[] byteData = GetImageAsByteArray(imageFilePath);
  46.             using (ByteArrayContent content = new ByteArrayContent(byteData))
  47.             {
  48.                 content.Headers.ContentType = new MediaTypeHeaderValue(“application/octet-stream”);
  49.                 response = await client.PostAsync(uri, content);
  50.                 string contentString = await response.Content.ReadAsStringAsync();
  51.                 List<ResponseModel> faceDetails = JsonConvert.DeserializeObject<List<ResponseModel>>(contentString);
  52.                 if(faceDetails.Count!=0)
  53.                 {
  54.                     lblTotalFace.Text = “Total Faces : “ + faceDetails.Count;
  55.                     lblGender.Text = “Gender : “ + faceDetails[0].faceAttributes.gender;
  56.                     lblAge.Text = “Total Faces : “ + faceDetails[0].faceAttributes.age;
  57.                 }
  58.             }
  59.         }
  60.         public byte[] GetImageAsByteArray(string imageFilePath)
  61.         {
  62.             using (FileStream fileStream =
  63.                 new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
  64.             {
  65.                 BinaryReader binaryReader = new BinaryReader(fileStream);
  66.                 return binaryReader.ReadBytes((int)fileStream.Length);
  67.             }
  68.         }
  69.     }
  70. }
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.

BÌNH LUẬN

Please enter your comment!
Please enter your name here