Introduction

Today, Artificial Intelligence is a very common aspect of our daily life. You can notice that most of the companies are using it to create very powerful and smart apps. On Facebook, while you're uploading a photo, it can automatically recognize your face. Also, the bots are available through Facebook Messenger, Cortana, Telegram, and many more. Using Artificial Intelligence makes your app more secure and robust and provides an interesting User Experience.

For example, if you want to create a home renting website, using Artificial Intelligence will make your project more powerful because you can add an Image Content recognizer to it. So, the home ads publishers won’t be able to upload any type of images except Home's; and your website will be more trusted. Also, using bots to make your users able to chat to your app will be amazing and the users will like your project more.

In this article, I’m going to talk about what Microsoft Cognitive Services is and how to use these APIs within your C# apps.

Microsoft Cognitive Services

Microsoft Cognitive Services is a set of APIs and SDKs that Microsoft created for the developers to make it easy for them to add intelligence to their apps, such as emotion and video detection; facial, speech, and vision recognition; and speech and language understanding – into their apps.

In this article, I will create a simple Windows Forms application and use the Vision API to recognize the content of an image and get the result in a JSON format so that you can manipulate it in a way you prefer.

Note - In this tutorial, I used the Vision API but you can use any of the available APIs with the same steps. Also, you can use any type of applications not only Windows Forms.

Let’s start step by step

Sign up for Microsoft Cognitive Services for free from this link, https://azure.microsoft.com/en-us/try/cognitive-services/. Follow the steps and set your region.

Cognitive Services

After you log in, choose "Add Vision API" and you will get your endpoint URL and the API key that you will use in your app.

Cognitive Services

This is all you need to start creating your intelligent app.

Open Visual Studio and create a new Windows Forms Project.

Cognitive Services

Add two buttons, a picturebox and a textbox as following.

Cognitive Services

In the code behind file, add the following namespaces:

  1. using System.Net.Http;
  2. using System.IO;

Double click on the Browse button to create a click event handler for this button and write the following code to select an image from your local drive.

  1. string imageFilePath = "";
  2. private void btnBrowse_Click(object sender, EventArgs e)
  3. {
  4. // Create an OpenFileDialogObject
  5. OpenFileDialog ofd = new OpenFileDialog();
  6. // Set the filters of the OpenFileDialog to the images formats JPEG and PNG
  7. ofd.Filter = "JPEG *.jpg|*.jpg|PNG *.png|*.png";
  8. if(ofd.ShowDialog() == DialogResult.OK)
  9. {
  10. // Store the selected file in a general variable
  11. imageFilePath = ofd.FileName;
  12. // Preview the selected picture in a pictureBox control
  13. pictureBox1.Image = Image.FromFile(imageFilePath);
  14. }
  15. }
Now, declare two string variables to store your endpoint URL and your API key respectively, that you've get from the step 2 and write the two following methods (The code is self-explanatory).
  1. const string subscriptionKey = "Paste your API key here";
  2. const string uriBase = "Paste your Endpoint URL here";
  3. // Method to make the restful request
  4. async Task<string> MakeAnalaysisRequest(string imageFilePath)
  5. {
  6. // Create an HttpClient object to make a post request to the Azure Services
  7. HttpClient client = new HttpClient();
  8. // set the following paramters to your request header
  9. client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
  10. // specify the requested resutls
  11. string requestParamters = "visualFeatures=Categories,Description,Color&language=en";
  12. // create the uri from your endpoint url and the requestedParamters
  13. string uri = uriBase + "?" + requestParamters;
  14. // create a respone message object to get the response of the sent request
  15. HttpResponseMessage responseMessage;
  16. // get the bytes of the selected image
  17. byte[] dataByte = GetImageAsBytesArray(imageFilePath);
  18. // create a content for the post request _ the content will be the bytes of the picture to send it to the Azure servers
  19. using (ByteArrayContent content = new ByteArrayContent(dataByte))
  20. {
  21. // Define the content type of the request
  22. content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
  23. // send the post request
  24. responseMessage = await client.PostAsync(uri, content);
  25. // read the string response from the sent request
  26. string contentString = await responseMessage.Content.ReadAsStringAsync();
  27. // return the string result
  28. return contentString;
  29. }
  30. }
  31. // Method to get the bytes of a specific image file
  32. private byte[] GetImageAsBytesArray(string imageFilePath)
  33. {
  34. // Create a file stream to access to the bytes of the selected file
  35. FileStream fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);
  36. // Create a BinaryReader object to read the bytes from a specific stream
  37. BinaryReader reader = new BinaryReader(fileStream);
  38. // Return the read bytes of a specific file
  39. return reader.ReadBytes((int)fileStream.Length);
  40. }
Double click on the “Tell me what you see” button to create a click event handler and write the following code.
  1. // Tell me what you see button click event handler
  2. private async void btnRecoginze_Click(object sender, EventArgs e)
  3. {
  4. // get the result
  5. string result = await MakeAnalaysisRequest(imageFilePath);
  6. // show the result in the textbox
  7. txtResult.Text = result;
  8. }
The full code should be like this.
  1. using System;
  2. using System.Drawing;
  3. using System.Threading.Tasks;
  4. using System.Windows.Forms;
  5. using System.Net.Http;
  6. using System.IO;
  7. namespace VisionApi
  8. {
  9. public partial class Form1 : Form
  10. {
  11. public Form1()
  12. {
  13. InitializeComponent();
  14. }
  15. const string subscriptionKey = "Paste your API key here";
  16. const string uriBase = "Paste your Endpoint URL here";
  17. string imageFilePath = "";
  18. private void btnBrowse_Click(object sender, EventArgs e)
  19. {
  20. OpenFileDialog ofd = new OpenFileDialog();
  21. ofd.Filter = "JPEG *.jpg|*.jpg|PNG *.png|*.png";
  22. if(ofd.ShowDialog() == DialogResult.OK)
  23. {
  24. imageFilePath = ofd.FileName;
  25. pictureBox1.Image = Image.FromFile(imageFilePath);
  26. btnRecoginze.Enabled = true;
  27. }
  28. }
  29. // Method to make the restful request
  30. async Task<string> MakeAnalaysisRequest(string imageFilePath)
  31. {
  32. // Create an HttpClient object to make a post request to the Azure Services
  33. HttpClient client = new HttpClient();
  34. // set the following paramters to your request header
  35. client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
  36. // specify the requested resutls
  37. string requestParamters = "visualFeatures=Categories,Description,Color&language=en";
  38. // create the uri from your endpoint url and the requestedParamters
  39. string uri = uriBase + "?" + requestParamters;
  40. // create a respone message object to get the response of the sent request
  41. HttpResponseMessage responseMessage;
  42. // get the bytes of the selected image
  43. byte[] dataByte = GetImageAsBytesArray(imageFilePath);
  44. // create a content for the post request _ the content will be the bytes of the picture to send it to the Azure servers
  45. using (ByteArrayContent content = new ByteArrayContent(dataByte))
  46. {
  47. // Define the content type of the request
  48. content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
  49. // send the post request
  50. responseMessage = await client.PostAsync(uri, content);
  51. // read the string response from the sent request
  52. string contentString = await responseMessage.Content.ReadAsStringAsync();
  53. // return the string result
  54. return contentString;
  55. }
  56. }
  57. // Method to get the bytes of a specific image file
  58. private byte[] GetImageAsBytesArray(string imageFilePath)
  59. {
  60. // Create a file stream to access to the bytes of the selected file
  61. FileStream fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);
  62. // Create a BinaryReader object to read the bytes from a specific stream
  63. BinaryReader reader = new BinaryReader(fileStream);
  64. // Return the read bytes of a specific file
  65. return reader.ReadBytes((int)fileStream.Length);
  66. }
  67. // Tell me what you see button click event handler
  68. private async void btnRecoginze_Click(object sender, EventArgs e)
  69. {
  70. // get the result
  71. string result = await MakeAnalaysisRequest(imageFilePath);
  72. // show the result in the textbox
  73. txtResult.Text = result;
  74. }
  75. }
  76. }
Now, just run the application and choose a photo from your device. Then, click “Tell me what you see”, and it will give you results in a JSON format.

Cognitive Services
For more information about how to use Microsoft Cognitive Services, go to the following URL -

https://docs.microsoft.com/en-us/azure/cognitive-services/computer-vision/quickstarts/csharp