You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求Android平台基于LeadTools实现特定区域实时OCR的代码片段

LeadTools Android 实时特定区域OCR实现代码片段

Absolutely! I’ve built real-time OCR features with LeadTools on Android before, so here’s a hands-on code example tailored to your needs—focused on camera preview and targeted region recognition.

前置准备

First, make sure you’ve got the LeadTools SDK set up properly in your Android project:

  • Add LeadTools dependencies to your module-level build.gradle
  • Request runtime permissions: CAMERA (required for camera preview)
  • Initialize your LeadTools license in your app’s entry point (like the Application class)

核心实现代码

1. 初始化LeadTools与OCR引擎

import android.app.Application
import com.leadtools.LTRuntime
import com.leadtools.ocr.OcrEngineManager

class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        // 替换为你的有效LeadTools许可证信息
        LTRuntime.setLicense(this, "YOUR_LICENSE_KEY", "YOUR_DEVELOPER_KEY")
        
        // 初始化OCR引擎环境
        OcrEngineManager.initialize(this)
    }
}

2. 相机预览与特定区域OCR处理(以TextureView为例)

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.Rect
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.leadtools.ocr.OcrEngine
import com.leadtools.ocr.OcrPage
import com.leadtools.ocr.OcrZone
import com.leadtools.ocr.OcrZoneCollection
import com.leadtools.ocr.OcrZoneType
import com.leadtools.RasterImage
import com.leadtools.camera.CameraPreview
import com.leadtools.camera.CameraPreviewListener

class RealTimeOcrActivity : AppCompatActivity(), CameraPreviewListener {
    private lateinit var cameraPreview: CameraPreview
    private lateinit var ocrEngine: OcrEngine
    private lateinit var resultTextView: TextView
    // 定义需要识别的特定区域(示例为屏幕中心矩形,可根据需求动态调整)
    private val targetRecognitionRegion = Rect(400, 600, 1200, 900) // 左、上、右、下坐标

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_real_time_ocr)
        
        cameraPreview = findViewById(R.id.camera_preview)
        resultTextView = findViewById(R.id.tv_ocr_result)
        
        // 初始化OCR引擎
        ocrEngine = OcrEngineManager.createEngine()
        ocrEngine.startup(null, null, null, null)
        
        // 检查并申请相机权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), 1001)
        } else {
            startCameraPreview()
        }
    }

    private fun startCameraPreview() {
        cameraPreview.setPreviewListener(this)
        cameraPreview.startPreview()
    }

    override fun onPreviewFrame(frame: ByteArray, width: Int, height: Int, format: Int) {
        // 将相机帧转换为LeadTools可处理的RasterImage
        val rasterImage = RasterImage.create(width, height, 24, 96, null)
        rasterImage.setData(frame, 0, width * 3, com.leadtools.RasterImageFormat.BGR24)
        
        // 裁剪出目标识别区域的图像
        val croppedImage = rasterImage.crop(
            targetRecognitionRegion.left,
            targetRecognitionRegion.top,
            targetRecognitionRegion.width(),
            targetRecognitionRegion.height()
        )
        
        // 执行OCR识别并更新UI
        runOnUiThread {
            try {
                val ocrPage = ocrEngine.createPage(croppedImage, false)
                // 手动设置识别区域为文本类型(也可让引擎自动检测)
                val zones = OcrZoneCollection()
                val textZone = OcrZone().apply {
                    bounds = com.leadtools.Rect(0, 0, croppedImage.width, croppedImage.height)
                    zoneType = OcrZoneType.TEXT
                }
                zones.add(textZone)
                ocrPage.zones = zones
                
                ocrPage.recognize(null)
                resultTextView.text = "识别结果: ${ocrPage.text}"
            } catch (e: Exception) {
                resultTextView.text = "识别失败: ${e.message}"
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1001 && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            startCameraPreview()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // 释放资源,避免内存泄漏
        cameraPreview.stopPreview()
        ocrEngine.shutdown()
    }
}

关键优化与注意事项

  • 许可证有效性: 必须替换代码中的YOUR_LICENSE_KEY和YOUR_DEVELOPER_KEY为你的有效LeadTools许可证,否则OCR功能无法正常运行。
  • 动态区域适配: targetRecognitionRegion的坐标建议基于屏幕尺寸动态计算,避免固定坐标导致的适配问题。
  • 性能优化: 实时OCR对资源消耗较大,建议:
    • 降低相机预览分辨率(比如设置为720p)
    • 增加识别间隔(比如每500ms处理一次帧,避免连续识别卡顿)
    • 缩小目标识别区域的范围
  • 错误处理: 示例仅做了基础异常捕获,实际项目中可扩展处理OCR引擎启动失败、相机帧转换失败等场景。

内容的提问来源于stack exchange,提问作者Snake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:38:13