Introduction
In the last couple of Cognitive Services posts, we focused on Microsoft Computer Vision API and its applications. In this article, we will focus on the Face API. We will see what we can do with the Face API with working examples of it.
Prerequisites
- Computer Vision Face API Key
- Microsoft.Net.Http
- Newtonsoft.Json
(ProjectName: FaceDetection)
Step 2 - Add References of NuGet Packages
First of all, in References, add the references to Microsoft.Net.Http and Newtonsoft.Json using NuGet Package Manager, as shown below.
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:padding="10dp"
- android:orientation="vertical">
- <LinearLayout
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:padding="8dp">
- <ImageView
- android:id="@+id/imgView"
- android:layout_width="350dp"
- android:layout_height="350dp" />
- <ProgressBar
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/progressBar"
- android:visibility="invisible" />
- <Button
- android:id="@+id/btnAnalyze"
- android:text="Analyze"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
- <TextView
- android:id="@+id/txtGender"
- android:text="Gender:"
- android:layout_width="match_parent"
- android:layout_height="match_parent"/>
- <TextView
- android:id="@+id/txtAge"
- android:text="Age:"
- android:layout_width="match_parent"
- android:layout_height="match_parent"/>
- <TextView
- android:id="@+id/txtFaces"
- android:text="Glasses:"
- android:layout_width="match_parent"
- android:layout_height="match_parent"/>
- </LinearLayout>
- </LinearLayout>
- using System.Collections.Generic;
- namespace FaceDetection
- {
- public class AnalysisModel
- {
- public string faceId { get; set; }
- public FaceRectangle faceRectangle { get; set; }
- public FaceAttributes faceAttributes { get; set; }
- }
- public class FaceRectangle
- {
- public int top { get; set; }
- public int left { get; set; }
- public int width { get; set; }
- public int height { get; set; }
- }
- public class Emotion
- {
- public double anger { get; set; }
- public double contempt { get; set; }
- public double disgust { get; set; }
- public double fear { get; set; }
- public double happiness { get; set; }
- public double neutral { get; set; }
- public double sadness { get; set; }
- public double surprise { get; set; }
- }
- public class FaceAttributes
- {
- public double smile { get; set; }
- public string gender { get; set; }
- public double age { get; set; }
- public string glasses { get; set; }
- public Emotion emotion { get; set; }
- }
- }
- using Android.App;
- using Android.Graphics;
- using Android.OS;
- using Android.Support.V7.App;
- using Android.Views;
- using Android.Widget;
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Threading.Tasks;
- namespace FaceDetection
- {
- [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
- public class MainActivity : AppCompatActivity
- {
- const string subscriptionKey = "202631d0172a48d08f21b52bc22ee860";
- const string uriBase = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect";
- Bitmap mBitmap;
- private ImageView imageView;
- private ProgressBar progressBar;
- ByteArrayContent content;
- private TextView txtAge , txtGender,txtFaces;
- Button btnAnalyze;
- protected override void OnCreate(Bundle savedInstanceState)
- {
- base.OnCreate(savedInstanceState);
- // Set our view from the "main" layout resource
- SetContentView(Resource.Layout.activity_main);
- mBitmap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.newAhsan);
- imageView = FindViewById<ImageView>(Resource.Id.imgView);
- imageView.SetImageBitmap(mBitmap);
- txtGender = FindViewById<TextView>(Resource.Id.txtGender);
- txtAge = FindViewById<TextView>(Resource.Id.txtAge);
- txtFaces = FindViewById<TextView>(Resource.Id.txtFaces);
- progressBar = FindViewById<ProgressBar>(Resource.Id.progressBar);
- btnAnalyze = FindViewById<Button>(Resource.Id.btnAnalyze);
- byte[] bitmapData;
- using (var stream = new MemoryStream())
- {
- mBitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
- bitmapData = stream.ToArray();
- }
- content = new ByteArrayContent(bitmapData);
- btnAnalyze.Click += async delegate
- {
- busy();
- await MakeAnalysisRequest(content);
- };
- }
- public async Task MakeAnalysisRequest(ByteArrayContent content)
- {
- try
- {
- HttpClient client = new HttpClient();
- // Request headers.
- client.DefaultRequestHeaders.Add(
- "Ocp-Apim-Subscription-Key", subscriptionKey);
- string requestParameters = "returnFaceId=true&returnfaceRectangle=true" +
- "&returnFaceAttributes=age,gender,smile,glasses";
- // Assemble the URI for the REST API method.
- string uri = uriBase + "?" + requestParameters;
- content.Headers.ContentType =
- new MediaTypeHeaderValue("application/octet-stream");
- // Asynchronously call the REST API method.
- var response = await client.PostAsync(uri, content);
- // Asynchronously get the JSON response.
- string contentString = await response.Content.ReadAsStringAsync();
- var faces = JsonConvert.DeserializeObject<List<AnalysisModel>>(contentString);
- Toast.MakeText(this, faces.Count.ToString()+ " Face Detected" , ToastLength.Short).Show();
- NotBusy();
- var newbitmap = DrawRectanglesOnBitmap(mBitmap, faces);
- imageView.SetImageBitmap(newbitmap);
- txtGender.Text = "Gender: " + faces[0].faceAttributes.gender.ToString();
- txtAge.Text ="Age: " + faces[0].faceAttributes.age.ToString();
- txtFaces.Text = "Glasses: " + faces[0].faceAttributes.glasses.ToString();
- }
- catch (Exception e)
- {
- Toast.MakeText(this, "" + e.ToString(), ToastLength.Short).Show();
- }
- }
- //DrawRectangle
- private Bitmap DrawRectanglesOnBitmap(Bitmap mybitmap, List<AnalysisModel> faces)
- {
- Bitmap bitmap = mybitmap.Copy(Bitmap.Config.Argb8888, true);
- Canvas canvas = new Canvas(bitmap);
- Paint paint = new Paint();
- paint.AntiAlias = true;
- paint.SetStyle(Paint.Style.Stroke);
- paint.Color = Color.DodgerBlue;
- paint.StrokeWidth = 12;
- foreach(var face in faces)
- {
- var faceRectangle = face.faceRectangle;
- canvas.DrawRect(faceRectangle.left,
- faceRectangle.top,
- faceRectangle.left + faceRectangle.width,
- faceRectangle.top + faceRectangle.height, paint);
- }
- return bitmap;
- }
- void busy()
- {
- progressBar.Visibility = ViewStates.Visible;
- btnAnalyze.Enabled = false;
- }
- void NotBusy()
- {
- progressBar.Visibility = ViewStates.Invisible;
- btnAnalyze.Enabled = true;
- }
- }
- }
Summary
In this post, we explored the Face API that belongs to the Microsoft Cognitive Services stable of products.
Catch up on my all Cognitive Services articles here.
0 Comments:
Post a Comment