当前位置: 首页 > news >正文

使用 Kotlin 结合 Tesseract OCR 识别验证码

更多内容访问ttocr.com或联系1436423940

  1. 环境准备
    1.1 安装 Kotlin

如果尚未安装 Kotlin,可以通过 Kotlin 官方网站
下载,或者使用 SDKMAN 安装:

sdk install kotlin

检查安装是否成功:

kotlin -version

1.2 安装 Tesseract OCR
Windows

从 Tesseract GitHub
下载并安装。

Linux(Ubuntu)
sudo apt install tesseract-ocr

macOS(Homebrew)
brew install tesseract

安装完成后,检查是否成功安装:

tesseract --version

1.3 创建 Kotlin 项目

使用 Gradle 创建 Kotlin 项目:

mkdir captcha_reader
cd captcha_reader
gradle init --type basic

然后,在 build.gradle.kts 添加 Tesseract 依赖:

dependencies {
implementation("com.rmtheis:tess-two:9.1.0") // Android 使用
}

  1. 代码实现

在 src/main/kotlin/Main.kt 文件中写入以下代码:

import java.io.File
import net.sourceforge.tess4j.Tesseract
import net.sourceforge.tess4j.TesseractException

fun main() {
val imagePath = "captcha.png" // 替换为你的验证码图片路径
val tesseract = Tesseract()

// 设置 Tesseract 语言和数据路径
tesseract.setDatapath("/usr/share/tesseract-ocr/4.00/tessdata") // 修改为你的 Tesseract 训练数据路径
tesseract.setLanguage("eng")try {val result = tesseract.doOCR(File(imagePath))println("识别出的验证码: $result")
} catch (e: TesseractException) {println("OCR 识别失败: ${e.message}")
}

}

  1. 代码解析
    3.1 读取图片并调用 Tesseract
    val tesseract = Tesseract()
    tesseract.setDatapath("/usr/share/tesseract-ocr/4.00/tessdata")
    tesseract.setLanguage("eng")

setDatapath 指定 Tesseract 数据文件路径

setLanguage("eng") 设置 OCR 识别语言

3.2 进行 OCR 识别
val result = tesseract.doOCR(File(imagePath))

读取 captcha.png 并使用 Tesseract 进行 OCR 解析

  1. 运行程序

确保 captcha.png 存在于项目目录下,然后运行:

gradle run

示例输出:

识别出的验证码: X7G9H

  1. 提高 OCR 识别率
    5.1 使用不同的 Tesseract PSM 模式
    tesseract.setTessVariable("tessedit_pageseg_mode", "6")

--psm 6 适用于单行验证码,提高识别率

5.2 限制识别字符集
tesseract.setTessVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")

限制 Tesseract 只识别数字和大写字母

http://www.jsqmd.com/news/27966/

相关文章:

  • 使用 Swift 结合 Tesseract OCR 解析验证码
  • 自律这一块儿
  • (Mutual) correlated agreement
  • AI元人文随想:当内心黑箱遇见技术黑箱
  • 如何基于区块链底层技术逻辑,反向用于 差别 AI生成与非AI生成内容
  • 2025.10.31总结
  • 电动车 NFC 学卡 All In One
  • 基于Qlearning强化学习的电梯群控系统高效调度策略matlab仿真
  • 基于Qlearning强化学习的Cart-Pole推车杆平衡控制系统matlab仿真
  • 绿源电动车 NFC 学卡 All In One
  • 洛谷 P8867 建造军营
  • 代码大全2阅读感悟2
  • 代码大全2阅读感悟3
  • 【Python】某站音视频爬取(转载)
  • 代码大全2阅读感悟
  • RT-Thread之消息队列使用示例
  • STM32之GPIO输出
  • 神秘数据结构手法之区间 LIS
  • 软考九
  • [该退役了]
  • 逆向基础--汇编语言介绍(003)
  • 文档抽取技术的实现原理及其在法律行业的应用价值分析
  • 【算法导论】2分治法
  • c++写得多不如写得少,同样的逻辑写的多报错逆天
  • 整理数学数据结构
  • viewerjs+vue3 using typescript
  • 题解:B4207 [常州市赛 2021] 战士
  • 最小二乘问题详解7:正则化最小二乘
  • 什么是重组蛋白?
  • 代码大全2{3}