HarmonyOS开发-系统AI视觉能力-图片识别

HarmonyOS开发-系统AI视觉能力-图片识别

简介

本文继续介绍HarmonyOS提供的AI能力,Core Vision Kit(基础视觉服务)提供了机器视觉相关的基础能力,本文将着重梳理一下AI视觉服务的使用流程,代码实现等,我们整体的流程是先从手机中选取图片,可以使用本地图片,也可以拍照,选取图片后,我们进行图片识别,话不多说,我们直接上代码

开发步骤:

第一步:我们先要引入视觉服务的工具类,我们这次演示的功能是文字识别,所以我们引入对应的文字

复制代码
import { textRecognition } from '@kit.CoreVisionKit'

另外,我们是在图片识别中需要用图片,选取本地文件和拍照功能,所以我们要对应引入图片的工具类,文件操作工具类,拍照工具类

复制代码
import { image } from '@kit.ImageKit';
import { fileIo } from '@kit.CoreFileKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';

第二步:根据图片识别的步骤,我们需要先选取图片,定义一个图片选取的方法,其中可以调用拍照,代码如下:

复制代码
 //选择图片
   async selectImage() {
 //这里我们调用图片选取的方法,方法在下面定义了
    let uri = await this.openPicture();
 
    console.log("xwq:::"+JSON.stringify(uri))
    setTimeout(
      async () => {
        let imageSource: image.ImageSource | undefined = undefined;
        let fileSource = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
        imageSource = image.createImageSource(fileSource.fd);
        this.chooseImage = await imageSource.createPixelMap();
    },100)

  }
    })
  }

第三步:打开图片选取picker,这块是单独的媒体管理能力,稍后我们另外去讲解

复制代码
```
//打开本地入库
openPicture(): Promise<string> {
    return new Promise<string>((resolve) => {
      let photoPicker: photoAccessHelper.PhotoViewPicker = new photoAccessHelper.PhotoViewPicker();
      photoPicker.select({
        MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE,
        maxSelectNumber: 1
      }).then((res: photoAccessHelper.PhotoSelectResult) => {
        resolve(res.photoUris[0]);
      }).catch((err: BusinessError) => {
        resolve('');
      })
    })
  }
```

第四步:对选取的图片进行文字识别,我们使用什么样的功能就选用对用的方法,在这里,我们使用textRecognition.recognizeText方法,这里的参数我们按照官方的文档参数进行填写即可

复制代码
textRecogn() {
    // 调用文本识别接口
    if (!this.chooseImage) {
      return
    }
    //VisionInfo为待OCR检测识别的入参项,目前仅支持PixelMap类型的视觉信息。
    let visionInfo: textRecognition.VisionInfo = {
      pixelMap: this.chooseImage
    };
    //配置通用文本识别的配置项TextRecognitionConfiguration,用于配置是否支持朝向检测
    let textConfiguration: textRecognition.TextRecognitionConfiguration = {
      isDirectionDetectionSupported: false
    };
    textRecognition.recognizeText(visionInfo, textConfiguration)
      .then((data: textRecognition.TextRecognitionResult) => {
        // 将结果更新到Text中显示
        this.dataValues = data.value;
      })
      .catch((error: BusinessError) => {
        this.dataValues = `Error: ${error.message}`;
      });
  }

基于以上四步,就可以完成整体文字识别的功能,以下为完整的代码,可直接复制使用:

复制代码
import { image } from '@kit.ImageKit';
import { fileIo } from '@kit.CoreFileKit';
import { objectDetection, visionBase } from '@kit.CoreVisionKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { textRecognition } from '@kit.CoreVisionKit'

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

  async aboutToAppear(): Promise<void> {
    const initResult = await textRecognition.init();
  }
  openPicture(): Promise<string> {
    return new Promise<string>((resolve) => {
      let photoPicker: photoAccessHelper.PhotoViewPicker = new photoAccessHelper.PhotoViewPicker();
      photoPicker.select({
        MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE,
        maxSelectNumber: 1
      }).then((res: photoAccessHelper.PhotoSelectResult) => {
        resolve(res.photoUris[0]);
      }).catch((err: BusinessError) => {
        resolve('');
      })
    })
  }

  async selectImage() {
    let uri = await this.openPicture();
    console.log("xwq:::"+JSON.stringify(uri))
    setTimeout(
      async () => {
        let imageSource: image.ImageSource | undefined = undefined;
        let fileSource = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
        imageSource = image.createImageSource(fileSource.fd);
        this.chooseImage = await imageSource.createPixelMap();
    },100)

  }

  textRecogn() {
    // 调用文本识别接口
    if (!this.chooseImage) {
      return
    }
    //VisionInfo为待OCR检测识别的入参项,目前仅支持PixelMap类型的视觉信息。
    let visionInfo: textRecognition.VisionInfo = {
      pixelMap: this.chooseImage
    };
    //配置通用文本识别的配置项TextRecognitionConfiguration,用于配置是否支持朝向检测
    let textConfiguration: textRecognition.TextRecognitionConfiguration = {
      isDirectionDetectionSupported: false
    };
    textRecognition.recognizeText(visionInfo, textConfiguration)
      .then((data: textRecognition.TextRecognitionResult) => {
        // 将结果更新到Text中显示
        this.dataValues = data.value;
      })
      .catch((error: BusinessError) => {
        this.dataValues = `Error: ${error.message}`;
      });
  }

  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 () => {
          this.textRecogn()
        })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

欢迎大家跟我一起学习鸿蒙开发知识,加入我的班级,参与HarmonyOS赋能资源丰富度建设(第四期),获得HarmonyOS应用开发者认证 每月对前200名学员进行激励,活动期间共计激励1000名

华为开发者学堂

相关推荐
人工智能训练4 小时前
【极速部署】Ubuntu24.04+CUDA13.0 玩转 VLLM 0.15.0:预编译 Wheel 包 GPU 版安装全攻略
运维·前端·人工智能·python·ai编程·cuda·vllm
源于花海5 小时前
迁移学习相关的期刊和会议
人工智能·机器学习·迁移学习·期刊会议
2601_949593655 小时前
基础入门 React Native 鸿蒙跨平台开发:模拟智能音响
react native·react.js·harmonyos
xiaoqi9225 小时前
React Native鸿蒙跨平台如何进行狗狗领养中心,实现基于唯一标识的事件透传方式是移动端列表开发的通用规范
javascript·react native·react.js·ecmascript·harmonyos
jin1233226 小时前
React Native鸿蒙跨平台剧本杀组队消息与快捷入口组件,包含消息列表展示、快捷入口管理、快捷操作触发和消息详情预览四大核心功能
javascript·react native·react.js·ecmascript·harmonyos
DisonTangor6 小时前
DeepSeek-OCR 2: 视觉因果流
人工智能·开源·aigc·ocr·deepseek
薛定谔的猫19826 小时前
二十一、基于 Hugging Face Transformers 实现中文情感分析情感分析
人工智能·自然语言处理·大模型 训练 调优
发哥来了6 小时前
《AI视频生成技术原理剖析及金管道·图生视频的应用实践》
人工智能
数智联AI团队7 小时前
AI搜索引领开源大模型新浪潮,技术创新重塑信息检索未来格局
人工智能·开源
不懒不懒7 小时前
【线性 VS 逻辑回归:一篇讲透两种核心回归模型】
人工智能·机器学习