使用 Swift + Tesseract OCR 解析验证码


1. 环境准备
1.1 安装 Swift
macOS 自带 Swift,可以在终端中检查是否已安装:


swift --version
如果 Swift 未安装,可通过 Xcode 或 brew 进行安装:

brew install swift
1.2 安装 Tesseract OCR
在 macOS 上,使用 Homebrew 安装:


brew install tesseract
安装完成后,验证 Tesseract 是否可用:


tesseract --version
1.3 创建 Swift 项目

mkdir CaptchaOCR
cd CaptchaOCR
swift package init --type executable
1.4 添加 Tesseract 依赖
编辑 Package.swift,添加 SwiftyTesseract:


// swift-tools-version:5.7
import PackageDescription

let package = Package(
    name: "CaptchaOCR",
    dependencies: [
        .package(url: "https://github.com/SwiftyTesseract/SwiftyTesseract.git", from: "2.0.0")
    ],
    targets: [
        .target(
            name: "CaptchaOCR",
            dependencies: ["SwiftyTesseract"]
        )
    ]
)
然后运行:

swift package update
2. 代码实现
在 Sources/CaptchaOCR/main.swift 中编写如下代码:


import Foundation
import SwiftyTesseract
import AppKit

/// 进行 OCR 识别
func recognizeCaptcha(imagePath: String) {
    let tesseract = SwiftyTesseract(languages: [.english])
    
    // 读取验证码图像
    guard let image = NSImage(contentsOfFile: imagePath) else {
        print("无法加载图片")
        return
    }
    
    // 进行 OCR 解析
    tesseract.performOCR(on: image) { result in
        switch result {
        case .success(let text):
            print("识别出的验证码: \(text)")
        case .failure(let error):
            print("OCR 识别失败: \(error)")
        }
    }
}

// 运行 OCR 识别
let imagePath = "captcha.png" // 你的验证码图片路径
recognizeCaptcha(imagePath: imagePath)
3. 代码解析
3.1 加载 Tesseract

let tesseract = SwiftyTesseract(languages: [.english])
这里使用 SwiftyTesseract 作为 OCR 引擎,加载 eng 语言模型。

3.2 读取图像

guard let image = NSImage(contentsOfFile: imagePath) else {
    print("无法加载图片")
    return
}
NSImage(contentsOfFile:) 读取本地验证码图片。

3.3 OCR 解析

tesseract.performOCR(on: image) { result in
    switch result {
    case .success(let text):
        print("识别出的验证码: \(text)")
    case .failure(let error):
        print("OCR 识别失败: \(error)")
    }
}
使用 performOCR 进行验证码解析,返回识别的文本。

4. 运行 OCR 识别
编译并运行:

swift run
终端将输出识别的验证码内容。

5. 提高 OCR 识别率
5.1 预处理验证码
可以使用 CoreImage 进行二值化处理,提高识别率:


import CoreImage

func preprocessImage(image: NSImage) -> NSImage? {
    let ciImage = CIImage(data: image.tiffRepresentation!)
    let filter = CIFilter(name: "CIColorControls")!
    filter.setValue(ciImage, forKey: kCIInputImageKey)
    filter.setValue(0.0, forKey: kCIInputSaturationKey) // 转灰度
    filter.setValue(2.0, forKey: kCIInputContrastKey)   // 增强对比度

    let context = CIContext()
    if let output = filter.outputImage,
       let cgImage = context.createCGImage(output, from: output.extent) {
        return NSImage(cgImage: cgImage, size: image.size)
    }
    return nil
}
5.2 设置合适的 PSM 模式
Tesseract 的页面分割模式(PSM)可以提高验证码识别率:

tesseract.setVariable(.tesseditPagesegMode, "6")
PSM 6 适用于单行验证码解析。

猜你喜欢

转载自blog.csdn.net/asfdsgdf/article/details/146483766
今日推荐