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

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

  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 Face API, Using UWP With Azure, XAML And C#

Microsoft Cognitive Services let 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 create Cognitive Service Emotion API in Universal Windows Apps development with 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.

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 Portals).

Now, we can discuss step by step app development.

Step 1

Open Visual Studio 2015. Go to Start -> New Project-> select Universal (under Visual C# -> Windows) -> Blank App -> give your app a suitable name (UWPCoginitiveEmotion) -> OK.

UWPCoginitiveEmotion

After choosing the target and minimum platform versions that your app will support, the Project creates App.xaml and MainPage.xaml.



Add TextBlock control and change the name and text property for the title.

UWPCoginitiveEmotion

Step 2


Add Image control and set the name property for storing the captured image.

UWPCoginitiveEmotion

Add a Button control and set the name for taking a photo from stream to image control.

UWPCoginitiveEmotion

Add a Button control and set the name as Get Emotions.

UWPCoginitiveEmotion

Add the Click event method for both the button controls.

UWPCoginitiveEmotion

Add a Textblock control and set the name and text properties for Emotion result.

UWPCoginitiveEmotion

Step 3

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

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

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

UWPCoginitiveEmotion

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

UWPCoginitiveEmotion

Reference is added to your project.

UWPCoginitiveEmotion

For adding Newtonsoft.Json Reference, choose browse and search Newtonsoft.Json,  select the package and install it.

UWPCoginitiveEmotion

Reference added to your project.

UWPCoginitiveEmotion

Note

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

  1. <Page x:Class="UWPCoginitiveEmotion.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:UWPCoginitiveEmotion" 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="255,98,0,0" TextWrapping="Wrap" Text="UWP Cognitive Service Emotion API Demo" VerticalAlignment="Top" FontSize="36" FontWeight="Bold" />  
  4.         <Image x:Name="imgEmotion" HorizontalAlignment="Left" Height="304" Margin="408,224,0,0" VerticalAlignment="Top" Width="310" />  
  5.         <Button x:Name="btnTakePhoto" Content="Take Photo" HorizontalAlignment="Left" Margin="172,548,0,0" VerticalAlignment="Top" FontSize="20" FontWeight="Bold" Click="btnTakePhoto_Click" />  
  6.         <Button x:Name="btnEmotions" Content="Get Emotions" HorizontalAlignment="Left" Margin="810,548,0,0" VerticalAlignment="Top" Height="39" Width="227" FontSize="20" FontWeight="Bold" Click="btnEmotions_Click" />  
  7.     </Grid>  
  8. </Page>  
http://www.c-sharpcorner.com/article/getting-started-with-microsoft-azure-cognitive-services-face-apis/

Step 4


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

Add the EmotionServiceClient key by using Azure service and generate it (For more information, please refer to 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 Key>";  
  2. EmotionServiceClient emotionserviceclient = new EmotionServiceClient(APIKey);  
  3. Add the code  
  4. for Emotion Details from the captured image  
  5. CameraCaptureUI captureUI = new CameraCaptureUI();  
  6. StorageFile photo;  
  7. IRandomAccessStream imageStream;  
  8. const string APIKey = "<Your Key>";  
  9. EmotionServiceClient emotionserviceclient = new EmotionServiceClient(APIKey);  
  10. Emotion[] emotionresult;  
  11. public MainPage() {  
  12.     this.InitializeComponent();  
  13.     captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;  
  14.     captureUI.PhotoSettings.CroppedSizeInPixels = new Size(200, 200);  
  15. }  
  16. private async void btnTakePhoto_Click(object sender, RoutedEventArgs e) {  
  17.     try {  
  18.         photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);  
  19.         if (photo == null) {  
  20.             return;  
  21.         } else {  
  22.             imageStream = await photo.OpenAsync(FileAccessMode.Read);  
  23.             BitmapDecoder decoder = await BitmapDecoder.CreateAsync(imageStream);  
  24.             SoftwareBitmap softwarebitmap = await decoder.GetSoftwareBitmapAsync();  
  25.             SoftwareBitmap softwarebitmapBGRB = SoftwareBitmap.Convert(softwarebitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);  
  26.             SoftwareBitmapSource bitmapsource = new SoftwareBitmapSource();  
  27.             await bitmapsource.SetBitmapAsync(softwarebitmapBGRB);  
  28.             imgEmotion.Source = bitmapsource;  
  29.         }  
  30.     } catch {  
  31.         tblEmotion.Text = "error taking Photo";  
  32.     }  
  33. }  
  34. private async void btnEmotions_Click(object sender, RoutedEventArgs e) {  
  35.     try {  
  36.         emotionresult = await emotionserviceclient.RecognizeAsync(imageStream.AsStream());  
  37.         if (emotionresult != null) {  
  38.             Scores score = emotionresult[0].Scores;  
  39.             tblEmotion.Text = "Your Emotion are : \n" +  
  40.                 "Happiness: " + score.Happiness + "\n" +  
  41.                 "Sadness: " + score.Sadness + "\n" +  
  42.                 "Surprise: " + score.Surprise + "\n" +  
  43.                 "Neutral: " + score.Neutral + "\n" +  
  44.                 "Anger: " + score.Anger + "\n" +  
  45.                 "Contempt: " + score.Contempt + "\n" +  
  46.                 "Disgust: " + score.Disgust + "\n" +  
  47.                 "Fear: " + score.Fear + "\n";  
  48.         }  
  49.     } catch {  
  50.         tblEmotion.Text = "Error Returning the emotion";  
  51.     }  
  52. }  
Step 6

Deploy your app on Local Machine. The output of the UWPCoginitiveEmotion app is shown below.
 
Clicking "Take Photo" button.

Photo

After clicking the "Take Photo" and "Apply" options, click the "Get Emotions"  button.
Photo

Another Emotion output is,
Photo

Summary

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

Up Next
    Ebook Download
    View all
    Learn
    View all