Introduction
In this article, you will learn how to consume Cognitive Services for recognizing a celebrity, using Xamarin.Android. I hope you will learn some amazing things in Xamarin using cognitive services.
Prerequisites
  • You must have a subscription key for Computer Vision
  • 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 that is needed 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).
Xamarin.Android - Recognize Celebrities Using Cognitive Services
The steps given below are required to be followed in order to create a Celebrity Recognition 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 RecognizeCelebrities.
(ProjectName: RecognizeCelebrities)
Step 2 - Add references of NuGet Packages
First of all, in References, add the reference to Microsoft.Net.Http and Newtonsoft.Json using NuGet Package Manager, as shown below.
Xamarin.Android - Recognize Celebrities Using Cognitive Services
Step 3 - Create 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 a celebrity's image. I also added a TextView to display the name of the celebrity.
(FileName: 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. <TextView
  24. android:id="@+id/txtDescription"
  25. android:text="Description:"
  26. android:layout_width="match_parent"
  27. android:layout_height="match_parent"
  28. android:textSize="25sp"
  29. android:textColor="#000000" />
  30. <Button
  31. android:id="@+id/btnAnalyze"
  32. android:text="Analyze"
  33. android:layout_width="match_parent"
  34. android:layout_height="wrap_content" />
  35. </LinearLayout>
  36. </LinearLayout>
Step 4 - Create Analysis Model Class
Add a new class to your project with the name AnalysisModel.cs. Add the following properties to get the result set from JSON response with an appropriate namespace.
  1. using System.Collections.Generic;
  2. namespace RecognizeCelebrities
  3. {
  4. public class AnalysisModel
  5. {
  6. public IList<Category> categories { get; set; }
  7. public object adult { get; set; }
  8. public IList<Tag> tags { get; set; }
  9. public Description description { get; set; }
  10. public string requestId { get; set; }
  11. public Metadata metadata { get; set; }
  12. public IList<Face> faces { get; set; }
  13. public Color color { get; set; }
  14. public ImageType imageType { get; set; }
  15. }
  16. public class FaceRectangle
  17. {
  18. public int left { get; set; }
  19. public int top { get; set; }
  20. public int width { get; set; }
  21. public int height { get; set; }
  22. }
  23. public class Celebrity
  24. {
  25. public string name { get; set; }
  26. public FaceRectangle faceRectangle { get; set; }
  27. public double confidence { get; set; }
  28. }
  29. public class Detail
  30. {
  31. public IList<Celebrity> celebrities { get; set; }
  32. public object landmarks { get; set; }
  33. }
  34. public class Category
  35. {
  36. public string name { get; set; }
  37. public double score { get; set; }
  38. public Detail detail { get; set; }
  39. }
  40. public class Tag
  41. {
  42. public string name { get; set; }
  43. public double confidence { get; set; }
  44. }
  45. public class Caption
  46. {
  47. public string text { get; set; }
  48. public double confidence { get; set; }
  49. }
  50. public class Description
  51. {
  52. public IList<string> tags { get; set; }
  53. public IList<Caption> captions { get; set; }
  54. }
  55. public class Metadata
  56. {
  57. public int width { get; set; }
  58. public int height { get; set; }
  59. public string format { get; set; }
  60. }
  61. public class Face
  62. {
  63. public int age { get; set; }
  64. public string gender { get; set; }
  65. public FaceRectangle faceRectangle { get; set; }
  66. }
  67. public class Color
  68. {
  69. public string dominantColorForeground { get; set; }
  70. public string dominantColorBackground { get; set; }
  71. public IList<string> dominantColors { get; set; }
  72. public string accentColor { get; set; }
  73. public bool isBWImg { get; set; }
  74. }
  75. public class ImageType
  76. {
  77. public int clipArtType { get; set; }
  78. public int lineDrawingType { get; set; }
  79. }
  80. }
Step 5 - Backend Logic
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 MainActivity 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. namespace RecognizeCelebrities
  14. {
  15. [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
  16. public class MainActivity : AppCompatActivity
  17. {
  18. const string subscriptionKey = "3407ad614**********4ebf0dc26d";
  19. const string uriBase = "https://westcentralus.api.cognitive.microsoft.com/vision/v2.0/analyze";
  20. Bitmap mBitmap;
  21. private ImageView imageView;
  22. private ProgressBar progressBar;
  23. ByteArrayContent content;
  24. private TextView textView;
  25. Button btnAnalyze;
  26. protected override void OnCreate(Bundle savedInstanceState)
  27. {
  28. base.OnCreate(savedInstanceState);
  29. // Set our view from the "main" layout resource
  30. SetContentView(Resource.Layout.activity_main);
  31. mBitmap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.dblbig);
  32. imageView = FindViewById<ImageView>(Resource.Id.imgView);
  33. imageView.SetImageBitmap(mBitmap);
  34. textView = FindViewById<TextView>(Resource.Id.txtDescription);
  35. progressBar = FindViewById<ProgressBar>(Resource.Id.progressBar);
  36. btnAnalyze = FindViewById<Button>(Resource.Id.btnAnalyze);
  37. byte[] bitmapData;
  38. using (var stream = new MemoryStream())
  39. {
  40. mBitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
  41. bitmapData = stream.ToArray();
  42. }
  43. content = new ByteArrayContent(bitmapData);
  44. btnAnalyze.Click += async delegate
  45. {
  46. busy();
  47. await MakeAnalysisRequest(content);
  48. };
  49. }
  50. public async Task MakeAnalysisRequest(ByteArrayContent content)
  51. {
  52. try
  53. {
  54. HttpClient client = new HttpClient();
  55. // Request headers.
  56. client.DefaultRequestHeaders.Add(
  57. "Ocp-Apim-Subscription-Key", subscriptionKey);
  58. string requestParameters =
  59. "visualFeatures=Categories&details=Celebrities";
  60. // Assemble the URI for the REST API method.
  61. string uri = uriBase + "?" + requestParameters;
  62. content.Headers.ContentType =
  63. new MediaTypeHeaderValue("application/octet-stream");
  64. // Asynchronously call the REST API method.
  65. var response = await client.PostAsync(uri, content);
  66. // Asynchronously get the JSON response.
  67. string contentString = await response.Content.ReadAsStringAsync();
  68. var analysesResult = JsonConvert.DeserializeObject<AnalysisModel>(contentString);
  69. NotBusy();
  70. textView.Text = "Name: " + analysesResult.categories[0].detail.celebrities[0].name.ToString();
  71. }
  72. catch (Exception e)
  73. {
  74. Toast.MakeText(this, "" + e.ToString(), ToastLength.Short).Show();
  75. }
  76. }
  77. void busy()
  78. {
  79. progressBar.Visibility = ViewStates.Visible;
  80. btnAnalyze.Enabled = false;
  81. }
  82. void NotBusy()
  83. {
  84. progressBar.Visibility = ViewStates.Invisible;
  85. btnAnalyze.Enabled = true;
  86. }
  87. }
  88. }
Results of recognizing the celebrities
Xamarin.Android - Recognize Celebrities Using Cognitive Services
Xamarin.Android - Recognize Celebrities Using Cognitive Services
Xamarin.Android - Recognize Celebrities Using Cognitive Services
Xamarin.Android - Recognize Celebrities Using Cognitive Services