当前位置: 首页 > news >正文

使用 Swift 进行验证码识别:集成 Tesseract OCR

  1. 环境准备
    1.1 安装 Tesseract OCR
    更多内容访问ttocr.com或联系1436423940
    在 macOS 上可以使用 Homebrew 进行安装:

brew install tesseract

安装完成后,检查 Tesseract 是否安装成功:

tesseract --version

1.2 创建 Swift 项目

如果是 macOS 应用,可以使用 Swift Package Manager (SPM),或者直接在 Xcode 项目中集成 OCR 识别功能。

创建一个新的 Swift 项目:

mkdir SwiftCaptchaOCR
cd SwiftCaptchaOCR
swift package init --type executable

编辑 Package.swift,添加 Tesseract 相关库:

// swift-tools-version:5.5
import PackageDescription

let package = Package(
name: "SwiftCaptchaOCR",
dependencies: [
.package(url: "https://github.com/gali8/Tesseract-OCR-iOS.git", from: "4.0.0")
],
targets: [
.executableTarget(
name: "SwiftCaptchaOCR",
dependencies: ["Tesseract-OCR-iOS"]
)
]
)

然后运行:

swift build

  1. 代码实现

在 Sources/SwiftCaptchaOCR/main.swift 中写入以下代码:

import Foundation
import TesseractOCR
import Cocoa

func preprocessImage(inputPath: String, outputPath: String) {
guard let image = NSImage(contentsOfFile: inputPath) else {
print("无法加载图片")
return
}

// 转换为灰度图像
let grayscaleImage = convertToGrayscale(image: image)// 二值化处理
let binaryImage = applyThreshold(image: grayscaleImage, threshold: 128)// 保存处理后的图片
saveImage(image: binaryImage, outputPath: outputPath)

}

func convertToGrayscale(image: NSImage) -> NSImage {
let rep = NSBitmapImageRep(data: image.tiffRepresentation!)
let grayscaleRep = rep?.converting(to: .deviceGray, renderingIntent: .default)
let grayImage = NSImage(size: image.size)
grayImage.addRepresentation(grayscaleRep!)
return grayImage
}

func applyThreshold(image: NSImage, threshold: CGFloat) -> NSImage {
let rep = NSBitmapImageRep(data: image.tiffRepresentation!)!
let width = rep.pixelsWide
let height = rep.pixelsHigh

for x in 0..<width {for y in 0..<height {let color = rep.colorAt(x: x, y: y)!.whiteComponentlet newColor = color > threshold / 255.0 ? NSColor.white : NSColor.blackrep.setColor(newColor, atX: x, y: y)}
}let newImage = NSImage(size: image.size)
newImage.addRepresentation(rep)
return newImage

}

func saveImage(image: NSImage, outputPath: String) {
let rep = NSBitmapImageRep(data: image.tiffRepresentation!)
let pngData = rep?.representation(using: .png, properties: [:])
try? pngData?.write(to: URL(fileURLWithPath: outputPath))
}

func recognizeCaptcha(imagePath: String) -> String {
guard let tesseract = G8Tesseract(language: "eng") else {
return "Tesseract 初始化失败"
}
tesseract.image = NSImage(contentsOfFile: imagePath)
tesseract.recognize()
return tesseract.recognizedText ?? "识别失败"
}

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

// 预处理验证码图像
preprocessImage(inputPath: inputImagePath, outputPath: processedImagePath)

// OCR 识别
let result = recognizeCaptcha(imagePath: processedImagePath)
print("识别出的验证码: (result)")

  1. 代码解析
    3.1 图像预处理

为了提高 OCR 识别率,我们进行了以下优化:

转换为灰度图像:

func convertToGrayscale(image: NSImage) -> NSImage {
let rep = NSBitmapImageRep(data: image.tiffRepresentation!)
let grayscaleRep = rep?.converting(to: .deviceGray, renderingIntent: .default)
let grayImage = NSImage(size: image.size)
grayImage.addRepresentation(grayscaleRep!)
return grayImage
}

二值化处理,增强字符对比度:

func applyThreshold(image: NSImage, threshold: CGFloat) -> NSImage {
let rep = NSBitmapImageRep(data: image.tiffRepresentation!)!
for x in 0..<rep.pixelsWide {
for y in 0..<rep.pixelsHigh {
let color = rep.colorAt(x: x, y: y)!.whiteComponent
let newColor = color > threshold / 255.0 ? NSColor.white : NSColor.black
rep.setColor(newColor, atX: x, y: y)
}
}
let newImage = NSImage(size: image.size)
newImage.addRepresentation(rep)
return newImage
}

3.2 OCR 解析

初始化 Tesseract OCR:

guard let tesseract = G8Tesseract(language: "eng") else {
return "Tesseract 初始化失败"
}

加载图像并执行 OCR:

tesseract.image = NSImage(contentsOfFile: imagePath)
tesseract.recognize()
tesseract.recognizedText ?? "识别失败"

  1. 运行程序

确保 captcha.png 在项目目录下,然后运行:

swift run

示例输出:

识别出的验证码: X9F2G

  1. 提高 OCR 识别率
    5.1 设置 Tesseract PSM 模式

Tesseract 提供不同的页面分割模式(PSM),可以调整以优化验证码识别:

tesseract.setVariableValue("6", forKey: "tessedit_pageseg_mode")

5.2 只识别特定字符
tesseract.charWhitelist = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

5.3 进一步优化

如果验证码干扰较多,可以使用 Core Image 进行滤波、去噪等处理。

http://www.hskmm.com/?act=detail&tid=40789

相关文章:

  • 使用 Rust 进行验证码识别:结合 Tesseract OCR 进行文本解析
  • 使用 Java 解析验证码:结合 Tesseract OCR 进行文本识别
  • 代码大全2阅读笔记(2)
  • 软件技术基本第二次作业
  • Day7CSS的引入方式与选择器
  • ZR-J 2025-10-29 比赛总结
  • newDay17
  • 做题日志3
  • 《代码大全2》观后感-理论与现实的桥梁
  • AI元人文架构:从价值计算到智能主体的演进路径
  • 《代码大全2》观后感-从“码农”到“工匠”的第一课
  • 从零开始编写一个办公软件(二、自适应窗口)
  • 10月29日日记
  • AI浪潮下的职业迷思:机遇还是泡沫?
  • 10/29
  • 静态类型、动态类型、强类型、弱类型
  • 价值主体的技术实现:基于Free Transformer潜变量Z的AI元人文架构探索
  • pyqt 自定义QTableWidget
  • 查询排序与表连接
  • 记录一下我最近一年写的脚本,不知不觉近100个了!
  • The 2025 Hunan Collegiate Programming Contest
  • 第二十二天
  • 2025.10.28
  • 日总结 20
  • 重组蛋白与传统蛋白的区别:从来源到特性的全面解析
  • CSP-S 2025 游记
  • NordicNRF91系列蜂窝产品在偏远地区低轨道卫星物联网连接领域取得关键突破
  • Windows Server 2025镜像下载地址
  • 博客园geek主题拓展-1
  • 2025年10月临江鳝丝店推荐:乐山地区五家优质店铺榜单与对比分析