鸿蒙AI功能开发【hiai引擎框架-人脸比对】 基础视觉服务

hiai引擎框架-人脸比对

介绍

本示例展示了使用hiai引擎框架提供的人脸比对能力。

本示例模拟了在应用里,选择两张图片,计算两个图中最大人脸的相似度

需要使用hiai引擎框架人脸比对接口@hms.ai.face.faceComparator。

效果预览

使用说明:

  1. 在手机的主屏幕,点击"faceComparatorDemo",启动应用。
  2. 点击"选择图片"按钮,默认自带一张图片,用户可以在图库中选择图片,或者通过相机拍照。
  3. 点击"人脸比对"按钮,比对人脸信息,结果通过文本展示。

具体实现

本示例展示的控件在@hms.ai.face.faceComparator.d.ets定义了文字比对API:

复制代码
    function compareFaces(visionInfo1: VisionInfo, visionInfo2: VisionInfo): Promise<FaceCompareResult>;

业务使用时,需要先进行import导入faceComparator 调用通用人脸比对接口,并传入想要比对的图片,接收处理返回的结果(文字信息)。参考:

复制代码
import { faceComparator } from '@kit.CoreVisionKit';
import { image } from '@kit.ImageKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { picker, fileIo } from '@kit.CoreFileKit';

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

  build() {
    Column() {
      Image(this.chooseImage)
        .objectFit(ImageFit.Fill)
        .height('30%')
        .accessibilityDescription("默认图片1")

      Image(this.chooseImage1)
        .objectFit(ImageFit.Fill)
        .height('30%')
        .accessibilityDescription("默认图片2")

      Text(this.dataValues)
        .copyOption(CopyOptions.LocalDevice)
        .height('15%')
        .margin(10)
        .width('60%')

      Button('选择图片')
        .type(ButtonType.Capsule)
        .fontColor(Color.White)
        .alignSelf(ItemAlign.Center)
        .width('80%')
        .margin(10)
        .onClick(() => {
          // 拉起图库
          this.selectImage()
        })

      Button('人脸比对')
        .type(ButtonType.Capsule)
        .fontColor(Color.White)
        .alignSelf(ItemAlign.Center)
        .width('80%')
        .margin(10)
        .onClick(async () => {
          if(!this.chooseImage || !this.chooseImage1) {
            hilog.error(0x0000, 'FaceCompareSample', `Failed to choose image. chooseImage: ${this.chooseImage}`);;
            return;
          }
          // 调用人脸比对接口
          let visionInfo: faceComparator.VisionInfo = {
            pixelMap: this.chooseImage,
          };
          let visionInfo1: faceComparator.VisionInfo = {
            pixelMap: this.chooseImage1,
          };
          try {
            let data:faceComparator.FaceCompareResult = await faceComparator.compareFaces(visionInfo, visionInfo1);
            let faceString = "相似度:"+ this.toPercentage(data.similarity)+((data.isSamePerson)?"。 是":"。 不是")+"同一个人";
            hilog.info(0x0000, 'FaceCompareSample', `Succeeded in face detect:${faceString}`);
            this.dataValues = faceString;
          } catch (error) {
            hilog.error(0x0000, 'FaceCompareSample', `人脸比对出错: ${error}`);
            this.dataValues = "人脸比对出错,请确保两张图片中都有人脸。";
          }
        })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }

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

  private async selectImage() {
    let uri = await this.openPhoto()
    if (uri === undefined) {
      hilog.error(0x0000, 'FaceCompareSample', "Failed to defined uri.");
    }
    this.loadImage(uri);
  }

  private openPhoto(): Promise<Array<string>> {
    return new Promise<Array<string>>((resolve, reject)=>{
      let PhotoSelectOptions = new picker.PhotoSelectOptions();
      PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
      PhotoSelectOptions.maxSelectNumber = 2;
      let photoPicker = new picker.PhotoViewPicker();
      photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult) => {
        resolve(PhotoSelectResult.photoUris)
      }).catch((err:BusinessError) => {
        hilog.error(0x0000, 'faceDetectorSample', `Failed to get photo image uri. code:${err.code},message:${err.message}`);
        reject();
      });
    })
  }

  private loadImage(names: string[]) {
    setTimeout(async () => {
      let imageSource: image.ImageSource | undefined = undefined;
      let 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();
    }, 100
    )
  }
}

以上就是本篇文章所带来的鸿蒙开发中一小部分技术讲解;想要学习完整的鸿蒙全栈技术。可以在结尾找我可全部拿到!

下面是鸿蒙的完整学习路线 ,展示如下:

除此之外,根据这个学习鸿蒙全栈学习路线,也附带一整套完整的学习【文档+视频】,内容包含如下

内容包含了:(ArkTS、ArkUI、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、鸿蒙南向开发、鸿蒙项目实战)等技术知识点。帮助大家在学习鸿蒙路上快速成长!

鸿蒙【北向应用开发+南向系统层开发】文档

鸿蒙【基础+实战项目】视频

鸿蒙面经

为了避免大家在学习过程中产生更多的时间成本,对比我把以上内容全部放在了↓↓↓想要的可以自拿喔!谢谢大家观看!

相关推荐
淼澄研学3 分钟前
大模型应用开发实战:从API调用到RAG与Agent架构的5个核心落地方案
人工智能·架构
b130538100498 分钟前
HarmonyOS应用《玄象》开发实战:命盘排布 Canvas:四柱干支 + 六十甲子纳音表的同步绘制
harmonyos·鸿蒙
蓝速科技9 分钟前
蓝速 AI 双屏翻译机:铝型材精工机身为何碾压塑料公模
人工智能
猫先生Mr.Mao10 分钟前
视频生成之LongLive-2.0详解:如何把 5B 长视频生成推到 45.7 FPS
ai·论文解读·视频生成·ai视频·longlive-2.0
Cosolar12 分钟前
Claude Opus 5 系统提示词被完整泄露,共 135027 字符、约 3.4 万 token
人工智能·后端·架构
腾视科技AIoT16 分钟前
腾视科技重磅发布全场景无人叉车及智能调度系统解决方案,开启工业物流智能新时代
人工智能·科技·ai·无人车·ai算力·无人叉车·低速无人车
Hrain-AI17 分钟前
2026 企业级 AI Agent 本地化部署选型:6 维度 + 避坑清单
人工智能
爱写代码的阿森18 分钟前
鸿蒙三方库 | harmony-utils之ArrayUtil集合过滤排序与分块详解
华为·harmonyos·鸿蒙·huawei
不言鹅喻20 分钟前
HarmonyOS ArkTS 实战:实现一个掷骰子模拟器
华为·harmonyos
过期的秋刀鱼!29 分钟前
项目实战-神经网络预测
人工智能·神经网络·机器学习