用 Julia 纠正旋转字符验证码图像并提升 OCR 识别准确率

很多验证码采用倾斜、旋转、甚至波形扭曲字符来干扰自动识别系统。这种扰动虽然对人眼友好,但对 OCR 模型来说破坏了字符结构的线性排列,导致识别失败。本文将演示如何使用 Julia 实现图像倾斜检测与字符旋转校正,结合 OCR 引擎完成识别。

一、准备环境

using Pkg
Pkg.add(["Images", "ImageIO", "ImageMorphology", "ImageTransformations", "Tesseract"])
二、加载图像并灰度化

using Images, ImageIO

img = load("rotated_captcha.png")
gray = Gray.(img)
save("gray.png", gray)
三、二值化处理(黑字白底)

binary = map(x -> x < 0.6 ? 1.0 : 0.0, gray)
save("binary.png", Gray.(binary))
四、估计字符倾斜角度(使用 Hough-like 方法)
我们计算图像的主方向(如重心矩阵或形态学方法),估计旋转角:

using ImageMorphology, ImageTransformations

粗略计算字符整体边界

function estimate_angle(binary)
rows, cols = size(binary)
ys, xs = findall(binary)
x̄ = mean(xs)
ȳ = mean(ys)
dx = xs .- x̄
dy = ys .- ȳ
θ = atan(sum(dx .* dy) / sum(dx .^ 2)) # 主轴角度(radians)
return θ
end

θ = estimate_angle(binary)
println("估计旋转角度(度): ", θ * 180 / π)
五、旋转图像回正

using ImageTransformations

aligned = imrotate(binary, -θ, axes=Centered)
save("aligned.png", Gray.(aligned))
六、使用 OCR 引擎识别
更多内容访问ttocr.com或联系1436423940
using Tesseract

ocr = TesseractOcr("eng")
set_image(ocr, "aligned.png")
text = strip(get_text(ocr))

println("识别结果:", text)

posted @ 2025-07-15 22:35  ttocr、com  阅读(12)  评论(0)    收藏  举报