添加面部跟踪和实时识别到您的Android应用程序

今天的相机应用可以做的不仅仅是拍完美的照片。无论是添加过滤器到您的图像或让您调整焦点和手动曝光,应用程序可以从根本上把你变成一个专业摄影师。虽然应用商店中的众多应用程序让你用相机做很多事情,还有其他人可以实时地对你的图像进行巧妙的操作,例如在脸上添加自定义掩码,操纵你的脸看起来更老或更年轻,和更多的。今天的社交媒体应用程序有这样的智能,所以你不必打开另一个应用程序让你的自拍看起来平凡的在你与朋友和家人分享。

无论是构建一个提供有趣过滤器的用户应用程序,还是一个识别收入的企业应用程序,添加像这样的智能轮胎让你比其他人更有优势。通过像微软认知服务API这样的服务,您只需添加几行代码即可快速分析和处理照片。

在这篇文章中,您将学习如何在Android应用程序中显示一个摄像头,通过使用Google的移动视觉的APIs添加面部跟踪并使用微软认知服务的API通过前置相机来识别人脸。

添加面部跟踪和实时识别到您的Android应用程序

在应用程序中添加面部跟踪

Google的移动视觉提供了一组用于“检测面部”和“扫描条码”的API。对于这个示例,我将使用面部API从应用程序中的实时摄像机流中检测人脸。

开始, 添加 Xamarin.GooglePlayServices.Vision的 NuGet包。

添加面部跟踪和实时识别到您的Android应用程序

为了在Android*问相机,你需要在你的Android的mainifest中添加你的用户权限请求和相机功能:

点击(此处)折叠或打开

  1.     

  2. if (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.Camera) == Permission.Granted)

  3. {

  4.     CreateCameraSource();

  5.     //...

  6. }

  7. else

  8. {

  9. Log.Warn(TAG, "Camera permission is not granted. Requesting permission");

  10.  

  11. var permissions = new string[] { Manifest.Permission.Camera };

  12.  

  13. if (!ActivityCompat.ShouldShowRequestPermissionRationale(this,

  14.         Manifest.Permission.Camera))

  15. {

  16.     ActivityCompat.RequestPermissions(this, permissions, RC_HANDLE_CAMERA_PERM);

  17.     return;

  18. }

  19.  

  20. Snackbar.Make(mGraphicOverlay, Resource.String.permission_camera_rationale,

  21.         Snackbar.LengthIndefinite)

  22.         .SetAction(Resource.String.ok, (o) => { ActivityCompat.RequestPermissions(this, permissions, RC_HANDLE_CAMERA_PERM); })

  23.         .Show();

  24. }


创建相机源

通过指定的属性使用FaceDetector.Builder创建FaceDetector的一个实例。在本例中,我们使用默认的面部检测器设置,并将处理器关联到它。

点击(此处)折叠或打开

  1. private void CreateCameraSource()

  2. {

  3.  

  4.     var context = Application.Context;

  5.     FaceDetector detector = new FaceDetector.Builder(context)

  6.             .SetClassificationType(ClassificationType.All)

  7.             .Build();

  8.  

  9.     detector.SetProcessor(

  10.             new MultiProcessor.Builder(this)

  11.                     .Build());

  12.  

  13.     if (!detector.IsOperational)

  14.     {

  15.         // Note: The first time that an app using face API is installed on a device, GMS will

  16.         // download a native library to the device in order to do detection.  Usually this

  17.         // completes before the app is run for the first time.  But if that download has not yet

  18.         // completed, then the above call will not detect any faces.

  19.         //

  20.         // isOperational() can be used to check if the required native library is currently

  21.         // available.  The detector will automatically become operational once the library

  22.         // download completes on the device.

  23.         Log.Warn(TAG, "Face detector dependencies are not yet available.");

  24.     }

  25.  

  26.     mCameraSource = new CameraSource.Builder(context, detector)

  27.             .SetRequestedPreviewSize(640, 480)

  28.             .SetFacing(CameraFacing.Front)

  29.             .SetRequestedFps(30.0f)

  30.             .Build();

  31.  

  32.     

  33. }


在上面的代码中, MultiProcessor被用来接收侦测结果,CameraSource.Builder用来创建一个指定预览尺寸,相机面对面和所需的FPS的相机源。


在相机显示一个实时图像

现在我们已经进入相机并且建立CameraSource,我们也可以通过自定义一个SurfaceView开始预览;本例中CameraSourcePreview.GraphicOverlay实例也被传递,以便在检测时绘制面部边界。

点击(此处)折叠或打开

  1. private void StartCameraSource()

  2. {

  3.  

  4.     // check that the device has play services available.

  5.     int code = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(

  6.             this.ApplicationContext);

  7.     if (code != ConnectionResult.Success)

  8.     {

  9.         var dlg =

  10.                 GoogleApiAvailability.Instance.GetErrorDialog(this, code, RC_HANDLE_GMS);

  11.         dlg.Show();

  12.     }

  13.  

  14.     if (mCameraSource != null)

  15.     {

  16.         try

  17.         {

  18.             mPreview.Start(mCameraSource, mGraphicOverlay);

  19.         }

  20.         catch (System.Exception e)

  21.         {

  22.             Log.Error(TAG, "Unable to start camera source.", e);

  23.             mCameraSource.Release();

  24.             mCameraSource = null;

  25.         }

  26.     }

  27. }


调用StartCameraSource()最好的地方是在Activity的OnResume()中,在OnPause()中停止预览。它将确保只有在用户使用应用程序时才使用相机资源。

人脸检测

从相机源接收的每个图像帧可以包含多个面,并且每个面对应由由多处理器创建的跟踪器表示的明显的面部标识。

实现iFactory捕捉每个面

MultiProcessor要求实现IFactory,在相机检测到一个人脸时以便回调。在本例中,在MainActivity中实现了IFactory,包含了Create():

点击(此处)折叠或打开

  1. public Tracker Create(Java.Lang.Object item)

  2. {

  3.     return new GraphicFaceTracker(mGraphicOverlay, mCameraSource);

  4. }


在上面的代码中,在每检测到一张人脸时都会创建GraphicFaceTracker的一个实例,每个构建人脸框图形对象在使用构造函数通过GraphicOverlay查看视频流。

下面是GraphicFaceTracker的一个实现:

点击(此处)折叠或打开

  1. class GraphicFaceTracker : Tracker

  2. {

  3.     private GraphicOverlay mOverlay;

  4.     private FaceGraphic mFaceGraphic;

  5.  

  6.     public GraphicFaceTracker(GraphicOverlay overlay)

  7.     {

  8.         mOverlay = overlay;

  9.         mFaceGraphic = new FaceGraphic(overlay);

  10.     }

  11.  

  12.     public override void OnNewItem(int id, Java.Lang.Object item)

  13.     {

  14.         mFaceGraphic.SetId(id);

  15.     }

  16.  

  17.     public override void OnUpdate(Detector.Detections detections, Java.Lang.Object item)

  18.     {

  19.         var face = item as Face;

  20.         mOverlay.Add(mFaceGraphic);

  21.         mFaceGraphic.UpdateFace(face);

  22.     }

  23.  

  24.     public override void OnMissing(Detector.Detections detections)

  25.     {

  26.         mOverlay.Remove(mFaceGraphic);

  27.     }

  28.  

  29.     public override void OnDone()

  30.     {

  31.         mOverlay.Remove(mFaceGraphic);

  32.     }

  33. }



在第一次检测到一张脸时会创建FaceGraphic的一个实例,在脸发生变化时会更新,当脸离开时会隐藏。

正是这样,我们成功地在应用程序中自定义的相机表面上创建了人脸跟踪!接下来,我们将识别帧内的人。

从实时流中识别脸

从实时视频帧中识别脸,每当检测到新的人脸并将其发送给微软认知服务API来识别此人时,我们就捕捉图像。人脸识别需要人工智能和高效的机器学习算法,提供给您的服务和免费开始。如果你是认知服务新手,我强烈推荐阅读博客文章,增加对移动应用程序的面部识别。

捕获检测到的人脸

捕捉新发现的人脸,首先改变GraphicFaceTracker实现CameraSource.IPictureCallback。

点击(此处)折叠或打开

  1. class GraphicFaceTracker : Tracker, CameraSource.IPictureCallback

  2. {

  3.     //...

  4. }

修改OnNewItem()捕捉面部图像帧

点击(此处)折叠或打开

  1. public override void OnNewItem(int id, Java.Lang.Object item)

  2. {

  3.     mFaceGraphic.SetId(id);

  4.     if (mCameraSource != null && !isProcessing)

  5.         mCameraSource.TakePicture(null, this);

  6. }



识别捕获帧中的人

最后,使用助手类ImageAnalyzer  和iveCamHelper (这些抽象了COGs API调用),我们从视频流中识别一个人。

点击(此处)折叠或打开

  1. public void OnPictureTaken(byte[] data)

  2. {

  3.     Task.Run(async () =>

  4.     {

  5.         try

  6.         {

  7.             isProcessing = true;

  8.  

  9.             Console.WriteLine("face detected: ");

  10.  

  11.             var p_w_picpathAnalyzer = new ImageAnalyzer(data);

  12.             await LiveCamHelper.ProcessCameraCapture(p_w_picpathAnalyzer);

  13.         }

  14.  

  15.         finally

  16.         {

  17.             isProcessing = false;

  18.         }

  19.     });

  20. }

https://s3.amazonaws.com/blog.xamarin.com/wp-content/uploads/2017/06/12050912/En-Face.mp4

结束语

人脸识别在许多场景中被广泛使用,包括安全性,自然用户界面、机器人技术等等。通过使用这些服务和平台API的组合,你可以建立无与伦比的移动应用程序,智能和五星级用户提供经验。在这个博客文章,我们使用谷歌移动视觉API来检测视频流和微软认知服务中的人脸以识别帧内的人。在iOS上构建相同的示例,请阅读如何在iOS应用程序中显示相机 和 添加面部识别到您的移动应用程序。

在这篇文章中构建并解释的示例是由谷歌开发人员关于面部跟踪的文档启发的。

对于iOS和Android从我的GitHub的回购下载样本。 注意:对于这个演示,我编写了代码来识别框架中的一个单独的面。不过,请随意修改并使之变得更好。