Introduction

Microsoft Cognitive Services offer awesome APIs and services for developers to create more intelligent applications. You can add interesting features, like people's emotions and video detection, face, speech, and vision recognition and speech and language understanding into your application. 

The Emotion API takes a facial expression in an image stream as an input, and returns confidence levels across a set of emotions for each face in the image, like anger, contempt, disgust, fear, happiness, neutral, sadness, and surprise, in a facial expression

Where we can implement?

There is no single unifying definition or theory of emotion. Nevertheless, several characteristics of an emotional reaction are frequently mentioned. Nowadays, feedback is more important for product promotion and review of the article and store, etc. Manual entry of emotion maybe wrong, so we automate the feedback and review.

In this wiki, we will learn how to implement Emotion Recognition in Xamarin.Forms with Microsoft Cognitive Services.

Getting Started with the Emotion API

The Emotion API can detect anger, contempt, disgust, fear, happiness, neutral, sadness, and surprise, as a facial expression, as well as, it returns an emotion result for a facial expression. The Emotion API also returns a bounding box for detected faces using the Face API. If a user has already called the Face API, he/she can submit the face rectangle as an optional input. Note that an API key must be obtained to use the Emotion API. 

You can follow the below steps for obtaining a free API key on Microsoft.com

Step 1: Click here for Generate Subscriber Key and Click on Create 

Step 2:  You can agree the terms and Microsoft privacy statement > select the country and click on Next

Step 3: Login with Microsoft /LinkedIn /Facebook /Github  for create your API

Step 4: You login and subscribe you should see the keys and the below information on available your subscriptions

We will use emotion API key in the following Xamarin application. before that we can test the API key

Test on Your Emotion Key

You can navigate emotion API online console application and provide the subscription key and image url . if your provide valid key and input the image, you will get it JSon data as output or relevant error 

Create New Xamarin Forms Application

If you already installed VS on your machine, Open Visual Studio > Create New Xamarin Forms application like below

Solution will create with all the platform and PCL project

In this solution, we are going to create demo application for Article review automate based on the emotion.

Access Camera using Xamarin. Forms API

We can use Media.Plugin Nuget package for Capture image or select image gallery from all the mobile platform (iOS,Android,Windows) Right Click on Solution > Type “xam.plugin” in the search box > Select all the project (PCL, iOS, Android and UWP) > Click on Install

Install Emotion Nuget Package

This client library is a thin C# client wrapper for the Microsoft Emotion API.The easiest way to use this client library is to get microsoft.projectoxford.emotion package from nuget .

 Right Click on Solution > Type “Microsoft Emotion” in the search box > Select all the project (PCL, iOS, Android and UWP) > Click on Install

Design UI

After successfully install above two nuget package.

Let start UI design from PCL project In PCL Project > Open MainPage.Xaml page and design following xaml code 

<?xml version="1.0" encoding="utf-8" ?>
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:DevEnvExeEmotion"
             x:Class="DevEnvExeEmotion.MainPage">
    <StackLayout Margin="20">
        <StackLayout Orientation="Horizontal" Padding="30" HorizontalOptions="CenterAndExpand" >
            <StackLayout x:Name="emotion">
            <Label Text="Reader is :"  FontSize="Large"/>
            <Label x:Name="emotionResultLabel" FontSize="Large" />
            </StackLayout>
            <Button Text="Share Your FeedBack" Clicked="OnFeedBackClicked"></Button>
        </StackLayout>
        <Image x:Name="image" Source="article.png" />
        <ActivityIndicator x:Name="activityIndicator" />
    </StackLayout>
 
</ContentPage>

In mainPage.xaml.cs file add your logic.

public partial class MainPage : ContentPage
    {
        EmotionServiceClient emotionClient;
        MediaFile photo;
 
        public MainPage()
        {
            InitializeComponent();
            emotion.IsVisible = false;
            emotionClient = new EmotionServiceClient("7f495be5faf643adbeead444d5b79a13");
        }

For capture image, write the following code

public async Task CaptureImage()
        {
            await CrossMedia.Current.Initialize();
            emotion.IsVisible = false;
            // Take photo
            if (CrossMedia.Current.IsCameraAvailable || CrossMedia.Current.IsTakePhotoSupported)
            {
                photo = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
                {
                    SaveToAlbum = false
                     
                });
 
            }
            else
            {
                await DisplayAlert("No Camera", "Camera unavailable.", "OK");
            }
        }

For Recognize emotion, write the following code

public async Task Recognizeemotion()
        {
            try
            {
                if (photo != null)
                {
                    using (var photoStream = photo.GetStream())
                    {
 
                        Emotion[] emotionResult = await emotionClient.RecognizeAsync(photoStream);
                        if (emotionResult.Any())
                        {
                            // Emotions detected are happiness, sadness, surprise, anger, fear, contempt, disgust, or neutral.
                            emotionResultLabel.Text = emotionResult.FirstOrDefault().Scores.ToRankedList().FirstOrDefault().Key;
                            emotion.IsVisible = true;
                        }
                        photo.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

While click on Feedback button, call the above two methods

async void OnFeedBackClicked(object sender, EventArgs e)
        {
            //capture image
            await CaptureImage();
            ((Button)sender).IsEnabled = false;
            // Recognize emotion
            await Recognizeemotion();
            ((Button)sender).IsEnabled = true;
        }

Run the Mobile Application

Select the iOS /Android /Windows and install into the device and click on ‘Share your Feedback ‘button The device should be camera so after click on the button,

 capture your face for Recognize emotion.

Summary

You learned about how to generate emotion API key and implement Emotion Recognition in Xamarin.Forms with Microsoft Cognitive Services. If you have any questions/ feedback/ issues, please write in the comment box