Xamarin.Forms - Computer Vision API Using Cognitive Service

In this article, you will learn how to use Computer Vision API using Cognitive Service in Xamarin.Forms

Introduction

 
 
Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files are the most easily done tasks using native file APIs on each platform. Alternatively, embedded resources are also a simpler solution to distribute the data files with an app.
 
Cognitive Services

Infuse your apps, websites, and bots with intelligent algorithms to see, hear, speak, understand and interpret your user needs through natural methods of communication. Transform your business with AI today.

Use AI to solve business problems
  1. Vision
  2. Speech
  3. Knowledge
  4. Search
  5. Language
Because the Cognitive Services APIs harness the power of machine learning, we are able to bring advanced intelligence into our product without the need to have a team of data scientists on hand.
Prerequisites
  • Visual Studio 2017(Windows or Mac)
  • Vision API Key
Setting up a Xamarin.Forms Project

Start by creating a new Xamarin.Forms project. You’ll learn more by going through the steps yourself. Choose the Cross-platform App project under Visual C# --> Cross-platform in the New Project dialog.
 
 

Now, select the Blank App and choose Portable Class Library (PCL).
 
 
 
Subsequently, go to the solution. In there, you get all the files and sources of your project (PCL). Now, select XAML page and double-click to open the MainPage.Xaml page.

You now have a basic Xamarin.Forms app. Click the Play button to try it out.
 
 
 
Get Computer Vision API Key

In this step, get computer Vision API Key. Go to the following link.

https://azure.microsoft.com/en-in/services/cognitive-services/

Click "Try Cognitive Services for free".
 
 
 
Now, you can choose Computer Vision under Vision APIs. Afterward, click "Get API Key".
 
 

Read the terms, and select your country/region. Afterward, click "Next".
 

Now, log in using your preferred account.
 
 

Now, the API Key is activated. You can use it now.
 
 
 
The trial key is available only 7 days. If you want a permanent key, refer to the following article.
Setting up the User Interface

Go to MainPage.Xaml and write the following code.
 
 

MainPage.xaml
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:XamarinComputerVision" x:Class="XamarinComputerVision.MainPage">  
  3.     <ContentPage.Content>  
  4.         <ScrollView>  
  5.             <StackLayout HorizontalOptions="CenterAndExpand" VerticalOptions="StartAndExpand">  
  6.                 <Image x:Name="imgBanner"></Image>  
  7.                 <Image x:Name="imgChoosed" HeightRequest="200"></Image>  
  8.                 <Button x:Name="btnPick" Text="Pick" Clicked="btnPick_Clicked"></Button>  
  9.                 <Button x:Name="btnTake" Text="Take" Clicked="btnTake_Clicked"></Button>  
  10.                 <Label Text="Result" x:Name="lblResult"></Label> </StackLayout>  
  11.         </ScrollView>  
  12.     </ContentPage.Content>  
  13. </ContentPage>  
 
NuGet Packages

Now, add the following NuGet Packages.
  1. Xam.Plugin.Media
  2. Microsoft.ProjectOxford.Vision
Go to Solution Explorer and select your solution. Right-click and select "Manage NuGet Packages for Solution".
 
Xam.Plugin.Media

 
Microsoft.ProjectOxford.Vision

 

Permissions - for Android

In this step give the following required permissions to your app:
  1. CAMERA
  2. READ_EXTERNAL_STORAGE
  3. WRITE_EXTERNAL_STORAGE
 
AndroidManifest.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.XamarinComputerVision" android:installLocation="auto">  
  3.     <uses-sdk android:minSdkVersion="15" />  
  4.     <uses-permission android:name="android.permission.CAMERA" />  
  5.     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />  
  6.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
  7.     <application android:label="XamarinComputerVision.Android">  
  8.         <provider android:name="android.support.v4.content.FileProvider" android:authorities="com.companyname.XamarinComputerVision.fileprovider" android:exported="false" android:grantUriPermissions="true">  
  9.             <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>  
  10.         </provider>  
  11.     </application>  
  12. </manifest>  
In this step, create a xml file under Resource-->xml folder for get file paths.

Go to Solution—>Android —>Right click—>New—>Xml—> file_paths.xml

 
 
Now, write the following code to get file paths.
 
  
file_paths.xml
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <paths xmlns:android="http://schemas.android.com/apk/res/android">  
  3.    <external-files-path name="my_images" path="Pictures" />  
  4.    <external-files-path name="my_movies" path="Movies" />  
  5. </paths>  
Analyze Image
 
MainPage.Xaml.cs
 
Now, write the following code for analyzing image using Cognitive Service Vision API. 
 
  1. public async Task<AnalysisResult> GetImageDescription(Stream imageStream)  
  2. {  
  3.    VisionServiceClient visionClient = new VisionServiceClient("a338648c0df347c6b3b9e46ea2022fcd""https://westcentralus.api.cognitive.microsoft.com/vision/v2.0");  
  4.    VisualFeature[] features = { VisualFeature.Tags, VisualFeature.Categories, VisualFeature.Description };  
  5.    return await visionClient.AnalyzeImageAsync(imageStream, features.ToList(), null);  
  6. }   
Pick Image

Now, write the following code to pick an image from your device.

MainPage.xaml.cs
  1. private async void btnPick_Clicked(object sender, EventArgs e) {  
  2.     await CrossMedia.Current.Initialize();  
  3.     try {  
  4.         var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions {  
  5.             PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium  
  6.         });  
  7.         if (file == nullreturn;  
  8.         imgChoosed.Source = ImageSource.FromStream(() => {  
  9.             var stream = file.GetStream();  
  10.             return stream;  
  11.         });  
  12.         var result = await GetImageDescription(file.GetStream());  
  13.         lblResult.Text = null;  
  14.         file.Dispose();  
  15.         foreach(string tag in result.Description.Tags) {  
  16.             lblResult.Text = lblResult.Text + "\n" + tag;  
  17.         }  
  18.     } catch (Exception ex) {  
  19.         string test = ex.Message;  
  20.     }  
  21. }  
Click the Play button to try it out.
 
 
 
Take Image

Now, write the following code to take an image using the camera.
 
 
 
MainPage.xaml.cs
  1. private async void btnTake_Clicked(object sender, EventArgs e) {  
  2.     await CrossMedia.Current.Initialize();  
  3.     try {  
  4.         if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported) {  
  5.             await DisplayAlert("No Camera"":( No camera available.""OK");  
  6.             return;  
  7.         }  
  8.         var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions {  
  9.             Directory = "Sample",  
  10.                 Name = "xamarin.jpg"  
  11.         });  
  12.         if (file == nullreturn;  
  13.         imgChoosed.Source = ImageSource.FromStream(() => {  
  14.             var stream = file.GetStream();  
  15.             return stream;  
  16.         });  
  17.         var result = await GetImageDescription(file.GetStream());  
  18.         file.Dispose();  
  19.         lblResult.Text = null;  
  20.         //lblResult.Text = result.Description.Captions.First().Text;    
  21.         foreach(string tag in result.Description.Tags) {  
  22.             lblResult.Text = lblResult.Text + "\n" + tag;  
  23.         }  
  24.     } catch (Exception ex) {  
  25.         string test = ex.Message;  
  26.     }  
  27. }  
Click the Play button to try it out.
 
 
 
 

Full Code - MainPage.Xaml.cs

MainPage.Xaml.cs
  1. using Microsoft.ProjectOxford.Vision;  
  2. using Microsoft.ProjectOxford.Vision.Contract;  
  3. using Plugin.Media;  
  4. using System;  
  5. using System.Collections.Generic;  
  6. using System.IO;  
  7. using System.Linq;  
  8. using System.Text;  
  9. using System.Threading.Tasks;  
  10. using Xamarin.Forms;  
  11. namespace XamarinComputerVision {  
  12.     public partial class MainPage: ContentPage {  
  13.         public MainPage() {  
  14.             InitializeComponent();  
  15.             imgBanner.Source = ImageSource.FromResource("XamarinComputerVision.images.banner.png");  
  16.             imgChoosed.Source = ImageSource.FromResource("XamarinComputerVision.images.thumbnail.jpg");  
  17.         }  
  18.         private async void btnPick_Clicked(object sender, EventArgs e) {  
  19.             await CrossMedia.Current.Initialize();  
  20.             try {  
  21.                 var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions {  
  22.                     PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium  
  23.                 });  
  24.                 if (file == nullreturn;  
  25.                 imgChoosed.Source = ImageSource.FromStream(() => {  
  26.                     var stream = file.GetStream();  
  27.                     return stream;  
  28.                 });  
  29.                 var result = await GetImageDescription(file.GetStream());  
  30.                 lblResult.Text = null;  
  31.                 file.Dispose();  
  32.                 foreach(string tag in result.Description.Tags) {  
  33.                     lblResult.Text = lblResult.Text + "\n" + tag;  
  34.                 }  
  35.             } catch (Exception ex) {  
  36.                 string test = ex.Message;  
  37.             }  
  38.         }  
  39.         public async Task < AnalysisResult > GetImageDescription(Stream imageStream) {  
  40.             VisionServiceClient visionClient = new VisionServiceClient("a338648c0df347c6b3b9e46ea2022fcd""https://westcentralus.api.cognitive.microsoft.com/vision/v2.0");  
  41.             VisualFeature[] features = {  
  42.                 VisualFeature.Tags,  
  43.                 VisualFeature.Categories,  
  44.                 VisualFeature.Description  
  45.             };  
  46.             return await visionClient.AnalyzeImageAsync(imageStream, features.ToList(), null);  
  47.         }  
  48.         private async void btnTake_Clicked(object sender, EventArgs e) {  
  49.             await CrossMedia.Current.Initialize();  
  50.             try {  
  51.                 if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported) {  
  52.                     await DisplayAlert("No Camera"":( No camera available.""OK");  
  53.                     return;  
  54.                 }  
  55.                 var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions {  
  56.                     Directory = "Sample",  
  57.                         Name = "xamarin.jpg"  
  58.                 });  
  59.                 if (file == nullreturn;  
  60.                 imgChoosed.Source = ImageSource.FromStream(() => {  
  61.                     var stream = file.GetStream();  
  62.                     return stream;  
  63.                 });  
  64.                 var result = await GetImageDescription(file.GetStream());  
  65.                 file.Dispose();  
  66.                 lblResult.Text = null;  
  67.                 //lblResult.Text = result.Description.Captions.First().Text;    
  68.                 foreach(string tag in result.Description.Tags) {  
  69.                     lblResult.Text = lblResult.Text + "\n" + tag;  
  70.                 }  
  71.             } catch (Exception ex) {  
  72.                 string test = ex.Message;  
  73.             }  
  74.         }  
  75.     }  
  76. }  
Click the Play button to try it out.

  
I hope you have understood how to use Computer Vision API using Cognitive Service in Xamarin.Forms.

Thanks for reading. Please share comments and feedback.