Xamarin.Android - Recognize Celebrities By Camera Using Computer Vision

Introduction
 
In this article, you will learn how to consume cognitive services for recognizing a celebrity in Xamarin.Android by using a mobile camera. I hope you will learn some cool stuff in Xamarin using cognitive services.
 
Xamarin.Android - Recognize Celebrities By Camera 
 
Prerequisites
  • Computer Vision API Key
  • Microsoft.Net.Http
  • Newtonsoft.Json
Computer Vision API keys
Xamarin.Android - Recognize Celebrities By Camera 
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 west-central region (https://westcentralus.api.cognitive.microsoft.com).
 
The steps given below are required to be followed in order to create a Celebrities Recognize app in Xamarin.Android, using Visual Studio.
 
Step 1 - Create an 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 RecognizeCelebritiesbyCamera.
 
(ProjectName: RecognizeCelebritiesbyCamera)
 
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 - Recognize Celebrities By Camera
 
Step 3 - User Interface
 
Open Solution Explorer-> Project Name-> Resources-> Layout-> Main.axml and add the following code. The layout will have an ImageView in order to display the preview of Celebrities image. I also added a TextView to display the contents of the Celebrities and two buttons.
 
(FileName: Main.axml)
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout 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.     
  8. <ImageView  
  9.         android:id="@+id/image"  
  10.         android:layout_width="match_parent"  
  11.         android:layout_height="match_parent"  
  12.         android:layout_above="@+id/group_button" />  
  13.     <LinearLayout  
  14.         android:layout_above="@+id/txtDescription"  
  15.         android:id="@+id/group_button"  
  16.         android:layout_width="match_parent"  
  17.         android:layout_height="wrap_content"  
  18.         android:orientation="horizontal"  
  19.         android:weightSum="2">  
  20.         <Button  
  21.             android:id="@+id/btnCapture"  
  22.             android:layout_width="0dp"  
  23.             android:layout_height="wrap_content"  
  24.             android:layout_weight="1"  
  25.             android:text="Capture" />  
  26.         <Button  
  27.             android:id="@+id/btnProcess"  
  28.             android:layout_width="0dp"  
  29.             android:layout_height="wrap_content"  
  30.             android:layout_weight="1"  
  31.             android:text="Process" />  
  32.     </LinearLayout>  
  33.     <TextView  
  34.         android:id="@+id/txtDescription"  
  35.         android:layout_width="match_parent"  
  36.         android:layout_height="wrap_content"  
  37.         android:text="Description: "  
  38.         android:textSize="20sp"  
  39.         android:layout_alignParentBottom="true" />  
  40.   
  41. </RelativeLayout>  
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 the appropriate namespace.
  1. using System.Collections.Generic;  
  2.   
  3. namespace RecoginizeCelebrities  
  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
 
Now, 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.Widget;  
  3. using Android.OS;  
  4. using Android.Support.V7.App;  
  5. using Android.Graphics;  
  6. using System.Net.Http;  
  7. using System.IO;  
  8. using Android.Content;  
  9. using Android.Runtime;  
  10. using Android.Content.PM;  
  11. using Android;  
  12. using Android.Provider;  
  13. using System.Threading.Tasks;  
  14. using Newtonsoft.Json;  
  15. using System;  
  16. using System.Net.Http.Headers;  
  17.   
  18. namespace RecoginizeCelebrities  
  19. {  
  20.     [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]  
  21.     public class MainActivity : AppCompatActivity  
  22.     {  
  23.         const string subscriptionKey = "3407ad6140b240f58847194ebf0dc26d";  
  24.         const string uriBase = "https://westcentralus.api.cognitive.microsoft.com/vision/v2.0/analyze";  
  25.         ImageView imageView;  
  26.         Bitmap mBitMap;  
  27.         int CAMERA_CODE = 1000, CAMERA_REQUEST = 1001;  
  28.         ByteArrayContent content;  
  29.         TextView txtDes;  
  30.         Button btnProcess, btnCapture;  
  31.   
  32.         public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)  
  33.         {  
  34.             base.OnRequestPermissionsResult(requestCode, permissions, grantResults);  
  35.             if (requestCode == CAMERA_CODE)  
  36.             {  
  37.                 if (grantResults[0] == Permission.Granted)  
  38.                     Toast.MakeText(this"Permission Granted", ToastLength.Short).Show();  
  39.                 else  
  40.                     Toast.MakeText(this"Permission Not Granted", ToastLength.Short).Show();  
  41.             }  
  42.         }  
  43.         protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)  
  44.         {  
  45.             base.OnActivityResult(requestCode, resultCode, data);  
  46.   
  47.             if (requestCode == 0 && resultCode == Android.App.Result.Ok &&  
  48.                 data != null)  
  49.             {  
  50.                 mBitMap = (Bitmap)data.Extras.Get("data");  
  51.                 imageView.SetImageBitmap(mBitMap);  
  52.                 byte[] bitmapData;  
  53.                 using (var stream = new MemoryStream())  
  54.                 {  
  55.                     mBitMap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);  
  56.                     bitmapData = stream.ToArray();  
  57.                 }  
  58.                 content = new ByteArrayContent(bitmapData);  
  59.             }  
  60.         }  
  61.         protected override void OnCreate(Bundle savedInstanceState)  
  62.         {  
  63.             base.OnCreate(savedInstanceState);  
  64.             // Set our view from the "main" layout resource  
  65.             SetContentView(Resource.Layout.activity_main);  
  66.             //Request runtime permission  
  67.             if (CheckSelfPermission(Manifest.Permission.Camera) == Android.Content.PM.Permission.Denied)  
  68.             {  
  69.                 RequestPermissions(new string[] { Manifest.Permission.Camera }, CAMERA_REQUEST);  
  70.             }  
  71.             txtDes = FindViewById<TextView>(Resource.Id.txtDescription);  
  72.             imageView = FindViewById<ImageView>(Resource.Id.image);  
  73.             btnProcess = FindViewById<Button>(Resource.Id.btnProcess);  
  74.             btnCapture = FindViewById<Button>(Resource.Id.btnCapture);  
  75.             btnCapture.Click += delegate  
  76.             {  
  77.                 Intent intent = new Intent(MediaStore.ActionImageCapture);  
  78.                 StartActivityForResult(intent, 0);  
  79.             };  
  80.             btnProcess.Click += async delegate  
  81.             {  
  82.                 await MakeAnalysisRequest(content);  
  83.             };  
  84.         }  
  85.         public async Task MakeAnalysisRequest(ByteArrayContent content)  
  86.         {  
  87.             try  
  88.             {  
  89.                 HttpClient client = new HttpClient();  
  90.                 // Request headers.  
  91.                 client.DefaultRequestHeaders.Add(  
  92.                     "Ocp-Apim-Subscription-Key", subscriptionKey);  
  93.                 string requestParameters =  
  94.                     "visualFeatures=Categories&details=Celebrities";  
  95.                 // Assemble the URI for the REST API method.  
  96.                 string uri = uriBase + "?" + requestParameters;  
  97.                 content.Headers.ContentType =  
  98.                     new MediaTypeHeaderValue("application/octet-stream");  
  99.                 // Asynchronously call the REST API method.  
  100.                 var response = await client.PostAsync(uri, content);  
  101.                 // Asynchronously get the JSON response.  
  102.                 string contentString = await response.Content.ReadAsStringAsync();  
  103.                 var analysesResult = JsonConvert.DeserializeObject<AnalysisModel>(contentString);  
  104.                 txtDes.Text = "Name: " + analysesResult.categories[0].detail.celebrities[0].name.ToString();  
  105.             }  
  106.             catch (Exception e)  
  107.             {  
  108.                 Toast.MakeText(this"" + e.ToString(), ToastLength.Short).Show();  
  109.             }  
  110.         }  
  111.     }  
  112. }  
Results of Analyzing the Celebrities
 
Just capture the image and hit "Analyze". You will get the same results as shown below.
 
 
Xamarin.Android - Recognize Celebrities By Camera  
 
 
 
Xamarin.Android - Recognize Celebrities By Camera 


Similar Articles