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

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

  1. 环境准备
    1.1 安装 Tesseract OCR

在 macOS 上可以使用 Homebrew 进行安装:

brew install tesseract

更多内容访问ttocr.com或联系1436423940
安装完成后,检查 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.jsqmd.com/news/35845/

相关文章:

  • 700.二叉搜索树中的搜索(二叉树算法) - 实践
  • egg-passport 的原理, 是否依赖数据库
  • P10194 [USACO24FEB] Milk Exchange G 做题记录
  • egg-sequelize 原理, 访问 sequelize 的方式, 支持情况
  • 创建conda环境时将要安装的一些软件包分析
  • 图书馆管理系统需求规格说明书
  • 含错方程与非线性滤波模型的逼近攻击
  • 重生之我在大学自学鸿蒙构建第一天-《基础篇》
  • 点云配准基础知识
  • 完整教程:Android监听第三方播放获取音乐信息及包名
  • git的各种HEAD以及使用示例
  • OneDrive上传和下载速度慢?有什么解决办法吗? - 指南
  • 详细介绍:深入浅出MATLAB数据可视化:超越plot()
  • 既然道可道相当道,那么传道授业解惑的根基是什么?
  • P10592 BZOJ4361 isn
  • 阿道夫
  • 软件开发公司常犯的5个设计误区,看看你中招了吗?
  • 使用jmeter做压力测试 - 实践
  • CSP2025游记总结
  • 连续出现的字符
  • 详解WebSocket及其妙用 - 指南
  • 2025 csp_j 游忌
  • 利用序列ID漏洞下载整个公司用户数据库的技术分析
  • 详细介绍:STM32 定时中断逻辑拆解:为什么 “每 2 次中断翻一次 LED”,却是 1 秒亮 1 秒灭?
  • 11.8 NOIP模拟4 改题记录
  • 红外遥控
  • C 指针初识
  • 翻译[9]-让sshfs再次伟大于浏览器中
  • 计算机毕业设计-基于Java的口腔管理平台系统创建实战(附源码+论文+演示视频)
  • 唯识主义:哲学爱智慧本质的当代回归 - 实践