使用 Kotlin 和 Tesseract OCR 实现验证码识别

一、背景简介
验证码识别在自动化测试、数据抓取和爬虫开发中至关重要。借助 Kotlin 的简洁语法和 Tesseract OCR 的强大文本识别能力,我们可以快速实现验证码的自动识别。

二、环境准备
2.1 安装 Tesseract OCR
Tesseract 是一个开源的 OCR 引擎,可以轻松集成到 Kotlin 中。

Ubuntu/Debian

sudo apt up更多内容访问ttocr.com或联系1436423940date
sudo apt install tesseract-ocr libtesseract-dev
MacOS (使用 Homebrew)

brew install tesseract
Windows
从 GitHub Releases 下载并安装适合的版本。

验证安装:

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

gradle init --type kotlin-application
2.3 添加依赖
在 build.gradle.kts 中添加以下依赖:

plugins {
kotlin("jvm") version "1.9.0"
application
}

repositories {
mavenCentral()
}

dependencies {
implementation("net.sourceforge.tess4j:tess4j:5.7.0")
}

application {
mainClass.set("CaptchaRecognizerKt")
}
三、代码实现
3.1 识别验证码的核心代码
在 src/main/kotlin/CaptchaRecognizer.kt 中编写以下代码:

import net.sourceforge.tess4j.Tesseract
import java.awt.Color
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO

fun preprocessImage(imagePath: String, outputPath: String): BufferedImage {
val image = ImageIO.read(File(imagePath))
val grayscaleImage = BufferedImage(image.width, image.height, BufferedImage.TYPE_BYTE_GRAY)

for (y in 0 until image.height) {
    for (x in 0 until image.width) {
        val color = Color(image.getRGB(x, y))
        val grayValue = (color.red * 0.3 + color.green * 0.59 + color.blue * 0.11).toInt()
        val binaryValue = if (grayValue > 128) 255 else 0
        grayscaleImage.setRGB(x, y, Color(binaryValue, binaryValue, binaryValue).rgb)
    }
}

ImageIO.write(grayscaleImage, "png", File(outputPath))
return grayscaleImage

}

fun recognizeCaptcha(imagePath: String): String {
val tesseract = Tesseract()
tesseract.setDatapath("/usr/share/tesseract-ocr/4.00/tessdata") // 根据实际路径调整
tesseract.setLanguage("eng")
tesseract.setTessVariable("tessedit_char_whitelist", "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

return try {
    tesseract.doOCR(File(imagePath))
} catch (e: Exception) {
    e.printStackTrace()
    "识别失败"
}

}

fun main() {
val imagePath = "captcha.png"
val processedPath = "processed_captcha.png"

println("正在进行图像预处理...")
preprocessImage(imagePath, processedPath)

println("开始识别验证码...")
val result = recognizeCaptcha(processedPath)
println("识别结果:$result")

}
四、运行程序
编译和运行

./gradlew run
输出示例

正在进行图像预处理...
开始识别验证码...
识别结果:7GHT9
五、效果优化
5.1 设置 PSM 模式
根据验证码特性调整页面分割模式:

tesseract.setTessVariable("tessedit_pageseg_mode", "6")
5.2 语言和字符集优化
如果验证码包含特殊字符或仅包含数字,可以设置白名单:

tesseract.setTessVariable("tessedit_char_whitelist", "0123456789")
六、性能分析
高效性:Kotlin 运行速度快,内存管理优秀。

准确性:通过二值化和字符白名单设置,有效提升识别率。

跨平台支持:适用于 Linux、MacOS 和 Windows。

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