Swift 和 Tesseract OCR 解析验证码

环境准备
1.1 安装 Tesseract OCR
在 macOS 上,你可以使用 Homebrew 进行安装:

brew install tesseract

更多内容访问ttocr.com或联系1436423940
安装完成后,检查 Tesseract 是否可用:

tesseract --version

1.2 创建 Swift 项目

如果你要在 macOS 终端应用中使用 Swift 进行 OCR 识别,可以创建一个 Swift Package:

mkdir SwiftOCR
cd SwiftOCR
swift package init --type executable

如果你要在 iOS 应用中使用 Tesseract,可以使用 CocoaPods 安装 TesseractOCRiOS:

pod init

在 Podfile 中添加:

pod 'TesseractOCRiOS'

然后执行:

pod install

代码实现(macOS 版本)
在 Sources/SwiftOCR/main.swift 中添加以下代码:

import Foundation
import Vision
import AppKit

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

/// 将图片转换为灰度并进行二值化处理
func preprocessImage(image: NSImage) -> NSImage? {
let ciImage = CIImage(data: image.tiffRepresentation!)
let grayscaleFilter = CIFilter(name: "CIColorControls")!
grayscaleFilter.setValue(ciImage, forKey: kCIInputImageKey)
grayscaleFilter.setValue(0.0, forKey: kCIInputSaturationKey)

let outputImage = grayscaleFilter.outputImage
let rep = NSBitmapImageRep(ciImage: outputImage!)
let pngData = rep.representation(using: .png, properties: [:])

return NSImage(data: pngData!)
}

/// 使用 Tesseract 进行 OCR 识别
func recognizeText(from imagePath: String) -> String? {
let process = Process()
process.launchPath = "/usr/local/bin/tesseract" // 确保路径正确
process.arguments = [imagePath, "stdout", "-l", "eng", "--psm", "6"]

let pipe = Pipe()
process.standardOutput = pipe
process.launch()

let data = pipe.fileHandleForReading.readDataToEndOfFile()
return String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines)
}

let imagePath = "captcha.png" // 请替换为你的验证码图片路径
if let image = loadCaptchaImage(path: imagePath) {
if let processedImage = preprocessImage(image: image) {
let processedPath = "processed_captcha.png"
let imageData = processedImage.tiffRepresentation!
try? imageData.write(to: URL(fileURLWithPath: processedPath))

if let text = recognizeText(from: processedPath) {
    print("识别出的验证码: \(text)")
} else {
    print("OCR 识别失败")
}

}
} else {
print("无法加载图像")
}

代码解析
3.1 读取并预处理图像
func preprocessImage(image: NSImage) -> NSImage?
先将图片转换为灰度

进一步进行二值化处理以增强字符对比度

3.2 调用 Tesseract 进行 OCR 解析
let process = Process()
process.launchPath = "/usr/local/bin/tesseract"
process.arguments = [imagePath, "stdout", "-l", "eng", "--psm", "6"]

使用 Tesseract 识别文本,并设置 PSM 模式为 6(假设文本为单行)

运行程序
执行:

swift run

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

提高识别准确率
5.1 调整 Tesseract PSM 模式
不同的 PSM 模式适用于不同场景:

PSM 6:假设为单行文本

PSM 7:单行纯文本(更适合验证码)

PSM 10:单字符模式(适用于分割验证码)

可以调整:

process.arguments = [imagePath, "stdout", "-l", "eng", "--psm", "7"]

5.2 进一步图像优化

降噪处理:可以使用 OpenCV 进一步去除噪点

字符分割:适用于粘连字符的验证码

posted @ 2025-11-15 23:49  ttocr、com  阅读(6)  评论(0)    收藏  举报