Xamarin.Forms - Emotion Recognition Using Cognitive Service

Introduction
 
Xamarin.Forms - Emotion Recognition 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 - Emotion Recognition Using Cognitive Service
 
Xamarin and Cognitive Services together can infuse your apps, websites, and bots with intelligent algorithms to see, hear, speak, understand and interpret your user needs through natural methods of communication. Also, they help you transform your business with AI today.
 
Use AI to solve business problems
  • Vision
  • Speech
  • Knowledge
  • Search
  • Language
Emotion API
  1. Emotion API takes a facial expression in an image as an input and returns the confidence across a set of emotions for each face in the image, as well as the bounding box for the face, using the Face API. If a user has already called the Face API, they can submit the face rectangle as an optional input.
  2. Emotion API is emotions detected are anger, contempt, disgust, fear, happiness, neutral, sadness and surprise. These emotions are understood to be cross-culturally and universally communicated with particular facial expressions.
Prerequisites
  • Visual Studio 2017(Windows or Mac)
  • Emotion 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 - Emotion Recognition Using Cognitive Service
 
Name your app, select “Use .NET Standard” for shared code, and target both Android and iOS.
 
Xamarin.Forms - Emotion Recognition 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 - Emotion Recognition Using Cognitive Service
 
You now have a basic Xamarin.Forms app. Click the play button to try it out.
 
Xamarin.Forms - Emotion Recognition Using Cognitive Service
 
Get Emotion API Key
 
In this step, get Emotion API Key. Go to the following link.
 
https://azure.microsoft.com/en-in/services/cognitive-services/
 
Click "Try Cognitive Services for free".
 
Xamarin.Forms - Emotion Recognition Using Cognitive Service
 
Now, you can choose Face under Vision APIs. Afterward, click "Get API Key".
 
Xamarin.Forms - Emotion Recognition Using Cognitive Service 
 
Read the terms, and select your country/region. Afterward, click "Next".
 
Xamarin.Forms - Emotion Recognition Using Cognitive Service
 
Now, log in using your preferred account.
 
Xamarin.Forms - Emotion Recognition Using Cognitive Service
 
Now, the API Key is activated. You can use it now.
 
Xamarin.Forms - Emotion Recognition 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 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="lblHappiness" ></Label>         
  14.             <Label x:Name="lblAnger"></Label>         
  15.             <Label x:Name="lblFear"></Label>   
  16.             <Label x:Name="lblNeutral"></Label>   
  17.             <Label x:Name="lblSadness"></Label>   
  18.             <Label x:Name="lblSurprise"></Label>   
  19.             <Label x:Name="lblDisgust"></Label>   
  20.             <Label x:Name="lblContempt"></Label>   
  21.         </StackLayout>  
  22.         </StackLayout>        
  23.     </StackLayout>      
  24.     </StackLayout>  
  25. </ContentPage>  
Click the play button to try it out.
 
Xamarin.Forms - Emotion Recognition 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, iO, and UWP).
 
Xamarin.Forms - Emotion Recognition 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. }  
Emotion Recognition
 
In this step, write the following code for Emotion Recognition.
 
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 = "26d1b6941e3a422c880639fdcdcf069b";  
  10.   
  11.         public string uriBase = "https://southeastasia.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.                     lblHappiness.Text = "Happiness : " + faceDetails[0].faceAttributes.emotion.happiness;  
  66.                     lblSadness.Text = "Sadness : " + faceDetails[0].faceAttributes.emotion.sadness;  
  67.                     lblAnger.Text = "Anger : " + faceDetails[0].faceAttributes.emotion.anger;  
  68.                     lblFear.Text = "Fear : " + faceDetails[0].faceAttributes.emotion.fear;  
  69.                     lblNeutral.Text = "Neutral : " + faceDetails[0].faceAttributes.emotion.neutral;  
  70.                     lblSurprise.Text = "Surprise : " + faceDetails[0].faceAttributes.emotion.surprise;  
  71.                     lblDisgust.Text = "Disgust : " + faceDetails[0].faceAttributes.emotion.disgust;  
  72.                     lblContempt.Text = "Contempt : " + faceDetails[0].faceAttributes.emotion.contempt;  
  73.                 }  
  74.   
  75.             }  
  76.         }  
  77.         public byte[] GetImageAsByteArray(string imageFilePath)  
  78.         {  
  79.             using (FileStream fileStream =  
  80.                 new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))  
  81.             {  
  82.                 BinaryReader binaryReader = new BinaryReader(fileStream);  
  83.                 return binaryReader.ReadBytes((int)fileStream.Length);  
  84.             }  
  85.         }  
  86.     }  
  87. }  
Click the Play button to try it out.
 
Xamarin.Forms - Emotion Recognition Using Cognitive Service
 
I hope you have understood how to Recognize emotions in images using Cognitive Service in Xamarin.Forms.
 
Thanks for reading. Please share comments and feedback. Happy Coding...!


Similar Articles