Go 实战:构建图像验证码识别系统
图像验证码广泛用于防止自动化攻击。本篇文章将使用 Go 实现一个完整的验证码识别系统,结合 Python 训练的模型和 Go 推理引擎完成识别流程。
一、整体流程
使用 Python 生成验证码数据并训练模型(输出 .tflite)
Go 语言加载验证码图像并处理
使用 TensorFlow Lite Go 接口进行预测
更多内容访问ttocr.com或联系1436423940
输出识别结果
二、Python 训练模型(预处理阶段)
此部分只需完成一次。我们使用 captcha 生成器、PyTorch 训练模型,并导出为 TensorFlow Lite 格式。
示例输出 TFLite 模型
import tensorflow as tf
model = tf.keras.models.load_model('captcha_model.h5')
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
open("captcha_model.tflite", "wb").write(tflite_model)
三、Go 加载模型并识别验证码
- 安装依赖
go get github.com/mattn/go-tflite
go get github.com/nfnt/resize
2. 图像预处理函数
func loadImageToTensor(path string) ([]float32, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
img, err := png.Decode(file)
if err != nil {
return nil, err
}
resized := resize.Resize(160, 60, img, resize.Bilinear)
result := make([]float32, 160*60*3)
i := 0
for y := 0; y < 60; y++ {
for x := 0; x < 160; x++ {
r, g, b, _ := resized.At(x, y).RGBA()
result[i] = float32(r>>8) / 255.0
result[i+1] = float32(g>>8) / 255.0
result[i+2] = float32(b>>8) / 255.0
i += 3
}
}
return result, nil
}
3. 加载 TFLite 模型并预测
func predict(modelPath, imagePath string) (string, error) {
model := tflite.NewModelFromFile(modelPath)
if model == nil {
return "", fmt.Errorf("模型加载失败")
}
defer model.Delete()
options := tflite.NewInterpreterOptions()
interpreter := tflite.NewInterpreter(model, options)
defer interpreter.Delete()
if interpreter.AllocateTensors() != nil {
return "", fmt.Errorf("张量分配失败")
}
input := interpreter.GetInputTensor(0)
data, err := loadImageToTensor(imagePath)
if err != nil {
return "", err
}
input.CopyFromBuffer(data)
if interpreter.Invoke() != nil {
return "", fmt.Errorf("推理失败")
}
charset := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
result := ""
for i := 0; i < 4; i++ {
output := interpreter.GetOutputTensor(i)
buf := make([]float32, len(charset))
output.CopyToBuffer(&buf[0])
maxIdx := 0
for j := range buf {
if buf[j] > buf[maxIdx] {
maxIdx = j
}
}
result += string(charset[maxIdx])
}
return result, nil
}
4. 主函数调用
func main() {
result, err := predict("captcha_model.tflite", "test_captcha.png")
if err != nil {
log.Fatal(err)
}
fmt.Println("识别结果:", result)
}
浙公网安备 33010602011771号