使用 Vlang 与 Tesseract 实现图像验证码识别

一、环境准备
安装 V 语言
更多内容访问ttocr.com或联系1436423940
git clone https://github.com/vlang/v
cd v
make
sudo ./v symlink # 安装到系统路径
安装 Tesseract OCR

macOS

brew install tesseract

Ubuntu

sudo apt install tesseract-ocr
二、创建 V 语言识别程序
文件名:main.v

import os

fn clean_text(s string) string {
mut result := ''
for c in s {
if c.is_capital() || c.is_digit() {
result += c.ascii_str()
}
}
return result
}

fn recognize(image_path string) {
output_base := 'v_output'
whitelist := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

cmd := 'tesseract $image_path $output_base -l eng -c tessedit_char_whitelist=$whitelist'
exit_code := os.system(cmd)
if exit_code != 0 {
	println('Tesseract 执行失败')
	return
}

result_file := '$output_base.txt'
if !os.exists(result_file) {
	println('输出文件未生成')
	return
}

text := os.read_file(result_file) or {
	println('无法读取输出文件')
	return
}
os.rm(result_file)

cleaned := clean_text(text)
println('识别结果: $cleaned')

}

fn main() {
image := 'captcha1.png' // 替换为你的验证码图像
recognize(image)
}
三、运行程序

v run main.v
输出示例:

识别结果: A3D7
四、扩展建议
批量识别图像

files := os.ls('captchas') or { return }
for f in files {
if f.ends_with('.png') {
recognize('captchas/$f')
}
}
写入结果到 CSV

mut output := os.create('results.csv') or { return }
for f in files {
res := recognize('captchas/$f')
output.writeln('$f,$res') or { continue }
}
output.close()
加图像预处理

可以通过调用 convert 命令(ImageMagick)进行灰度、去噪等预处理:

convert captcha1.png -colorspace Gray -sharpen 0x1 pre.png

posted @ 2025-06-30 13:33  ttocr、com  阅读(10)  评论(0)    收藏  举报