Multiple People Emotions In UWP With Cognitive Service Emotion API, Azure, XAML And C#

Before reading this article, please go through the following article.

  1. Introduction To Universal Windows Platform (UWP) App Development Using Windows 10 And Visual Studio 2015
  2. How To Create Microsoft Cognitive Service Emotion API On Azure Portal
  3. Cognitive Service Emotion API In UWP With Azure, XAML And C#

Microsoft Cognitive Services lets you build apps with powerful algorithms, using just a few lines of code. They work across devices and platforms such as iOS, Android, and Windows, keep improving, and are easy to set up.

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

Reading this article, you can learn how to use Multiple People Emotions in Universal Windows apps development with Cognitive Service Emotion API, Azure, XAML and Visual C#. Here, input is a captured image and Emotion API returns different emotions like anger, contempt, disgust, fear, happiness, neutral, sadness, and surprise in different people.

The following important tools are required for developing UWP,

  1. Windows 10 (Recommended)
  2. Visual Studio 2015 Community Edition (It is a free software available online).
  3. Emotion API Key - (How To Create Microsoft Cognitive Service Emotion API On Azure Portal)

Now, we can discuss step by step app development.

Step1

Open Visual Studio 2015 -> Start -> New Project-> Select Universal (under Visual C#->Windows)-> Blank App -> Give a suitable name to your app (UWPCogGroupEmot) ->OK.

Multiple People Emotions in UWP

After choosing the Target and Minimum platform version that your Windows Universal application will support the Project creates App.xaml and MainPage.xaml.

Multiple People Emotions in UWP

Step 2

Add a Grid with two columns - for photo and for emotion results.

Multiple People Emotions in UWP

Add a Stack Panel and Border Control. Inside the Border Control, add a Canvas Control for displaying a photo.

Multiple People Emotions in UWP

Add a Button Control and set the name for View Emotions.

Multiple People Emotions in UWP

Add another Grid for Column 2 and add the Listview Control for Emotion Results.

Multiple People Emotions in UWP

Add the "Click Event" method for the Button Control.

Multiple People Emotions in UWP

Add the TextBlock Control for Emotion Result title.

Multiple People Emotions in UWP

Add the Rectangle image for drawing a rectangle on each face.

Multiple People Emotions in UWP

Step 3

Open (double click) the file MainPage.xaml in Solution Explorer and add the following references in the project.

  1. Microsoft.ProjectOxford.Face
  2. Newtonsoft.Json

For adding Microsoft.ProjectOxford.Emotion Reference, right click your project (UWPCogGroupEmot) and select "Manage NuGet Packages".

Choose Browse and search Microsoft.ProjectOxford.Emotion. Select the package and install it.

Reference is now added to your project. For adding Newtonsoft.Json Reference, choose Browse and search Newtonsoft.Json. Select the package and install it.

Multiple People Emotions in UWP

Reference is added to your project

Multiple People Emotions in UWP

Automatically, the following code will be generated in XAML code view, while we are done in the design view.

  1. <Page x:Class="UWPCogGroupEmot.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:UWPCogGroupEmot" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">  
  2.     <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">  
  3.         <TextBlock x:Name="tblTitle" HorizontalAlignment="Left" Margin="313,88,0,0" TextWrapping="Wrap" Text="UWP Coginitive Service Muliple People Emotions Demo" VerticalAlignment="Top" FontSize="24" FontWeight="Bold" />  
  4.         <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" BorderThickness="5" Margin="82,125,50,50">  
  5.             <Grid.ColumnDefinitions>  
  6.                 <ColumnDefinition Width="*" />  
  7.                 <ColumnDefinition Width="*" />  
  8.             </Grid.ColumnDefinitions>  
  9.             <StackPanel Grid.Column="0" VerticalAlignment="Center">  
  10.                 <Border x:Name="BorPhoto" BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="437" Margin="51,0,0,0" Width="495">  
  11.                     <Canvas x:Name="CANPhoto" Width="598" Height="598" />  
  12.                 </Border>  
  13.             </StackPanel>  
  14.             <Button x:Name="btnEmotions" Content="View Emotions" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="39" Margin="374,0,10,506" Click="btnEmotions_Click" RenderTransformOrigin="0.989,0.406" FontWeight="Bold" />  
  15.             <Grid Grid.Column="2">  
  16.                 <ListView x:Name="lstEmotionRes" HorizontalAlignment="Stretch" Margin="248,63,10,52" VerticalAlignment="Stretch" Height="420" />  
  17.             </Grid>  
  18.         </Grid>  
  19.         <TextBlock x:Name="tblEmotion" HorizontalAlignment="Left" Margin="959,140,0,0" TextWrapping="Wrap" Text="Emotions are," VerticalAlignment="Top" Height="30" Width="187" FontWeight="Bold" FontSize="22" />  
  20.     </Grid>  
  21. </Page>  
Step 4

Add the following namespaces in Mainpage.xaml.cs for capturing a photo and getting emotions.
  1. using Microsoft.ProjectOxford.Emotion;  
  2. using Microsoft.ProjectOxford.Emotion.Contract;  
  3. using Windows.UI.Xaml.Media.Imaging;  
  4. using System.Threading.Tasks;  
  5. using Windows.Graphics.Imaging;  
  6. using Windows.Storage.Streams;  
Step 5

Add the EmotionServiceClient key, use Azure service, and generate it (For More Information, please refer the article How To Create Microsoft Cognitive Service Emotion API On Azure Portal.

Add the following code with Azure generated key for EmotionServiceClient.
  1. const string APIKey = "Your Emotion Key";  
  2. EmotionServiceClient emotionServiceClient = new EmotionServiceClient(APIKey);  
  3. Add the code  
  4. for Multiple People Emotion Details from the image url,  
  5. const string APIKey = "Your Emotion Key";  
  6. string urlStr = "https://pbs.twimg.com/media/CtrrCSYUMAEanQI.jpg";  
  7. Uri uri;  
  8. BitmapImage bitMapImage;  
  9. public MainPage() {  
  10.     this.InitializeComponent();  
  11.     CANPhoto.Children.Clear();  
  12.     try {  
  13.         uri = new Uri(urlStr, UriKind.Absolute);  
  14.     } catch (UriFormatException ex) {  
  15.         return;  
  16.     }  
  17.     bitMapImage = new BitmapImage();  
  18.     bitMapImage.UriSource = uri;  
  19.     ImageBrush imgBrush = new ImageBrush();  
  20.     imgBrush.ImageSource = bitMapImage;  
  21.     CANPhoto.Background = imgBrush;  
  22. }  
  23. private async void btnEmotions_Click(object sender, RoutedEventArgs e) {  
  24.     Emotion[] emotionResult = await PhotoUploadAndDetectEmotions();  
  25.     resultdisplay(emotionResult);  
  26.     DrawFaceRectangle(emotionResult, bitMapImage);  
  27. }  
  28. private async Task < Emotion[] > PhotoUploadAndDetectEmotions() {  
  29.   
  30.     EmotionServiceClient emotionServiceClient = new EmotionServiceClient(APIKey);  
  31.     try {  
  32.         Emotion[] emotionResult = await emotionServiceClient.RecognizeAsync(urlStr);  
  33.         return emotionResult;  
  34.     } catch (Exception exception) {  
  35.         return null;  
  36.     }  
  37. }  
  38. private void resultdisplay(Emotion[] resultList) {  
  39.     int index = 0;  
  40.     foreach(Emotion emotion in resultList) {  
  41.         lstEmotionRes.Items.Add("\nFace #" + index +  
  42.             "\nAnger: " + emotion.Scores.Anger +  
  43.             "\nContempt: " + emotion.Scores.Contempt +  
  44.             "\nDisgust: " + emotion.Scores.Disgust +  
  45.             "\nFear: " + emotion.Scores.Fear +  
  46.             "\nHappiness: " + emotion.Scores.Happiness +  
  47.             "\nSurprise: " + emotion.Scores.Surprise);  
  48.         index++;  
  49.     }  
  50. }  
  51. public async void DrawFaceRectangle(Emotion[] emotionResult, BitmapImage bitMapImage) {  
  52.     if (emotionResult != null && emotionResult.Length > 0) {  
  53.         IRandomAccessStream stream = await RandomAccessStreamReference.CreateFromUri(new Uri(urlStr)).OpenReadAsync();  
  54.         BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);  
  55.         double resizeFactorH = CANPhoto.Height / decoder.PixelHeight;  
  56.         double resizeFactorW = CANPhoto.Width / decoder.PixelWidth;  
  57.         foreach(var emotion in emotionResult) {  
  58.             Microsoft.ProjectOxford.Common.Rectangle faceRect = emotion.FaceRectangle;  
  59.             Image Img = new Image();  
  60.             BitmapImage BitImg = new BitmapImage();  
  61.             Windows.Storage.Streams.IRandomAccessStream box = await Windows.Storage.Streams.RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/rectangle.png", UriKind.Absolute)).OpenReadAsync();  
  62.             BitImg.SetSource(box);  
  63.             var maxWidth = faceRect.Width * resizeFactorW;  
  64.             var maxHeight = faceRect.Height * resizeFactorH;  
  65.             var origHeight = BitImg.PixelHeight;  
  66.             var origWidth = BitImg.PixelWidth;  
  67.             var ratioX = maxWidth / (float) origWidth;  
  68.             var ratioY = maxHeight / (float) origHeight;  
  69.             var ratio = Math.Min(ratioX, ratioY);  
  70.             var newHeight = (int)(origHeight * ratio);  
  71.             var newWidth = (int)(origWidth * ratio);  
  72.             BitImg.DecodePixelWidth = newWidth;  
  73.             BitImg.DecodePixelHeight = newHeight;  
  74.             Thickness margin = Img.Margin;  
  75.             margin.Left = faceRect.Left * resizeFactorW;  
  76.             margin.Top = faceRect.Top * resizeFactorH;  
  77.             Img.Margin = margin;  
  78.             Img.Source = BitImg;  
  79.             CANPhoto.Children.Add(Img);  
  80.         }  
  81.     }  
  82. }  
Multiple People Emotions in UWP

Step 6

Deploy your app in a Local Machine. The output of the UWPCogGroupEmot app is shown below.

Multiple People Emotions in UWP

After clicking the View Emotions button.

Multiple People Emotions in UWP

Summary

Now, you have successfully tested Multiple People Emotions with Cognitive Service Emotion API, Azure, XAML AND C# in UWP environment.


Similar Articles