鸿蒙应用开发之基础视觉服务多目标识别基础

仿佛云烟
发布于 2025-6-28 17:02
浏览
0收藏

一、工具


鸿蒙应用开发之基础视觉服务多目标识别基础-鸿蒙开发者社区

DevEco Studio


二、项目介绍



开发步骤
在使用多目标识别时,将实现多目标识别相关的类添加至工程。
import { BusinessError } from '@kit.BasicServicesKit';
import { objectDetection, visionBase } from '@kit.CoreVisionKit';
简单配置页面的布局,并在Button组件添加点击事件,拉起图库,选择图片。
Button('选择图片')
  .type(ButtonType.Capsule)
  .fontColor(Color.White)
  .alignSelf(ItemAlign.Center)
  .width('80%')
  .margin(10)
  .onClick(() => {
    // 拉起图库,获取图片资源
    this.selectImage();
  })
通过图库获取图片资源,将图片转换为PixelMap。
private async selectImage() {
  let uri = await this.openPhoto()
  if (uri === undefined) {
    hilog.error(0x0000, 'objectDetectSample', "Failed to defined uri.");
  }
  this.loadImage(uri)
}


private openPhoto(): Promise {
  return new Promise((resolve, reject) => {
    let photoPicker: photoAccessHelper.PhotoViewPicker = new photoAccessHelper.PhotoViewPicker();
    photoPicker.select({
      MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE, maxSelectNumber: 1
    }).then(res => {
      resolve(res.photoUris[0])
    }).catch((err: BusinessError) => {
      hilog.error(0x0000, 'objectDetectSample', ​​​Failed to get photo image uri. code:${err.code},message:${err.message}​​​);
      reject('')
    })
  })
}


private loadImage(name: string) {
  setTimeout(async () => {
    let fileSource = await fileIo.open(name, fileIo.OpenMode.READ_ONLY);
    this.imageSource = image.createImageSource(fileSource.fd);
    this.chooseImage = await this.imageSource.createPixelMap();
  }, 100)
}
实例化Request对象,并传入待检测图片的PixelMap,调用多目标识别的实现多目标识别功能。
// 调用多目标检测接口
let request: visionBase.Request = {
  inputData: { pixelMap: this.chooseImage }
};
let data: objectDetection.ObjectDetectionResponse = await (await objectDetection.ObjectDetector.create()).process(request);
(可选)如果需要将结果展示在界面上,可以使用下列代码。
let objectJson = JSON.stringify(data);
​​​hilog.info​​​(0x0000, 'objectDetectSample', ​​Succeeded in object detection:${objectJson}​​​);
this.dataValues = objectJson;
开发实例
点击“选择图片”按钮,触发AI多目标识别功能。


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


@Entry
@Component
struct Index {
  private imageSource: image.ImageSource | undefined = undefined;
  @State chooseImage: PixelMap | undefined = undefined
  @State dataValues: string = ''


  build() {
    Column() {
      Image(this.chooseImage)
        .objectFit(ImageFit.Fill)
        .height('60%')


      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) {
            hilog.error(0x0000, 'objectDetectSample', ​​​Failed to choose image. chooseImage: ${this.chooseImage}​​​);
            return;
          }
          let request: visionBase.Request = {
            inputData: { pixelMap: this.chooseImage }
          };
          let data: objectDetection.ObjectDetectionResponse = await (await objectDetection.ObjectDetector.create()).process(request);
          let objectJson = JSON.stringify(data);
          ​​​hilog.info​​​(0x0000, 'objectDetectSample', ​​Succeeded in object detection:${objectJson}​​​);
          this.dataValues = objectJson;
        })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }


  private async selectImage() {
    try {
      let uri = await this.openPhoto();
      if (uri === undefined) {
        hilog.error(0x0000, 'objectDetectSample', "Failed to defined uri.");
        return;
      }
      this.loadImage(uri);
    } catch (err) {
      hilog.error(0x0000, 'objectDetectSample', ​​​Failed to get photo image uri. code:${err.code}, message:${err.message}​​​);
    }
  }


{
    return new Promise((resolve, reject) => {
      let photoPicker: photoAccessHelper.PhotoViewPicker = new photoAccessHelper.PhotoViewPicker();
      photoPicker.select({
        MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE, maxSelectNumber: 1
      }).then(res => {
        resolve(res.photoUris[0]);
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'objectDetectSample', ​​​Failed to get photo image uri. code:${err.code}, message:${err.message}​​​);
        reject(err);
      })
    })
  }


  private loadImage(name: string) {
    setTimeout(async () => {
      let fileSource = await fileIo.open(name, fileIo.OpenMode.READ_ONLY);
      this.imageSource = image.createImageSource(fileSource.fd);
      this.chooseImage = await this.imageSource.createPixelMap();
    }, 100)
  }
}

收藏
回复
举报
回复
    相关推荐