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


一、简介
验证码识别是自动化测试和数据提取中的常见挑战。使用 Swift 结合 Tesseract OCR 可以在 iOS 或 macOS 应用中进行验证码自动识别。本文将介绍如何使用 Swift 和 Tesseract OCR 实现验证码识别。
更多内容访问ttocr.com或联系1436423940
二、环境准备
2.1 安装 Tesseract OCR
macOS 上安装 Tesseract: 使用 Homebrew 安装:

brew install tesseract
验证安装:

tesseract --version
2.2 安装 SwiftOCR
SwiftOCR 是一个基于 Swift 的开源 OCR 库,可以与 Tesseract 结合使用。
使用 Swift Package Manager 安装: 在项目的 Package.swift 中添加依赖:

dependencies: [
    .package(url: "https://github.com/garnele007/SwiftOCR", from: "1.0.0")
]
三、代码实现
3.1 代码结构
图像预处理

验证码识别

识别结果输出

3.2 Swift 代码示例
创建文件 CaptchaOCR.swift:

import Foundation
import SwiftOCR
import Vision
import AppKit

func preprocessImage(imagePath: String) -> NSImage? {
    guard let image = NSImage(contentsOfFile: imagePath) else {
        print("无法加载图像")
        return nil
    }

    let processedImage = NSImage(size: image.size)
    processedImage.lockFocus()

    let rect = NSRect(origin: .zero, size: image.size)
    image.draw(in: rect, from: rect, operation: .sourceOver, fraction: 1.0)

    // 灰度化处理
    let context = NSGraphicsContext.current?.cgContext
    context?.setFillColor(NSColor.white.cgColor)
    context?.fill(rect)
    context?.setBlendMode(.darken)
    context?.draw(image.cgImage(forProposedRect: nil, context: nil, hints: nil)!, in: rect)

    processedImage.unlockFocus()
    return processedImage
}

func recognizeCaptcha(imagePath: String) {
    guard let processedImage = preprocessImage(imagePath: imagePath) else {
        print("预处理失败")
        return
    }

    let swiftOCRInstance = SwiftOCR()

    swiftOCRInstance.recognize(processedImage) { recognizedString in
        print("识别出的验证码: \(recognizedString)")
    }
}

// 主程序
let captchaPath = "captcha.png"
recognizeCaptcha(imagePath: captchaPath)
四、运行程序
在终端运行:

swift run CaptchaOCR
示例输出:

识别出的验证码: H4J8K
五、效果优化
5.1 使用 Tesseract 自定义配置
调整 PSM 模式,假设验证码是单行文本:


let swiftOCRInstance = SwiftOCR()
swiftOCRInstance.tesseract.setVariable("tessedit_pageseg_mode", value: "6")
5.2 字符白名单
如果验证码只包含数字和大写字母:


swiftOCRInstance.tesseract.setVariable("tessedit_char_whitelist", value: "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
5.3 提高图像清晰度
通过调整对比度和亮度,提升识别率:


context?.setAlpha(0.8)
context?.setBlendMode(.multiply)
六、性能和效果分析
实时性强:Swift 结合 SwiftOCR,在 iOS 和 macOS 上运行速度较快。

识别准确:合理使用 Tesseract 参数能够显著提升识别效果。

兼容性好:适用于 macOS 和 iOS 平台。