- 环境准备
1.1 安装 Xcode 和 Swift
如果你在 macOS 上开发,建议使用 Xcode 进行 Swift 代码编写。安装 Xcode 后,可以使用以下命令检查 Swift 是否可用:
swift --version
1.2 安装 Tesseract OCR
在 macOS 上,可以通过 Homebrew 安装 Tesseract:
brew install tesseract
安装完成后,检查版本:
tesseract --version
1.3 创建 Swift 项目
你可以使用 Xcode 创建一个 macOS 命令行工具项目,或者使用终端:
mkdir SwiftOCR
cd SwiftOCR
swift package init --type executable
1.4 添加依赖
Swift 使用 Swift Package Manager (SPM) 来管理依赖。我们需要引入 SwiftyTesseract 库。
编辑 Package.swift,添加:
dependencies: [
.package(url: "https://github.com/SwiftyTesseract/SwiftyTesseract.git", from: "2.2.0")
],
targets: [
.target(
name: "SwiftOCR",
dependencies: ["SwiftyTesseract"]
)
]
然后运行:
swift build
2. 代码实现
在 Sources/SwiftOCR/main.swift 中编写如下代码:
import Foundation
import SwiftyTesseract
import AppKit
// 图像处理函数:加载验证码
func loadImage(from path: String) -> NSImage? {
return NSImage(contentsOfFile: path)
}
// OCR 识别函数
func recognizeCaptcha(imagePath: String) {
guard let image = loadImage(from: imagePath),
let tiffData = image.tiffRepresentation,
let bitmap = NSBitmapImageRep(data: tiffData) else {
print("无法加载图片")
return
}
let swiftyTesseract = SwiftyTesseract(language: .english)swiftyTesseract.performOCR(on: bitmap) { result inswitch result {case .success(let text):print("识别出的验证码: \(text.trimmingCharacters(in: .whitespacesAndNewlines))")case .failure(let error):print("OCR 失败: \(error.localizedDescription)")}
}
}
// 运行识别
let imagePath = "captcha.png" // 你的验证码图片路径
recognizeCaptcha(imagePath: imagePath)
3. 代码解析
3.1 加载验证码
func loadImage(from path: String) -> NSImage? {
return NSImage(contentsOfFile: path)
}
NSImage 是 macOS 的图像处理类,可用于加载图像。
3.2 OCR 识别
let swiftyTesseract = SwiftyTesseract(language: .english)
swiftyTesseract.performOCR(on: bitmap) { result in
switch result {
case .success(let text):
print("识别出的验证码: (text.trimmingCharacters(in: .whitespacesAndNewlines))")
case .failure(let error):
print("OCR 失败: (error.localizedDescription)")
}
}
使用 SwiftyTesseract 进行 OCR 识别。
解析 NSBitmapImageRep 类型的图像,并提取文本。
- 运行 OCR 识别
在终端运行:
swift run
终端将输出识别出的验证码文本。
- 提高 OCR 识别率
5.1 选择适合的 PSM 模式
Tesseract 提供了不同的页面分割模式(PSM),可以优化识别效果:
swiftyTesseract.setVariable("tessedit_pageseg_mode", value: "6")
其中:
6 适用于单行文本识别
7 适用于纯文本验证码
5.2 训练自定义模型
如果验证码使用特殊字体或样式,可训练 Tesseract 适应新的字符集:
更多内容访问ttocr.com或联系1436423940
tesseract captcha.png output --psm 6 --oem 1
5.3 进一步优化
降噪处理:可以使用 Core Image 进行滤波,去除噪点。
字符切割:如果验证码字符连在一起,可以考虑字符分割算法提高识别率。