HarmonyOS 鸿蒙Next图片文字识别OCR功能如何实现?文字提取开发指南

HarmonyOS 鸿蒙Next图片文字识别OCR功能如何实现?文字提取开发指南 HarmonyOS 5.0,DevEco Studio 5.0

  • 需要从图片中识别并提取文字内容
  • 不清楚如何调用系统的OCR识别API
  • 希望了解完整的图片文字识别流程

希望了解HarmonyOS OCR文字识别的完整实现方案,包括图片选择、识别调用和结果处理

3 回复

解决方案

1. 完整实现代码

import { textRecognition } from '@kit.CoreVisionKit'
import { picker } from '@kit.CoreFileKit'
import { image } from '@kit.ImageKit'
import { BusinessError } from '@kit.BasicServicesKit'
import { fileIo } from '@kit.CoreFileKit'

@Entry
@Component
struct OCRPage {
  @State recognizedText: string = ''
  @State selectedImage: string = ''
  @State isRecognizing: boolean = false
  @State statusText: string = '请选择图片'

  // 选择图片
  async selectImage(): Promise<void> {
    try {
      const photoPicker = new picker.PhotoViewPicker()
      const result = await photoPicker.select({
        MIMEType: picker.PhotoViewMIMETypes.IMAGE_TYPE,
        maxSelectNumber: 1
      })
     
      if (result.photoUris.length > 0) {
        this.selectedImage = result.photoUris[0]
        this.statusText = '图片已选择,点击识别'
        this.recognizedText = ''
      }
    } catch (err) {
      console.error('选择图片失败:', err)
    }
  }

  // 执行OCR识别
  async recognizeText(): Promise<void> {
    if (!this.selectedImage) {
      this.statusText = '请先选择图片'
      return
    }
   
    this.isRecognizing = true
    this.statusText = '正在识别...'
   
    try {
      // 读取图片文件
      const file = fileIo.openSync(this.selectedImage, fileIo.OpenMode.READ_ONLY)
      const imageSource = image.createImageSource(file.fd)
      const pixelMap = await imageSource.createPixelMap()
      fileIo.closeSync(file)
     
      // 配置识别参数
      const visionInfo: textRecognition.VisionInfo = {
        pixelMap: pixelMap
      }
     
      const textConfiguration: textRecognition.TextRecognitionConfiguration = {
        isDirectionDetectionSupported: true  // 支持方向检测
      }
     
      // 执行识别
      const result = await textRecognition.recognizeText(visionInfo, textConfiguration)
     
      // 处理识别结果
      if (result && result.value) {
        this.recognizedText = result.value
        this.statusText = '识别完成'
      } else {
        this.recognizedText = '未识别到文字'
        this.statusText = '识别完成(无结果)'
      }
     
      // 释放资源
      pixelMap.release()
     
    } catch (err) {
      const error = err as BusinessError
      console.error(`OCR识别失败: ${error.code} - ${error.message}`)
      this.statusText = '识别失败'
      this.recognizedText = ''
    } finally {
      this.isRecognizing = false
    }
  }

  build() {
    Column({ space: 16 }) {
      // 状态显示
      Text(this.statusText)
        .fontSize(14)
        .fontColor($r('app.color.text_secondary'))
     
      // 图片预览
      if (this.selectedImage) {
        Image(this.selectedImage)
          .width('100%')
          .height(200)
          .objectFit(ImageFit.Contain)
          .backgroundColor($r('app.color.surface'))
          .borderRadius(12)
      } else {
        Column() {
          Image($r('app.media.ic_image'))
            .width(48)
            .height(48)
            .fillColor($r('app.color.text_secondary'))
          Text('点击选择图片')
            .fontSize(14)
            .fontColor($r('app.color.text_secondary'))
            .margin({ top: 8 })
        }
        .width('100%')
        .height(200)
        .backgroundColor($r('app.color.surface'))
        .borderRadius(12)
        .justifyContent(FlexAlign.Center)
        .onClick(() => this.selectImage())
      }
     
      // 操作按钮
      Row({ space: 12 }) {
        Button('选择图片')
          .layoutWeight(1)
          .height(44)
          .backgroundColor($r('app.color.surface'))
          .fontColor($r('app.color.primary'))
          .onClick(() => this.selectImage())
       
        Button(this.isRecognizing ? '识别中...' : '开始识别')
          .layoutWeight(1)
          .height(44)
          .backgroundColor('#36e27b')
          .enabled(!this.isRecognizing && !!this.selectedImage)
          .onClick(() => this.recognizeText())
      }
      .width('100%')
     
      // 识别结果
      Column() {
        Text('识别结果')
          .fontSize(16)
          .fontWeight(FontWeight.Bold)
          .fontColor($r('app.color.text_primary'))
          .width('100%')
       
        Scroll() {
          Text(this.recognizedText || '识别结果将显示在这里')
            .fontSize(14)
            .fontColor($r('app.color.text_primary'))
            .width('100%')
        }
        .layoutWeight(1)
        .margin({ top: 12 })
      }
      .layoutWeight(1)
      .padding(16)
      .backgroundColor($r('app.color.surface'))
      .borderRadius(12)
    }
    .width('100%')
    .height('100%')
    .padding(16)
    .backgroundColor($r('app.color.background'))
  }
}

2. 获取详细识别信息

// 获取每个文字块的详细信息
async recognizeTextWithDetails(): Promise<void> {
  // ... 前面的图片读取代码相同

  const result = await textRecognition.recognizeText(visionInfo, textConfiguration)

  if (result && result.textBlocks) {
    let fullText = ''
   
    result.textBlocks.forEach((block, blockIndex) => {
      console.info(`文字块 ${blockIndex}:`)
      console.info(`  内容: ${block.value}`)
      console.info(`  置信度: ${block.confidence}`)
      console.info(`  边界框: ${JSON.stringify(block.boundingBox)}`)
     
      fullText += block.value + '\n'
    })
   
    this.recognizedText = fullText
  }
}

3. 识别配置参数

const textConfiguration: textRecognition.TextRecognitionConfiguration = {
  isDirectionDetectionSupported: true,  // 支持文字方向检测
}

4. 从相机拍照识别

import { camera } from '@kit.CameraKit'

// 拍照后识别
async captureAndRecognize(): Promise<void> {
  // 使用相机拍照获取图片
  const cameraPicker = new picker.PhotoViewPicker()
  // ... 相机拍照逻辑

  // 然后调用 recognizeText 进行识别
}

更多关于HarmonyOS 鸿蒙Next图片文字识别OCR功能如何实现?文字提取开发指南的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


鸿蒙Next图片文字识别OCR功能通过ML Kit的文本识别能力实现。开发者需导入@ohos.ml.text接口,使用TextRecognition类进行识别。主要步骤包括:创建TextRecognition实例,配置识别参数,调用detect方法传入图片数据,获取识别结果。支持静态图片和相机流识别,可提取文字内容及位置信息。需在module.json5中声明ohos.permission.READ_MEDIA权限。

在HarmonyOS Next中,图片文字识别(OCR)功能主要通过@ohos.ocr系统能力实现。以下是基于你当前环境(HarmonyOS 5.0, DevEco Studio 5.0)的核心实现步骤:

1. 权限与模型准备

  • 权限声明:在module.json5文件中请求必要权限。
    "requestPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      },
      {
        "name": "ohos.permission.READ_IMAGEVIDEO"
      }
    ]
    
  • 模型部署:确保设备上已安装并部署了OCR识别模型。这通常通过应用首次启动时,使用@ohos.ai.engine相关API下载和管理模型文件来完成。

2. 核心开发流程

整个流程可分为图片获取、引擎创建、识别执行和结果处理四步。

第一步:获取图片 你可以使用系统PhotoViewPicker选择图片,或使用相机API拍摄。获取到的图片需转换为PixelMap对象,这是OCR引擎所需的输入格式。

import { photoAccessHelper } from '@kit.MediaLibraryKit';
// ... 使用选择器或相机获取图片URI
let pixelMap: image.PixelMap | undefined = await image.createPixelMapFromImageSource(/* 图片源 */);

第二步:创建OCR识别引擎 导入OCR模块,并创建文字识别引擎实例。

import { ocr } from '@kit.OcrKit';
import { BusinessError } from '@kit.BasicServicesKit';

let ocrInstance: ocr.OCR | undefined = undefined;
try {
  // 创建OCR引擎,可指定识别语言等配置
  ocrInstance = ocr.createOCR({ language: 'en' });
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`OCR引擎创建失败,错误码:${err.code}, 消息:${err.message}`);
}

第三步:执行文字识别 调用引擎的detect方法,传入PixelMap进行识别。

if (ocrInstance && pixelMap) {
  try {
    const textBlocks: ocr.TextBlock[] = await ocrInstance.detect(pixelMap);
    // 处理识别结果 textBlocks
  } catch (error) {
    let err: BusinessError = error as BusinessError;
    console.error(`识别失败,错误码:${err.code}, 消息:${err.message}`);
  }
}

第四步:处理识别结果 识别成功返回TextBlock数组,每个对象包含识别出的文字块及其位置信息。

if (textBlocks && textBlocks.length > 0) {
  for (let block of textBlocks) {
    console.info(`识别出的文字:${block.text}`);
    console.info(`文字位置:${JSON.stringify(block.boundingBox)}`);
    // 可以将block.text拼接或按需使用
  }
}

3. 资源释放

识别完成后,务必释放引擎和图片资源。

if (ocrInstance) {
  ocrInstance.release();
}
if (pixelMap) {
  pixelMap.release();
}

关键注意事项

  • 模型依赖:首次使用需确保模型已下载至设备,否则识别会失败。模型管理代码需单独实现。
  • 性能与线程:识别是耗时操作,务必在非UI线程(如使用TaskPool)中调用detect方法,避免阻塞主线程。
  • 输入图片质量:图片的清晰度、光照和角度会直接影响识别准确率。
  • 错误处理:必须对创建引擎、识别操作等步骤进行完整的try-catch异常捕获,并根据错误码进行相应处理。

这个流程提供了从图片到文字提取的基本路径。具体实现时,请参考HarmonyOS官方文档中@kit.OcrKit@kit.MediaLibraryKit@kit.ImageKit的详细API说明。

回到顶部