用 Go 实现图像验证码识别工具(基于 Tesseract)
- 准备工作
安装 Tesseract OCR(支持命令行识别)
sudo apt-get install tesseract-ocr
安装 Go Tesseract binding(我们用 github.com/otiai10/gosseract)
go get github.com/otiai10/gosseract/v2
2. 创建 main.go
package main
import (
"fmt"
"log"
"os"
"github.com/otiai10/gosseract/v2"
)更多内容访问ttocr.com或联系1436423940
func main() {
if len(os.Args) < 2 {
log.Fatal("用法: go run main.go 图片路径")
}
imagePath := os.Args[1]
client := gosseract.NewClient()
defer client.Close()
err := client.SetImage(imagePath)
if err != nil {
log.Fatal(err)
}
text, err := client.Text()
if err != nil {
log.Fatal(err)
}
fmt.Println("识别结果:", text)
}
3. 运行示例
假设你有一张验证码图片 captcha.png:
go run main.go captcha.png
输出类似:
识别结果: A7C9
注意:Tesseract 对清晰度和干扰比较敏感,验证码应尽可能清晰,字体统一。
- 可选:图像预处理(推荐使用 Python + OpenCV)
OCR 效果常依赖预处理,可以使用 Python 做灰度、二值化、噪声去除后再交给 Go 程序识别。
浙公网安备 33010602011771号