鸿蒙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)
  }
}
相关推荐
九流下半2 小时前
window wsl 环境下编译openharmony,HarmonyOS 三方库 FFmpeg
windows·ffmpeg·harmonyos·编译·openharmony·三方库
shayu8nian4 小时前
Hap包引用的Hsp报签名错误怎么解决
华为·harmonyos
shayu8nian9 小时前
鸿蒙的NDK开发初级入门篇
华为·harmonyos
万少20 小时前
03-自然壁纸实战教程-项目结构介绍
harmonyos
前端世界1 天前
鸿蒙系统安全机制全解:安全启动 + 沙箱 + 动态权限实战落地指南
android·安全·harmonyos
长弓三石1 天前
鸿蒙网络编程系列57-仓颉版固定包头可变包体解决TCP粘包问题
网络·tcp/ip·harmonyos
zhanshuo1 天前
HarmonyOS 隐私安全机制实战:动态权限、沙箱隔离与分布式授权
harmonyos
zhanshuo1 天前
鸿蒙系统防黑秘籍:如何彻底防止恶意应用窃取用户数据?
harmonyos
财经三剑客1 天前
鸿蒙智行6月交付新车52747辆 单日交付量3651辆
华为·harmonyos