鸿蒙Next(四)文字识别

鸿蒙系统提供了文字识别的能力,支持简体中文、英文、日文、韩文、繁体中文五种语言。

1、使用场景:

  • 文档数字化:扫描纸质文件(合同、书籍)转化为可编辑文本。
  • 实时翻译:识别图片中的外语文字并即时翻译(如菜单、路牌)。
  • 无障碍辅助:为视障用户提供语音播报图片中的文字内容。
  • 智能交互:结合AR应用提取现实场景中的文字(如商品标签、海报)。
  • 自动化处理:批量处理图片库中的文字信息,生成结构化数据。

2、优势:

a、离线高效
  • 无需联网即可运行,保障隐私安全(如敏感文件处理)。
  • 低功耗设计,CPU占用率低于同类框架30%。
b、高精度与灵活性
  • 采用深度学习模型,印刷体识别率超99%,手写体超95%。
  • 支持倾斜校正、透视变换,适应拍摄角度偏差。
c、开发者友好
  • 通过简单API调用(如textRecognition.detect() )即可集成。
  • 输出结果包含文字内容、坐标和置信度,便于二次开发(如表格重建)。

3、完整示例:

typescript 复制代码
import { textRecognition } 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';

@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();
    hilog.info(0x0000, 'OCRDemo', `OCR service initialization result:${initResult}`);
  }

  async aboutToDisappear(): Promise<void> {
    await textRecognition.release();
    hilog.info(0x0000, 'OCRDemo', 'OCR service released successfully');
  }

  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.textRecognitionTest();
        })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }

  private textRecognitionTest() {
    if (!this.chooseImage) {
      return;
    }
    // 调用文本识别接口
    let visionInfo: textRecognition.VisionInfo = {
      pixelMap: this.chooseImage
    };
    let textConfiguration: textRecognition.TextRecognitionConfiguration = {
      isDirectionDetectionSupported: false
    };
    textRecognition.recognizeText(visionInfo, textConfiguration)
      .then((data: textRecognition.TextRecognitionResult) => {
        // 识别成功,获取对应的结果
        let recognitionString = JSON.stringify(data);
        hilog.info(0x0000, 'OCRDemo', `Succeeded in recognizing text:${recognitionString}`);
        // 将结果更新到Text中显示
        this.dataValues = data.value;
      })
      .catch((error: BusinessError) => {
        hilog.error(0x0000, 'OCRDemo', `Failed to recognize text. Code: ${error.code}, message: ${error.message}`);
        this.dataValues = `Error: ${error.message}`;
      });
  }

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

  private openPhoto(): 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) => {
        hilog.error(0x0000, 'OCRDemo', `Failed to get photo image uri. Code:${err.code},message:${err.message}`);
        resolve('');
      })
    })
  }

  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)
  }
}
相关推荐
承渊政道1 小时前
Python IDLE鸿蒙PC适配全记录:用 ArkUI 重建编辑、运行、Shell 与基础调试闭环
python·microsoft·harmonyos·鸿蒙系统·pc端
User_芊芊君子1 小时前
RapidSVN 鸿蒙 PC 适配全记录:用 ArkUI 重建工作台,打通本地 SVN 操作闭环
华为·svn·harmonyos
lqj_本人1 小时前
WinMerge 鸿蒙 PC 适配全记录:以 Qt 重建桌面外壳,打通文件与文件夹差异闭环
qt·华为·harmonyos
不羁的木木1 小时前
给鸿蒙 App 增加唤起系统邮件发送能力 —— flutter_email_sender 的鸿蒙使用指南
flutter·华为·harmonyos
承渊政道1 小时前
PostgreSQL 鸿蒙 PC 适配全记录:从原生交叉编译到 HNP 数据库服务闭环
数据库·postgresql·harmonyos·鸿蒙系统·pc端
lqj_本人1 小时前
Tftpd64 鸿蒙 PC 适配全记录:用 Qt 重建一组可运行的 UDP 网络服务
qt·udp·harmonyos
User_芊芊君子1 小时前
RStudio 鸿蒙 PC 适配全记录:以 Qt 原生工作区承载嵌入式 R
qt·r语言·harmonyos
ai安歌2 小时前
Git Extensions 鸿蒙 PC 适配全记录:从 WinForms 客户端到 ArkUI 原生工作台
git·华为·harmonyos
●VON2 小时前
Flutter 鸿蒙插件适配实战:用 accurate_storage_info 0.1.1 查询总量、可用量与已用量
flutter·华为·harmonyos
网络豆2 小时前
Apache Maven 鸿蒙 PC 适配全记录:把 JVM 构建工具交付到 HiShell
maven·apache·harmonyos