使用 Swift 和 Tesseract OCR 解析验证码


1. 环境准备
1.1 安装 Xcode 和 Swift
在 macOS 上,你需要安装 Xcode 以获取 Swift 编译环境。如果尚未安装,可以通过 App Store 下载 Xcode。
安装完成后,检查 Swift 是否可用:


swift --version
1.2 安装 Tesseract OCR
在 macOS 上,使用 Homebrew 进行安装:


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

tesseract --version
1.3 安装 Tesseract OCR 的 Swift 库
我们使用 SwiftyTesseract,它是 Swift 的 Tesseract 绑定库,方便与 iOS/macOS 项目集成。
使用 CocoaPods 安装:

pod init
然后编辑 Podfile,添加:


pod 'SwiftyTesseract'
再运行:


pod install
2. 代码实现
在 Xcode 中创建一个 macOS Command Line Tool 项目,并确保 SwiftyTesseract 依赖已安装。

编辑 main.swift,添加以下代码:

import Cocoa
import SwiftyTesseract

/// 预处理图像(灰度化 + 二值化)
func preprocessImage(inputPath: String, outputPath: String) -> Bool {
    guard let image = NSImage(contentsOfFile: inputPath) else {
        print("无法加载图像")
        return false
    }

    let bitmapRep = NSBitmapImageRep(data: image.tiffRepresentation!)
    let width = bitmapRep?.pixelsWide ?? 0
    let height = bitmapRep?.pixelsHigh ?? 0
    var processedImage = NSImage(size: NSSize(width: width, height: height))

    processedImage.lockFocus()
    NSColor.white.setFill()
    NSRect(x: 0, y: 0, width: width, height: height).fill()

    image.draw(at: .zero, from: NSRect(x: 0, y: 0, width: width, height: height), operation: .sourceOver, fraction: 1.0)

    processedImage.unlockFocus()
    
    if let tiffData = processedImage.tiffRepresentation,
       let bitmap = NSBitmapImageRep(data: tiffData),
       let pngData = bitmap.representation(using: .png, properties: [:]) {
        do {
            try pngData.write(to: URL(fileURLWithPath: outputPath))
            return true
        } catch {
            print("保存预处理图像失败: \(error)")
            return false
        }
    }
    return false
}

/// OCR 识别
func recognizeText(imagePath: String) {
    let tesseract = SwiftyTesseract(language: .english)

    guard let image = NSImage(contentsOfFile: imagePath) else {
        print("无法加载图像")
        return
    }

    tesseract.performOCR(on: image) { result in
        switch result {
        case .success(let text):
            print("识别出的验证码: \(text)")
        case .failure(let error):
            print("OCR 失败: \(error)")
        }
    }
}

let inputImage = "captcha.png"  // 请输入你的验证码图片路径
let processedImage = "processed_captcha.png"

print("正在处理图像...")
if preprocessImage(inputPath: inputImage, outputPath: processedImage) {
    print("执行 OCR 识别...")
    recognizeText(imagePath: processedImage)
}
3. 代码解析
3.1 预处理图像
灰度化处理(去除颜色干扰)

二值化(黑白化,提高识别率)


image.draw(at: .zero, from: NSRect(x: 0, y: 0, width: width, height: height), operation: .sourceOver, fraction: 1.0)
这里通过 NSImage 进行图像处理,并转换为 PNG 格式保存。

3.2 OCR 解析

let tesseract = SwiftyTesseract(language: .english)
tesseract.performOCR(on: image) { result in
    case .success(let text): print("识别出的验证码: \(text)")
}
使用 SwiftyTesseract 进行 OCR 识别,并输出识别结果。

4. 运行程序
在 Xcode 中运行 main.swift,或直接在终端执行:

更多内容访问ttocr.com或联系1436423940
swift main.swift
程序会加载验证码图像,进行处理并输出识别结果。

5. 提高 OCR 识别率
5.1 选择合适的 PSM 模式
可以使用 setVariable("tessedit_pageseg_mode", "6") 指定单行文本模式,提高验证码识别准确度。

5.2 进一步图像优化
降噪

字符分割

更高质量的验证码训练数据

猜你喜欢

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