FaceRecognition Xamarin Android
Hola que tal amigos, con el respecto al calendario Segundo Calendario de Adviento de Xamarin en Español #AdvientoXamarin, en este articulo hablaremos sobre un tema muy importante que nos puede ayudar en cuanto a nuestros proyectos. Reconocimiento de Rostro en aplicacion Xamarin Android con Xamarin.GooglePlayServices.Vision
Link del componente https://www.nuget.org/packages/Xamarin.GooglePlayServices.Vision/
Mobile Vision ¿QUE ES?
Detect Faces
The Face API finds human faces in photos, videos, or live streams. It also finds and tracks positions of facial landmarks such as the eyes, nose, and mouth.
The API also provides information about the state of facial features — are the subject’s eyes open? Are they smiling? With these technologies, you can edit photos and video, enhance video feeds with effects and decorations, create hands-free controls for games and apps, or react when a person winks or smiles.
Detectar caras
- - Creamos un proyecto de tipo Android y Black Android App
2.- Le Ponemos un nombre para este ejemplo pondremos FaceRecognition. y creamos el proyecto
3.- Damos click derecho y click Manage Nuget Packages
4.- Buscamos el Paquete Xamarin.GooglePlayServices.Vision y agregamos el paquete
5.- En nuestro Manifest agregamos los siguientes permisos
<manifest
xmlns:android=”http://schemas.android.com/apk/res/android"
android:versionCode=”1"
android:versionName=”1.0"
package=”com.ecoscadiz.facerecognition”>
<uses-sdk android:minSdkVersion=”21" android:targetSdkVersion=”28" />
<uses-feature android:name=”android.hardware.camera” android:required=”true” />
<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” />
<uses-permission android:name=”android.permission.READ_EXTERNAL_STORAGE” />
<uses-permission android:name=”android.permission.CAMERA” />
<application
android:allowBackup=”true”
android:icon=”@mipmap/ic_launcher”
android:label=”@string/app_name”
android:roundIcon=”@mipmap/ic_launcher_round”
android:supportsRtl=”true”
android:theme=”@style/AppTheme”>
<provider
android:name=”android.support.v4.content.FileProvider”
android:authorities=”com.ecoscadiz.facerecognition.fileprovider”
android:exported=”false”
android:grantUriPermissions=”true”>
<meta-data
android:name=”android.support.FILE_PROVIDER_PATHS”
android:resource=”@xml/file_paths”/>
</provider>
<meta-data android:name=”com.google.android.gms.vision.DEPENDENCIES” android:value=”face” />
</application>
</manifest>
6.- En nuestra carpeta layout en el archivo main_activity.xml agregamos estas lineas
<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:orientation=”vertical”
android:layout_width=”match_parent”
android:layout_height=”match_parent”>
<ImageView
android:src=”@android:drawable/ic_menu_gallery”
android:layout_width=”match_parent”
android:layout_height=”350.0dp”
android:id=”@+id/imageviewface” />
<Button
android:text=”Galeria”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:id=”@+id/btngalery” />
<Button
android:text=”Camara”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:id=”@+id/btncamera” />
<TextView
android:id=”@+id/txtDescription”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginBottom=”8dp”
android:layout_marginTop=”8dp”
android:gravity=”center” />
</LinearLayout>
7.- Ahora abrimos nuestro MainActivity.cs agregamos estas lineas
8.- En el OnCreate agregamos este codigo
9.- Agregamos los permisos en tiempo de ejecucion
10.- Generamos los Eventos clicked de los botones, y agregamos estos codigos
11.- Sobrescribimos el Metodo OnDestroy y agregamos esto
12.- sobreesceibimos el Metodo OnActivityResult
13.- Agregamos este metodo DecodeBitmapUri
14.- Por ultimo creamos este metodo ProcessCameraPicture
private void ProcessCameraPicture()
{
Bitmap bitmap = DecodeBitmapUri(this, imageUri);
if (detector.IsOperational && bitmap != null)
{
editedBitmap = Bitmap.CreateBitmap(bitmap.Width, bitmap
.Height, bitmap.GetConfig());
float scale = Resources.DisplayMetrics.Density;
Paint paint = new Paint(PaintFlags.AntiAlias);
paint.Color = Color.Green;
paint.TextSize = (int)(16 * scale);
paint.SetShadowLayer(1f, 0f, 1f, Color.White);
paint.SetStyle(Paint.Style.Stroke);
paint.StrokeWidth = 6f;
Canvas canvas = new Canvas(editedBitmap);
canvas.DrawBitmap(bitmap, 0, 0, paint);
Frame frame = new Frame.Builder().SetBitmap(editedBitmap).Build();
SparseArray faces = detector.Detect(frame);
string text = “”;
for (int index = 0; index < faces.Size(); ++index)
{
Face face = faces.ValueAt(index) as Face;
canvas.DrawRect(
face.Position.X,
face.Position.Y,
face.Position.X + face.Width,
face.Position.Y + face.Height, paint); //CREA EL RECUADRO
text += “Cara “ + (index + 1) + “\n”;
text += “Probilidad de una sonrisa:” + “ “ + face.IsSmilingProbability * 100 + “\n”;
text += “Probilidad que el ojo izquierdo este abierto : “ + “ “ + face.IsLeftEyeOpenProbability * 100 + “\n”;
text += “Probilidad que el ojo derecho este abierto: “ + “ “ + face.IsRightEyeOpenProbability * 100 + “\n”;
foreach (Landmark landmark in face.Landmarks)
{
int cx = (int)(landmark.Position.X);
int cy = (int)(landmark.Position.Y);
canvas.DrawCircle(cx, cy, 8, paint); // CREA EL CIRCULO
}
}
if (faces.Size() == 0)
{
txtDescription.Text = “Scaneo fallido”;
}
else
{
_imageView.SetImageBitmap(editedBitmap);
text += “\n\n” + “Numero de caras detectadas: “ + “ “ + faces.Size().ToString() + “\n\n”;
}
txtDescription.Text = text;
}
else
{
txtDescription.Text = “No se pudo configurar el detector!”;
}
}
DEMO
Sigamos apoyando a estas iniciativas.