目录

Face Tracking (ArkTS)

Constraints

Since version 6.1.0(23), the face tracking capability has been supported on a subset of phones and tablets, and all TVs. You can check whether a device supports the capability (ARENGINE_FEATURE_TYPE_FACE) by referring to Hardware Requirements.

API Description

Face tracking mainly depends on ARFace. The following lists APIs related to face tracking. For details about the APIs, please refer to AR Engine API Reference.

API Description
ARSession.getFrame Obtains a processed frame from AR Engine.
ARSession.getAllTrackables Obtains the face object contained in the current session.
ARFace.getGeometry Returns a geometric object that describes a face.
ARFace.getBlendShapes Returns a facial micro-expression object.

Development Procedure

For any AR app built with ArkTS, you must first check whether the current device supports this feature by referring to the AR feature check description. If the device supports this feature, create an AR session ARViewContext to manage the system status of AR Engine. Create an AR session ARViewContext by referring to Managing AR Sessions.

[h2]Importing Modules

The modules required for face tracking are as follows:

import { arEngine, ARView, arViewController } from '@kit.AREngine';
import {CustomGeometry, Geometry, Material, MaterialType, MeshResource, Node, PrimitiveTopology,
  Scene, SceneResourceFactory, Shader, ShaderMaterial, Vec3} from '@kit.ArkGraphics3D';
import { BusinessError } from '@kit.BasicServicesKit';
import { logger } from '../utils/Logger';
import {arrayBufferFloat32ToNumber, arrayBufferInt32ToNumber, generateFaceMeshIndex,
  generateMeshInput, getFaceFrontVertices} from '../utils/Utils';

[h2]Defining Variables

Define the variable face to receive the face object, the variable faceGeometry to receive the geometric object that describes a face, and the variable faceBlendShapes to receive the facial micro-expression object.

let face: arEngine.ARFace = trackables[i] as arEngine.ARFace;
// ...
// Data processing.
let faceGeometry: arEngine.ARGeometry = face.getGeometry();
let faceBlendShapes: arEngine.ARBlendShapes = face.getBlendShapes();

[h2]Displaying the Preview Stream

First, initialize the AR session and AR scene. For details, please refer to Initializing the AR Session and AR Scene.

Change the value of type to ARType.FACE, the value of cameraLensFacing to ARCameraLensFacing.FRONT, and the value of multiFaceMode to ARMultiFaceMode.MULTIFACE_ENABLE to enable the face tracking capability of the front camera.

@Builder
export function ARFaceBuilder() {
  ARFace();
}
// ...
@Component
export struct ARFace {
  pageInfos: NavPathStack = new NavPathStack();
  @State context: Context = this.getUIContext().getHostContext() as Context;
  @State arContext?: arViewController.ARViewContext = undefined;

  build() {
    NavDestination() {
      RelativeContainer() {
        if (this.arContext) {
          ARView({ context: this.arContext })
            .height('100%')
            .width('100%')
            .alignRules({
              center: { anchor: '__container__', align: VerticalAlign.Center },
              middle: { anchor: '__container__', align: HorizontalAlign.Center }
            })
        }
      }
    }
    .onAppear(async () => {
      this.initARView();
    })
    .onWillDisappear(async () => {
      await this.stopARView();
      this.clearGlobalVariables();
    })
    .onShown(() => {
      this.resumeARView();
    })
    .onHidden(() => {
      this.pauseARView();
    })
    .hideTitleBar(true)
    .hideBackButton(true)
    .hideToolBar(true)
  }

  private async stopARView(): Promise<void> {
    if (!this.arContext) {
      return;
    }
    try {
      await this.arContext.destroy();
    } catch (error) {
      const err: BusinessError = error as BusinessError;
      logger.error(`Failed to pause context. Code is ${err.code}, message is ${err.message}`);
    }
  }

  private pauseARView(): void {
    if (!this.arContext) {
      return;
    }
    try {
      this.arContext.pause();
    } catch (error) {
      const err: BusinessError = error as BusinessError;
      logger.error(`Failed to pause context. Code is ${err.code}, message is ${err.message}`);
    }
  }

  private resumeARView(): void {
    if (!this.arContext) {
      return;
    }
    try {
      this.arContext.resume();
    } catch (error) {
      const err: BusinessError = error as BusinessError;
      logger.error(`Failed to resume context. Code is ${err.code}, message is ${err.message}`);
    }
  }

  private initARView(): void {
    Scene.load().then(async (result: Scene) => {
      try {
        let ret: boolean = arViewController.isARTypeSupported(arEngine.ARFeatureType.ARENGINE_FEATURE_TYPE_FACE);
        logger.info(`ARFace isARTypeSupported is ${ret}`);
      } catch (error) {
        const err: BusinessError = error as BusinessError;
        logger.error(
          `Failed to get whether the device is support ARFace. Code is ${err.code}, message is ${err.message}`);
      }

      let context = new arViewController.ARViewContext();
      context.scene = result;
      context.callback = new ARViewCallbackImpl();
      context.config = {
        type: arEngine.ARType.FACE,
        planeFindingMode: arEngine.ARPlaneFindingMode.DISABLED,
        powerMode: arEngine.ARPowerMode.NORMAL,
        focusMode: arEngine.ARFocusMode.AUTO,
        cameraLensFacing: arEngine.ARCameraLensFacing.FRONT,
        multiFaceMode: arEngine.ARMultiFaceMode.MULTIFACE_ENABLE,
      };
      context.init().then(() => {
        this.arContext = context;
      }).catch((err: BusinessError) => {
        logger.error(`Failed to init context. Code is ${err.code}, message is ${err.message}`);
      });
    })
  }
  // ...
}

[h2]Obtaining Geometric and Micro-Expression Data of a Face

Call ARViewCallback and use its onFrameUpdate method to update frame data. Use ARSession.getFrame to obtain the current frame, use ARSession.getAllTrackables to obtain the face object data contained in the current session, and use ARFace.getGeometry and ARFace.getBlendShapes to obtain the recognized geometric and micro-expression information from the face object data. For details about the definition of related variables, please refer to Defining Variables.

class ARViewCallbackImpl extends arViewController.ARViewCallback {
  onAnchorAdd(ctx: arViewController.ARViewContext, node: Node, anchor: arEngine.ARAnchor): void {
  }

  onAnchorUpdate(ctx: arViewController.ARViewContext, node: Node, anchor: arEngine.ARAnchor): void {
  }

  async onFrameUpdate(ctx: arViewController.ARViewContext, sysBootTs: number): Promise<void> {
    if (!ctx.session) {
      logger.error('arSession is undefined');
      return;
    }

    let session: arEngine.ARSession = ctx.session;
    // ...
    try {
      let mesh = new CustomGeometry();
      let geometry: Geometry | null = null;
      if (session == null) {
        logger.error('session is null');
      }

      let vertexArray: Vec3[][] = [];
      let indexArray: Map<number, number[]> = new Map;

      // Obtain the face data.
      let trackables: arEngine.ARTrackable[] = session.getAllTrackables(arEngine.ARTrackableType.FACE);
      logger.debug(`the faceList length is ${trackables.length}`);
      for (let i = 0; i < trackables.length; ++i) {
        let face: arEngine.ARFace = trackables[i] as arEngine.ARFace;
        let centerPose = face.getPose();
        let viewMatrix = centerPose.getMatrix();

        if (trackables[i].state !== arEngine.ARTrackingState.TRACKING) {
          logger.error(`Face not in tracking state`);
          continue;
        }
        // Data processing.
        let faceGeometry: arEngine.ARGeometry = face.getGeometry();
        let faceBlendShapes: arEngine.ARBlendShapes = face.getBlendShapes();
        let tmpVert = faceGeometry.getVertices();
        let tmpIndices = faceGeometry.getIndices();
        faceVertices = arrayBufferFloat32ToNumber(tmpVert);
        let faceIndices: number[] = arrayBufferInt32ToNumber(tmpIndices);
        vertexArray.push(getFaceFrontVertices(viewMatrix, faceVertices));
        indexArray.set(i, faceIndices);

        // BlendShapes logging.
        logger.info('the count of blendShapes is' + faceBlendShapes.count);
        logger.info('the data of blendShapes is' + arrayBufferFloat32ToNumber(faceBlendShapes.getData()));
        logger.info('the types of blendShapes is' + faceBlendShapes.getTypes());
      }

      // ...
    } catch (error) {
      const err: BusinessError = error as BusinessError;
      logger.error(`Failed to acquire face information. Code is ${err.code}, message is ${err.message}`)
    }
  }
}