Monday, April 20, 2020

Xamarin.Android - Analyze Image Using Computer Vision


 

Introduction

In this article, I will show you how to consume computer vision API in xamarin.android for analyzing images. I hope you will learn the latest things in Xamarin using cognitive services.

Prerequisites
  • Computer Vision API Key
  • Microsoft.Net.Http
  • Newtonsoft.Json
Computer Vision API keys
 
Computer vision services require special subscription keys. Every call to the Computer Vision API requires a subscription key. This key needs to be either passed through a query string parameter or specified in the request header.
 
To sign up for subscription keys, see Subscriptions. It's free to sign up. Pricing for these services is subject to change.
 
If you sign up using the Computer Vision free trial, your subscription keys are valid for the westcentral region (https://westcentralus.api.cognitive.microsoft.com).
 
The steps given below are required to be followed in order to create a Image Analyze app in Xamarin.Android, using Visual Studio.
 
Step 1 - Create Android Project
 
Create your Android solution in Visual Studio or Xamarin Studio. Select Android and from the list, choose Android Blank App. Give it a name, like ImageAnalyze.
 
(ProjectName: ImageAnalyze)
 
Step 2 - Add References of Nuget Packages
 
First of all, in References, add the reference of Microsoft.Net.Http and Newtonsoft.Json using NuGet Package Manager, as shown below.
 
Xamarin.Android - Analyze Image Using Cognitive Services
 
Step 3 - User Interface
 
Open Solution Explorer-> Project Name-> Resources-> Layout-> Main.axml and add the following code. The layout will have a ImageView in order to display the preview of sample image. I also added a TextView to display the contents of the Image.
 
(FileName: activity_main.axml)
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  4.     xmlns:tools="http://schemas.android.com/tools"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     android:padding="10dp"  
  8.     android:orientation="vertical">  
  9.     <LinearLayout  
  10.         android:orientation="vertical"  
  11.         android:layout_width="match_parent"  
  12.         android:layout_height="wrap_content"  
  13.         android:padding="8dp">  
  14.         <ImageView  
  15.             android:id="@+id/imgView"  
  16.             android:layout_width="350dp"  
  17.             android:layout_height="350dp" />  
  18.         <ProgressBar  
  19.             android:layout_width="match_parent"  
  20.             android:layout_height="wrap_content"  
  21.             android:id="@+id/progressBar"  
  22.             android:visibility="invisible" />  
  23.           
  24.         <Button  
  25.             android:id="@+id/btnAnalyze"  
  26.             android:text="Analyze"  
  27.             android:layout_width="match_parent"  
  28.             android:layout_height="wrap_content" />  
  29.     <TextView  
  30.             android:id="@+id/txtDescription"  
  31.             android:text="Description:"  
  32.             android:layout_width="match_parent"  
  33.             android:layout_height="match_parent"  
  34.             android:textSize="18sp"    
  35.             android:layout_alignParentBottom="true"/>  
  36.     </LinearLayout>  
  37. </LinearLayout>  
Step 4 - Analysis Model Class
 
Add a new class in your project with name AnalysisModel.cs. Add the following properties to get the result set from json response with appropriate namespace.
  1. using System.Collections.Generic;  
  2.   
  3. namespace RecognizeCelebrities  
  4. {  
  5.     public class AnalysisModel  
  6.     {  
  7.         public IList<Category> categories { getset; }  
  8.         public object adult { getset; }  
  9.         public IList<Tag> tags { getset; }  
  10.         public Description description { getset; }  
  11.         public string requestId { getset; }  
  12.         public Metadata metadata { getset; }  
  13.         public IList<Face> faces { getset; }  
  14.         public Color color { getset; }  
  15.         public ImageType imageType { getset; }  
  16.     }  
  17.     public class FaceRectangle  
  18.     {  
  19.         public int left { getset; }  
  20.         public int top { getset; }  
  21.         public int width { getset; }  
  22.         public int height { getset; }  
  23.     }  
  24.   
  25.     public class Celebrity  
  26.     {  
  27.         public string name { getset; }  
  28.         public FaceRectangle faceRectangle { getset; }  
  29.         public double confidence { getset; }  
  30.     }  
  31.   
  32.     public class Detail  
  33.     {  
  34.         public IList<Celebrity> celebrities { getset; }  
  35.         public object landmarks { getset; }  
  36.     }  
  37.   
  38.     public class Category  
  39.     {  
  40.         public string name { getset; }  
  41.         public double score { getset; }  
  42.         public Detail detail { getset; }  
  43.     }  
  44.   
  45.     public class Tag  
  46.     {  
  47.         public string name { getset; }  
  48.         public double confidence { getset; }  
  49.     }  
  50.   
  51.     public class Caption  
  52.     {  
  53.         public string text { getset; }  
  54.         public double confidence { getset; }  
  55.     }  
  56.   
  57.     public class Description  
  58.     {  
  59.         public IList<string> tags { getset; }  
  60.         public IList<Caption> captions { getset; }  
  61.     }  
  62.   
  63.     public class Metadata  
  64.     {  
  65.         public int width { getset; }  
  66.         public int height { getset; }  
  67.         public string format { getset; }  
  68.     }  
  69.   
  70.     public class Face  
  71.     {  
  72.         public int age { getset; }  
  73.         public string gender { getset; }  
  74.         public FaceRectangle faceRectangle { getset; }  
  75.     }  
  76.   
  77.     public class Color  
  78.     {  
  79.         public string dominantColorForeground { getset; }  
  80.         public string dominantColorBackground { getset; }  
  81.         public IList<string> dominantColors { getset; }  
  82.         public string accentColor { getset; }  
  83.         public bool isBWImg { getset; }  
  84.     }  
  85.   
  86.     public class ImageType  
  87.     {  
  88.         public int clipArtType { getset; }  
  89.         public int lineDrawingType { getset; }  
  90.     }  
  91. }   
Step 5 - Backend Code
 
Let's go to Solution Explorer-> Project Name-> MainActivity and add the following code with appropriate namespaces.
 
Note: Please replace your subscription key and your selected region address in the Main activity class. 
 
(FileName: MainActivity)
  1. using Android.App;  
  2. using Android.Graphics;  
  3. using Android.OS;  
  4. using Android.Support.V7.App;  
  5. using Android.Views;  
  6. using Android.Widget;  
  7. using Newtonsoft.Json;  
  8. using System;  
  9. using System.IO;  
  10. using System.Net.Http;  
  11. using System.Net.Http.Headers;  
  12. using System.Threading.Tasks;  
  13.   
  14. namespace AnalyzeImage  
  15. {  
  16.     [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]  
  17.     public class MainActivity : AppCompatActivity  
  18.     {  
  19.         const string subscriptionKey = "3407ad61**********94ebf0dc26d";  
  20.         const string uriBase = 
  21.         "https://westcentralus.api.cognitive.microsoft.com/vision/v2.0/analyze";  
  22.         Bitmap mBitmap;  
  23.         private ImageView imageView;  
  24.         private ProgressBar progressBar;  
  25.         ByteArrayContent content;  
  26.         private TextView textView;  
  27.         Button btnAnalyze;  
  28.         protected override void OnCreate(Bundle savedInstanceState)  
  29.         {  
  30.             base.OnCreate(savedInstanceState);
  31.             // Set our view from the "main" layout resource  
  32.             SetContentView(Resource.Layout.activity_main);
  33.             mBitmap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.myPic);  
  34.             imageView = FindViewById<ImageView>(Resource.Id.imgView);  
  35.             imageView.SetImageBitmap(mBitmap);  
  36.             textView = FindViewById<TextView>(Resource.Id.txtDescription);  
  37.             progressBar = FindViewById<ProgressBar>(Resource.Id.progressBar);  
  38.             btnAnalyze = FindViewById<Button>(Resource.Id.btnAnalyze);  
  39.             byte[] bitmapData;  
  40.             using (var stream = new MemoryStream())  
  41.             {  
  42.                 mBitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);  
  43.                 bitmapData = stream.ToArray();  
  44.             }  
  45.             content = new ByteArrayContent(bitmapData);
  46.             btnAnalyze.Click += async delegate  
  47.             {  
  48.                 busy();  
  49.                await MakeAnalysisRequest(content);  
  50.             };             
  51.     }  
  52.         public async Task MakeAnalysisRequest(ByteArrayContent content)  
  53.         {  
  54.             try  
  55.             {  
  56.                 HttpClient client = new HttpClient();
  57.                 // Request headers.  
  58.                 client.DefaultRequestHeaders.Add(  
  59.                     "Ocp-Apim-Subscription-Key", subscriptionKey);
  60.                 string requestParameters =  
  61.                     "visualFeatures=Description&details=Landmarks&language=en";
  62.                 // Assemble the URI for the REST API method.  
  63.                 string uri = uriBase + "?" + requestParameters;  
  64.                 content.Headers.ContentType =  
  65.                     new MediaTypeHeaderValue("application/octet-stream");
  66.                 // Asynchronously call the REST API method.  
  67.                 var response = await client.PostAsync(uri, content);
  68.                 // Asynchronously get the JSON response.
  69.                 string contentString = await response.Content.ReadAsStringAsync();
  70.                 var analysesResult = JsonConvert.DeserializeObject<AnalysisModel>(contentString);  
  71.                 NotBusy();  
  72.                 textView.Text = analysesResult.description.captions[0].text.ToString();  
  73.             }  
  74.             catch (Exception e)  
  75.             {  
  76.                 Toast.MakeText(this"" + e.ToString(), ToastLength.Short).Show();  
  77.             }  
  78.         }  
  79.         void busy()  
  80.         {  
  81.             progressBar.Visibility = ViewStates.Visible;  
  82.             btnAnalyze.Enabled = false;  
  83.         }  
  84.         void NotBusy()  
  85.         {  
  86.             progressBar.Visibility = ViewStates.Invisible;  
  87.             btnAnalyze.Enabled = true;  
  88.         }  
  89.     }  
  90. }   
Results of Analyzing the Images
 
Xamarin.Android - Analyze Image Using Cognitive Services 
 
Xamarin.Android - Analyze Image Using Cognitive Services 
 
Xamarin.Android - Analyze Image Using Cognitive Services

Ahsan Siddique

Author & Editor

Experienced Microsoft Certified Azure Developer and Trainer with a demonstrated history of working in the computer software industry. Skilled in .NET, .NET Core, C#, Xamarin, Azure, Kubernetes, Docker Containers, Microservices, CI/CD, and Universal Windows Platform with Strong engineering professional.

0 Comments:

Post a Comment