目录

Face Verification

Use Cases

Face verification compares two input images and determines whether the two faces in the images are of the same person. If so, the system shows that they are the same person, with a high confidence score. If not, the system shows that they are different people, with a low confidence score. This function can be used in face verification scenarios, such as identity authentication and face unlock.

Example:

Development Procedure

  1. Add the classes for implementing face verification to a project.

    import { faceComparator } from '@kit.CoreVisionKit';
    import { image } from '@kit.ImageKit';
    import { hilog } from '@kit.PerformanceAnalysisKit';
    import { BusinessError } from '@kit.BasicServicesKit';
    import { fileIo } from '@kit.CoreFileKit';
    import { photoAccessHelper } from '@kit.MediaLibraryKit';
  2. Initialization and release: Call faceComparator.init() in aboutToAppear to initialize the faceComparator (load the model), and call faceComparator.release() in aboutToDisappear to release resources.

    async aboutToAppear(): Promise<void> {
      const initResult = await faceComparator.init();
      hilog.info(0x0000, TAG, `Face comparator initialization result:${initResult}`);
    }
    
    async aboutToDisappear(): Promise<void> {
      await faceComparator.release();
      hilog.info(0x0000, TAG, 'Face comparator released successfully');
    }
  3. Call photoAccessHelper.PhotoViewPicker to start the gallery to select two images to be compared, and use the fileIo and image modules to convert the URI to a PixelMap to prepare input data for the comparison API.

    Button('Select image')
      .type(ButtonType.Capsule)
      .fontColor(Color.White)
      .alignSelf(ItemAlign.Center)
      .width('80%')
      .margin(10)
      .onClick(() => {
        // Bring up the gallery to obtain images.
        void this.selectImage();
      })

    The method for selecting and decoding images is implemented as follows:

    private async selectImage() {
      let uri = await this.openPhoto();
      if (uri === undefined) {
        hilog.error(0x0000, TAG, 'Failed to get two image uris.');
        return;
      }
      this.loadImage(uri);
    }
    
    private async openPhoto(): Promise<string[]> {
      return new Promise<string[]>((resolve, reject) => {
        let photoPicker: photoAccessHelper.PhotoViewPicker = new photoAccessHelper.PhotoViewPicker();
        photoPicker.select({
          MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE,
          maxSelectNumber: 2
        }).then(res => {
          resolve(res.photoUris);
        }).catch((err: BusinessError) => {
          hilog.error(0x0000, TAG, `Failed to get photo image uris. code: ${err.code}, message: ${err.message}`);
          reject();
        });
      });
    }
    
    private loadImage(names: string[]) {
      setTimeout(async () => {
        let imageSource: image.ImageSource | undefined = undefined;
        let fileSource: fileIo.File;
        fileSource = await fileIo.open(names[0], fileIo.OpenMode.READ_ONLY);
        imageSource = image.createImageSource(fileSource.fd);
        this.chooseImage = await imageSource.createPixelMap();
        fileSource = await fileIo.open(names[1], fileIo.OpenMode.READ_ONLY);
        imageSource = image.createImageSource(fileSource.fd);
        this.chooseImage1 = await imageSource.createPixelMap();
        await fileIo.close(fileSource);
      }, 100);
    }
  4. Construct a VisionInfo object, pass the pixel maps of the two images, call the faceComparator.compareFaces method to obtain the similarity score, and display the result on the screen.

    Button('Compare faces')
      .type(ButtonType.Capsule)
      .fontColor(Color.White)
      .alignSelf(ItemAlign.Center)
      .width('80%')
      .margin(10)
      .onClick(() => {
        if (!this.chooseImage || !this.chooseImage1) {
          hilog.error(0x0000, TAG, 'Failed to choose image');
          return;
        }
        // Call the face verification API.
        let visionInfo: faceComparator.VisionInfo = {
          pixelMap: this.chooseImage
        };
        let visionInfo1: faceComparator.VisionInfo = {
          pixelMap: this.chooseImage1
        };
         faceComparator.compareFaces(visionInfo, visionInfo1)
         .then((data: faceComparator.FaceCompareResult) => {
           if (data !== undefined) {
             let faceString = `degree of similarity: ${this.toPercentage(data.similarity)}${(data.isSamePerson) ? '. is' : '. no'} same person`;
             hilog.info(0x0000, TAG, 'faceString data is ' + faceString);
             this.dataValues = faceString;
           } else {
             hilog.error(0x0000, TAG, 'Invalid data received from face comparison');
             this.dataValues = 'Error: Invalid data';
           }
         })
         .catch((error: BusinessError) => {
           hilog.error(0x0000, TAG, `Face comparison failed. Code: ${error.code}, message: ${error.message}`);
           this.dataValues = `Error: ${error.message}`;
         });
       })

    Auxiliary method for converting the similarity value to a percentage:

    private toPercentage(num: number): string {
      return `${(num * 100).toFixed(2)}%`;
    }

Development Example

[h2]Index.ets

import { faceComparator } from '@kit.CoreVisionKit';
import { image } from '@kit.ImageKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';

const TAG: string = 'FaceCompareSample';

@Entry
@Component
struct Index {
  @State chooseImage: PixelMap | undefined = undefined;
  @State chooseImage1: PixelMap | undefined = undefined;
  @State dataValues: string = '';

  async aboutToAppear(): Promise<void> {
    const initResult = await faceComparator.init();
    hilog.info(0x0000, TAG, `Face comparator initialization result:${initResult}`);
  }

  async aboutToDisappear(): Promise<void> {
    await faceComparator.release();
    hilog.info(0x0000, TAG, 'Face comparator released successfully');
  }

  build() {
    Column() {
      Image(this.chooseImage)
        .objectFit(ImageFit.Fill)
        .height('30%')
        .accessibilityDescription('Default image 1')
      Image(this.chooseImage1)
        .objectFit(ImageFit.Fill)
        .height('30%')
        .accessibilityDescription('Default image 2')
      Text(this.dataValues)
        .copyOption(CopyOptions.LocalDevice)
        .height('15%')
        .margin(10)
        .width('60%')
      Button('Select image')
        .type(ButtonType.Capsule)
        .fontColor(Color.White)
        .alignSelf(ItemAlign.Center)
        .width('80%')
        .margin(10)
        .onClick(() => {
          // Start Gallery.
          void this.selectImage();
        })
      Button('Compare faces')
        .type(ButtonType.Capsule)
        .fontColor(Color.White)
        .alignSelf(ItemAlign.Center)
        .width('80%')
        .margin(10)
        .onClick(() => {
          if (!this.chooseImage || !this.chooseImage1) {
            hilog.error(0x0000, TAG, 'Failed to choose image');
            return;
          }
          // Call the face verification API.
          let visionInfo: faceComparator.VisionInfo = {
            pixelMap: this.chooseImage
          };
          let visionInfo1: faceComparator.VisionInfo = {
            pixelMap: this.chooseImage1
          };
          faceComparator.compareFaces(visionInfo, visionInfo1)
            .then((data: faceComparator.FaceCompareResult) => {
              if (data !== undefined) {
                let faceString = `degree of similarity: ${this.toPercentage(data.similarity)}${(data.isSamePerson) ? '. is' : '. no'} same person`;
                hilog.info(0x0000, TAG, 'faceString data is ' + faceString);
                this.dataValues = faceString;
              } else {
                hilog.error(0x0000, TAG, 'Invalid data received from face comparison');
                this.dataValues = 'Error: Invalid data';
              }
            })
            .catch((error: BusinessError) => {
              hilog.error(0x0000, TAG, `Face comparison failed. Code: ${error.code}, message: ${error.message}`);
              this.dataValues = `Error: ${error.message}`;
            });
        })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }

  private toPercentage(num: number): string {
    return `${(num * 100).toFixed(2)}%`;
  }

  private async selectImage() {
    let uris: string[] = await this.openPhoto();
    if (uris === undefined || uris.length < 2) {
      hilog.error(0x0000, TAG, 'Failed to get two image uris.');
      return;
    }
    this.loadImage(uris);
  }

  private async openPhoto(): Promise<string[]> {
    return new Promise<string[]>((resolve, reject) => {
      let photoPicker: photoAccessHelper.PhotoViewPicker = new photoAccessHelper.PhotoViewPicker();
      photoPicker.select({
        MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE,
        maxSelectNumber: 2
      }).then(res => {
        resolve(res.photoUris);
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, TAG, `Failed to get photo image uris. code: ${err.code}, message: ${err.message}`);
        reject();
      });
    });
  }

  private loadImage(names: string[]) {
    setTimeout(async () => {
      let imageSource: image.ImageSource | undefined = undefined;
      let fileSource: fileIo.File;
      fileSource = await fileIo.open(names[0], fileIo.OpenMode.READ_ONLY);
      imageSource = image.createImageSource(fileSource.fd);
      this.chooseImage = await imageSource.createPixelMap();
      fileSource = await fileIo.open(names[1], fileIo.OpenMode.READ_ONLY);
      imageSource = image.createImageSource(fileSource.fd);
      this.chooseImage1 = await imageSource.createPixelMap();
      await fileIo.close(fileSource);
    }, 100);
  }
}