鸿蒙人脸识别

鸿蒙人脸识别

参考文档

鸿蒙原生提供用于实现人脸识别的API。感觉能够实现一些好玩的效果。

javascript 复制代码
private detectFace(img: PixelMap) {
  // 调用人脸检测接口
  faceDetector.init();
  let visionInfo: faceDetector.VisionInfo = {
    pixelMap: img,
  };
  faceDetector.detect(visionInfo)
    .then((data: faceDetector.Face[]) => {
      if (data.length === 0) {
      } else {
        let faceString = JSON.stringify(data);
        hilog.info(0x0000, 'faceDetectorSample', "faceString data is " + faceString);
        promptAction.showDialog({
          message: `识别到信息  ${faceString}`
        })
      }
    })
    .catch((error: BusinessError) => {
      hilog.error(0x0000, 'faceDetectorSample', `Face detection failed. Code: ${error.code}, message: ${error.message}`);
    });
  faceDetector.release();
}

示例代码

javascript 复制代码
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { image } from '@kit.ImageKit';
import { fileIo } from '@kit.CoreFileKit';
import { faceDetector } from '@kit.CoreVisionKit';
import { promptAction } from '@kit.ArkUI';

const TAG: string = "index";

@Entry
@Component
struct Index {
  @State chooseImage: image.PixelMap | null = null
  @State segImage: image.PixelMap | null = null

  private openPhoto(): Promise<Array<string>> {
    return new Promise<Array<string>>((resolve, reject) => {
      let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
      PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
      PhotoSelectOptions.maxSelectNumber = 1;
      let photoPicker: photoAccessHelper.PhotoViewPicker = new photoAccessHelper.PhotoViewPicker();
      hilog.info(0x0000, TAG, 'PhotoViewPicker.select successfully, PhotoSelectResult uri: ');
      photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult) => {
        hilog.info(0x0000, TAG, `PhotoViewPicker.select successfully, PhotoSelectResult uri: ${PhotoSelectResult.photoUris}`);
        resolve(PhotoSelectResult.photoUris)
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, TAG, `PhotoViewPicker.select failed with errCode: ${err.code}, errMessage: ${err.message}`);
        reject();
      });
    })
  }

  private async loadImage(path: string) {
    let imageSource: image.ImageSource | undefined = undefined
    let fileSource = await fileIo.open(path, fileIo.OpenMode.READ_ONLY)
    imageSource = image.createImageSource(fileSource.fd)
    this.chooseImage = await imageSource.createPixelMap()
    hilog.info(0x0000, TAG, `this.chooseImage===${this.chooseImage}`);
  }

  private detectFace(img: PixelMap) {
    // 调用人脸检测接口
    faceDetector.init();
    let visionInfo: faceDetector.VisionInfo = {
      pixelMap: img,
    };
    faceDetector.detect(visionInfo)
      .then((data: faceDetector.Face[]) => {
        if (data.length === 0) {
        } else {
          let faceString = JSON.stringify(data);
          hilog.info(0x0000, 'faceDetectorSample', "faceString data is " + faceString);
          promptAction.showDialog({
            message: `识别到信息  ${faceString}`
          })
        }
      })
      .catch((error: BusinessError) => {
        hilog.error(0x0000, 'faceDetectorSample', `Face detection failed. Code: ${error.code}, message: ${error.message}`);
      });
    faceDetector.release();
  }

  build() {
    Column() {
      Image(this.chooseImage)
        .objectFit(ImageFit.Contain)
        .width('100%')
        .height('40%')

      Row() {
        Image(this.segImage)
          .objectFit(ImageFit.Contain)
          .width('100%')
          .height('100%')
      }
      .width('100%')
      .height('40%')

      Blank()

      Row() {
        Text('选择图片')
          .height(50)
          .width(140)
          .borderRadius(25)
          .textAlign(TextAlign.Center)
          .backgroundColor(Color.Orange)
          .onClick(async () => {
            let urls = await this.openPhoto()
            if (urls.length > 0) {
              let url = urls[0]
              this.loadImage(url)
            }
          })

        Text('人脸识别')
          .height(50)
          .width(140)
          .borderRadius(25)
          .textAlign(TextAlign.Center)
          .backgroundColor(Color.Orange)
          .onClick(async () => {
            if (this.chooseImage) {
              this.detectFace(this.chooseImage)
            }
          })
      }
    }
    .height('100%')
    .width('100%')
  }
}

后记

最近利用这些知识上架了两个应用

小鱼证件照,免费便捷的证件照生成工具。

小鱼抽签。出门之前占卜吉凶,总会有好事发生。

第1签 锤离成道

天开地辟结良缘,日吉时良万事全,若得此签非小可,人行中正帝王宜

上上签

子宫

此卦盘古初开天地之象,诸事皆吉也

快使用鸿蒙next版本扫一扫体验一下吧~

相关推荐
Lanren的编程日记几秒前
Flutter 鸿蒙应用快捷操作功能实战:快捷菜单+快捷手势+快捷键支持,打造高效操作体验
flutter·华为·harmonyos
memoryjs5 分钟前
鸿蒙系统进一步学习(二):ArkUI底层原理揭秘
学习·华为·harmonyos
XiYang-DING19 分钟前
【Java EE】锁策略、锁升级、锁消除和锁粗化
java·redis·java-ee
木斯佳26 分钟前
HarmonyOS 本地存储实战:用一个记账本案例吃透 RDB 与 KVStore
harmonyos·存储
苗俊祥29 分钟前
纯AI打造沐界输入法--简洁、流畅、实用的 HarmonyOS 中文输入法
华为·harmonyos
小成Coder1 小时前
【Jack实战】如何给《时光旅记》接入跨设备拍照和跨设备相册导入
华为·harmonyos·鸿蒙·码上创新
maaath1 小时前
【maaath】Flutter for OpenHarmony 集成应用更新能力
flutter·华为·harmonyos
key_3_feng1 小时前
鸿蒙6.0 Widget服务卡片落地方案
华为·harmonyos
maaath1 小时前
【maaath】 OpenHarmony 设备信息获取能力集成指南
flutter·华为·harmonyos
Devin~Y1 小时前
大厂Java面试实录:Spring Boot/Cloud + Redis/Kafka + JWT + RAG/Agent(小Y翻车版)
java·spring boot·redis·spring cloud·kafka·spring security·jwt