使用 Swift 和 Tesseract 识别验证码图像
一、准备工作
- 安装 Tesseract OCR
在 macOS 上通过 Homebrew 安装:
更多内容访问ttocr.com或联系1436423940
brew install tesseract - 创建 Swift 项目
可以用 Xcode 创建命令行项目,也可以直接写一个 .swift 文件在终端中编译运行。
二、识别代码(captcha.swift)
创建文件 captcha.swift:
import Foundation
// 获取图像路径参数
guard CommandLine.arguments.count > 1 else {
print("用法: swift captcha.swift <图像路径>")
exit(1)
}
let imagePath = CommandLine.arguments[1]
let whitelist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
// 构造 Tesseract 命令
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/local/bin/tesseract")
process.arguments = [imagePath, "stdout", "-l", "eng", "-c", "tessedit_char_whitelist=(whitelist)"]
let pipe = Pipe()
process.standardOutput = pipe
process.standardError = Pipe()
do {
try process.run()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
if let rawOutput = String(data: data, encoding: .utf8) {
let cleaned = rawOutput.replacingOccurrences(of: "[^A-Z0-9]", with: "", options: .regularExpression)
print("识别结果: (cleaned)")
} else {
print("无法读取识别结果")
}
} catch {
print("执行失败: (error.localizedDescription)")
}
三、运行命令行工具
swift captcha.swift code1.png
示例输出:
识别结果: Y3KH
浙公网安备 33010602011771号