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.
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.
This is all you need to start creating your intelligent app.
Open Visual Studio and create a new Windows Forms Project.
Add two buttons, a picturebox and a textbox as following.
In the code behind file, add the following namespaces:
- using System.Net.Http;
- 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.
- string imageFilePath = "";
-
- private void btnBrowse_Click(object sender, EventArgs e)
- {
-
- OpenFileDialog ofd = new OpenFileDialog();
-
- ofd.Filter = "JPEG *.jpg|*.jpg|PNG *.png|*.png";
-
- if(ofd.ShowDialog() == DialogResult.OK)
- {
-
- imageFilePath = ofd.FileName;
-
- pictureBox1.Image = Image.FromFile(imageFilePath);
- }
- }
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).
- const string subscriptionKey = "Paste your API key here";
- const string uriBase = "Paste your Endpoint URL here";
-
-
- async Task<string> MakeAnalaysisRequest(string imageFilePath)
- {
-
- HttpClient client = new HttpClient();
-
-
- client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
-
-
- string requestParamters = "visualFeatures=Categories,Description,Color&language=en";
-
-
- string uri = uriBase + "?" + requestParamters;
-
-
- HttpResponseMessage responseMessage;
-
-
- byte[] dataByte = GetImageAsBytesArray(imageFilePath);
-
-
- using (ByteArrayContent content = new ByteArrayContent(dataByte))
- {
-
- content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
-
-
- responseMessage = await client.PostAsync(uri, content);
-
-
- string contentString = await responseMessage.Content.ReadAsStringAsync();
-
-
- return contentString;
- }
-
- }
-
-
- private byte[] GetImageAsBytesArray(string imageFilePath)
- {
-
- FileStream fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);
-
- BinaryReader reader = new BinaryReader(fileStream);
-
- return reader.ReadBytes((int)fileStream.Length);
- }
Double click on the “Tell me what you see” button to create a click event handler and write the following code.
-
- private async void btnRecoginze_Click(object sender, EventArgs e)
- {
-
- string result = await MakeAnalaysisRequest(imageFilePath);
-
-
- txtResult.Text = result;
-
- }
The full code should be like this.
- using System;
- using System.Drawing;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using System.Net.Http;
- using System.IO;
-
- namespace VisionApi
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- const string subscriptionKey = "Paste your API key here";
- const string uriBase = "Paste your Endpoint URL here";
- string imageFilePath = "";
-
- private void btnBrowse_Click(object sender, EventArgs e)
- {
- OpenFileDialog ofd = new OpenFileDialog();
- ofd.Filter = "JPEG *.jpg|*.jpg|PNG *.png|*.png";
-
- if(ofd.ShowDialog() == DialogResult.OK)
- {
- imageFilePath = ofd.FileName;
- pictureBox1.Image = Image.FromFile(imageFilePath);
- btnRecoginze.Enabled = true;
- }
- }
-
-
- async Task<string> MakeAnalaysisRequest(string imageFilePath)
- {
-
- HttpClient client = new HttpClient();
-
-
- client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
-
-
- string requestParamters = "visualFeatures=Categories,Description,Color&language=en";
-
-
- string uri = uriBase + "?" + requestParamters;
-
-
- HttpResponseMessage responseMessage;
-
-
- byte[] dataByte = GetImageAsBytesArray(imageFilePath);
-
-
- using (ByteArrayContent content = new ByteArrayContent(dataByte))
- {
-
- content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
-
-
- responseMessage = await client.PostAsync(uri, content);
-
-
- string contentString = await responseMessage.Content.ReadAsStringAsync();
-
-
- return contentString;
- }
-
- }
-
-
- private byte[] GetImageAsBytesArray(string imageFilePath)
- {
-
- FileStream fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);
-
- BinaryReader reader = new BinaryReader(fileStream);
-
- return reader.ReadBytes((int)fileStream.Length);
- }
-
-
- private async void btnRecoginze_Click(object sender, EventArgs e)
- {
-
- string result = await MakeAnalaysisRequest(imageFilePath);
-
-
- txtResult.Text = result;
-
- }
- }
- }
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.
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