🔧 准备工作: Crystal 没有内建图像处理或 OCR 库,但我们可以通过调用外部工具完成图像识别任务:
安装 Crystal
安装 Tesseract OCR
安装 ImageMagick(用于图像预处理)
准备一张验证码图像 captcha.png
📄 Crystal 示例代码: require "file_utils"
1. 图像预处理(灰度 + 二值化)
puts "正在处理图片..." system("convert captcha.png -colorspace Gray -threshold 50% clean.png")
2. OCR 识别
puts "正在识别验证码..." system("tesseract clean.png output -l eng")
3. 读取识别结果
if File.exists?("output.txt") result = File.read("output.txt").strip puts "识别结果: #{result}" else puts "未能找到识别结果" end 📌 示例输出:
正在处理图片... 正在识别验证码... 识别结果: T3ST9P