鸿蒙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)
  }
}
相关推荐
鸿蒙布道师8 小时前
鸿蒙NEXT开发Base64工具类(ArkTs)
android·ios·华为·harmonyos·arkts·鸿蒙系统·huawei
The 旺9 小时前
《HarmonyOS Next开发实战:从零构建响应式Todo应用的基石》
华为·harmonyos
Industio_触觉智能10 小时前
鸿蒙北向开发OpenHarmony5.0 DevEco Studio开发工具安装与配置
harmonyos·鸿蒙系统·openharmony·开源鸿蒙·鸿蒙开发·嵌入式开发板
秋叶先生_14 小时前
HarmonyOS NEXT——【鸿蒙监听网络状态变化】
华为·harmonyos·鸿蒙
东林知识库15 小时前
鸿蒙NEXT小游戏开发:围住神经猫
harmonyos
zacksleo15 小时前
鸿蒙Flutter开发故事:不,你不需要鸿蒙化
flutter·harmonyos
别说我什么都不会17 小时前
OpenHarmony解读之设备认证:sts协议-客户端发起sts end请求
物联网·嵌入式·harmonyos
悬空八只脚20 小时前
React-Native开发鸿蒙NEXT-本地与沙盒加载bundle
harmonyos
鸿蒙布道师20 小时前
鸿蒙NEXT开发日志工具类(ArkTs)
android·ios·华为·harmonyos·arkts·鸿蒙系统·huawei
90后的晨仔20 小时前
HarmonyOS的页面生命周期 和 组件生命周期
harmonyos