AI Series - Part Two - Programming Emotions

Previously, we kickstarted our new article series “AI HowTo” and talked how to register for Emotions API Preview (Project Oxford) through Azure Portal.

Now, I’d suggest we should start coding and learning the ways of emotions via codes.

Programming emotions

Before we start, make sure you get your “key” ready. If you haven't already, read the previous article to learn how it is done.

Analyzing Emotions in Images

This project requires an image to be processed at startup, makes some calculations on which emotion is stronger, and then according to that calculation, it posts the emotion on the screen. Let’s start with step by step.

Create a new Visual Studio project, preferably a console application. Install NewtonSoft JSON Parser from NuGeT command line.

  1. Install-Package Newtonsoft.Json  
Create a method to calculate the maximum number on a dictionary/collection:
  1. static string ShowMeEmotion(Dictionary<string,dynamic> results)  
  2. {  
  3.   KeyValuePair<string, dynamic> max = new KeyValuePair<string, dynamic>();  
  4.   foreach (var kvp in results)  
  5.   {  
  6.     if (kvp.Value > max.Value)  
  7.         max = kvp;  
  8.   }  
  9.   return max.Key;  
  10. }  
Create a method to convert the image to byte array. It’s needed while posting the image as byte to Emotions REST API.
  1. static byte[] GetImageAsByteArray(string imageFilePath)  
  2. {  
  3.  FileStream fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);  
  4.  BinaryReader binaryReader = new BinaryReader(fileStream);  
  5.  return binaryReader.ReadBytes((int)fileStream.Length);  
  6. }  
Make a REST POST request to the Emotion Service URL and parse the JSON to display values from it.
  1. static async void MakeRequest(string imageFilePath)  
  2. {  
  3.   var client = new HttpClient();  
  4.   client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key""Update here with your own Emotion API Key");              
  5.   string uri = "";  
  6.   HttpResponseMessage response;  
  7.   string responseContent;  
  8.   byte[] byteData = GetImageAsByteArray(imageFilePath);  
  10.   using (var content = new ByteArrayContent(byteData))  
  11.   {  
  12.     content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");  
  13.     response = await client.PostAsync(uri, content);  
  14.     responseContent = response.Content.ReadAsStringAsync().Result;  
  15.   }  
  17.   dynamic d = JsonConvert.DeserializeObject(responseContent);  
  18.   Dictionary<string, dynamic> emotions = new Dictionary<string, dynamic>()  
  19.   {  
  20.    {"angry", d[0].scores.anger},  
  21.    {"contempt", d[0].scores.contempt},  
  22.    {"disgust", d[0].scores.disgust},  
  23.    {"fear", d[0].scores.fear},  
  24.    {"happiness", d[0].scores.happiness},  
  25.    {"neutral", d[0].scores.neutral},  
  26.    {"sadness", d[0].scores.sadness},  
  27.    {"surprise", d[0].scores.surprise}  
  28.   };    
  29.   Console.WriteLine(ShowMeEmotion(emotions));       
  30. }  
Call the main method.
  1. [STAThread]  
  2. static void Main()  
  3. {  
  4.   OpenFileDialog ofd = new OpenFileDialog();  
  5.   ofd.ShowDialog();  
  6.   string imageFilePath = ofd.FileName;  
  7.   MakeRequest(imageFilePath);  
  8.   Console.Read();  
  9. }  


That’s all!

Well done in kickstarting Azure Cognitive Services Emotions API. Remember that Emotions API(Project Oxford) is still in “Preview Stage” so not all your images are meant to work (Tried like 10 happiness emotion images and only 1 got processed).

Final thoughts

Emotion analysis is essential for all industries. We live in a world where emotions are changed instantly so if we analyze and take precautions before bad things happen, we can avoid dramas or even deaths.

There used to be emotion reading in police departments. These men/women could easily read one’s emotions in an interrogation. I don’t know if police stations have been upgraded to use AI but Artificial Intelligence can also help to avoid crime.


Emotion-reading AI spots if potential criminals are stressed or nervous, and alerts the police BEFORE they act. Read it from here.

Analyzing emotions must be a top priority for all companies and governmental organizations. For governments; to secure public life and avoid terrorist, anarchist attacks. For companies; to increase happiness among employees and solving their problems before it gets bigger.

Companies, nowadays, are trying to convince employees not to leave by increasing their wage, gifting cars, or improving working style but the companies most of the time miss the point where problems occur. Emotion Analysis may help the managers too to discover if employees are happy with the company or not.

The future is AI, use it!

<<Click here for previous part

Similar Articles