用 Swift 和 Tesseract OCR 解析验证码

  1. 环境准备
    1.1 安装 Xcode 和 Swift
    首先,确保你已经安装了 Xcode,并且 Swift 可用。你可以在终端中运行以下命令检查 Swift 版本:

bash

swift --version
1.2 安装 Tesseract OCR
在 macOS 上,你可以使用 Homebrew 来安装 Tesseract:

bash

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

bash

tesseract --version
1.3 创建 Swift 项目
你可以使用 Xcode 创建一个 macOS 命令行工具项目,或者直接在 Swift 脚本中运行代码。

  1. 代码实现
    在 ocr.swift 文件中添加以下代码:

swift

import Foundation
import Vision
import AppKit

/// 读取验证码图片
func loadCaptchaImage(imagePath: String) -> NSImage? {
return NSImage(contentsOfFile: imagePath)
}

/// 预处理图像(灰度化 + 二值化)
func preprocessImage(image: NSImage) -> NSImage? {
guard let tiffData = image.tiffRepresentation,
let bitmap = NSBitmapImageRep(data: tiffData) else { return nil }

let width = bitmap.pixelsWide
let height = bitmap.pixelsHigh

let processedBitmap = NSBitmapImageRep(bitmapDataPlanes: nil,
                                       pixelsWide: width,
                                       pixelsHigh: height,
                                       bitsPerSample: 8,
                                       samplesPerPixel: 1,
                                       hasAlpha: false,
                                       isPlanar: false,
                                       colorSpaceName: .deviceGray,
                                       bytesPerRow: 0,
                                       bitsPerPixel: 0)

for x in 0..<width {
    for y in 0..<height {
        let color = bitmap.colorAt(x: x, y: y)
        let grayscale = color?.whiteComponent ?? 0
        let newColor = grayscale > 0.5 ? NSColor.white : NSColor.black
        processedBitmap?.setColor(newColor, atX: x, y: y)
    }
}

return processedBitmap?.nsImage

}

/// OCR 识别
func recognizeText(imagePath: String) -> String {
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/local/bin/tesseract") // Tesseract 路径
process.arguments = [imagePath, "stdout"]

let pipe = Pipe()
process.standardOutput = pipe

do {
    try process.run()
} catch {
    print("无法运行 Tesseract: \(error)")
    return ""
}

let outputData = pipe.fileHandleForReading.readDataToEndOfFile()
let outputText = String(data: outputData, encoding: .utf8) ?? ""

return outputText.trimmingCharacters(in: .whitespacesAndNewlines)

}

let imagePath = "captcha.png" // 请替换为你的验证码图片路径

print("加载验证码图片...")
if let img = loadCaptchaImage(imagePath: imagePath) {
print("预处理图像...")
if let processedImg = preprocessImage(image: img) {
print("执行 OCR 识别...")
let text = recognizeText(imagePath: imagePath)
print("识别出的验证码: (text)")
} else {
print("图像处理失败")
}
} else {
print("无法加载图像")
}
3. 代码解析
3.1 读取和预处理图像
swift

let img = loadCaptchaImage(imagePath: imagePath)
NSImage 读取图片
转换为灰度
二值化处理,增强字符对比度
3.2 运行 Tesseract OCR
swift

let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/local/bin/tesseract")
process.arguments = [imagePath, "stdout"]
通过 Process() 在 macOS 终端运行 Tesseract
解析图片文本
4. 运行程序
执行:

bash

swift ocr.swift
程序会处理验证码图片并输出识别结果。

  1. 提高识别准确率
    5.1 调整 Tesseract PSM 模式
    使用 PSM 7 以适应验证码:

swift

process.arguments = [imagePath, "stdout", "--psm", "7"]
5.2 进一步图像优化
降噪处理
字符分割

posted @ 2025-03-21 23:47  ttocr、com  阅读(10)  评论(0)    收藏  举报