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

  1. 环境准备
    1.1 安装 Kotlin
    如果尚未安装 Kotlin,可以通过 Kotlin 官方网站 下载,或者使用 SDKMAN 安装:

bash

sdk install kotlin
检查安装是否成功:

bash

kotlin -version
1.2 安装 Tesseract OCR
Windows
从 Tesseract GitHub 下载并安装。

Linux(Ubuntu)
bash

sudo apt install tesseract-ocr
macOS(Homebrew)
bash

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

bash

tesseract --version
1.3 创建 Kotlin 项目
使用 Gradle 创建 Kotlin 项目:

bash

mkdir captcha_reader
cd captcha_reader
gradle init --type basic
然后,在 build.gradle.kts 添加 Tesseract 依赖:

kotlin

dependencies {
implementation("com.rmtheis:tess-two:9.1.0") // Android 使用
}
2. 代码实现
在 src/main/kotlin/Main.kt 文件中写入以下代码:

kotlin

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}")
}

}
3. 代码解析
3.1 读取图片并调用 Tesseract
kotlin

val tesseract = Tesseract()
tesseract.setDatapath("/usr/share/tesseract-ocr/4.00/tessdata")
tesseract.setLanguage("eng")
setDatapath 指定 Tesseract 数据文件路径
setLanguage("eng") 设置 OCR 识别语言
3.2 进行 OCR 识别
kotlin

val result = tesseract.doOCR(File(imagePath))
读取 captcha.png 并使用 Tesseract 进行 OCR 解析
4. 运行程序
确保 captcha.png 存在于项目目录下,然后运行:

bash

gradle run
示例输出:

makefile

识别出的验证码: X7G9H
5. 提高 OCR 识别率
5.1 使用不同的 Tesseract PSM 模式
kotlin

tesseract.setTessVariable("tessedit_pageseg_mode", "6")
--psm 6 适用于单行验证码,提高识别率
5.2 限制识别字符集
kotlin
更多内容访问ttocr.com或联系1436423940
tesseract.setTessVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
限制 Tesseract 只识别数字和大写字母

posted @ 2025-03-15 18:22  ttocr、com  阅读(32)  评论(0)    收藏  举报