用 Go 和 TensorFlow Lite 实现验证码识别
在本项目中,我们将使用 Python 训练好的模型,并通过 TensorFlow Lite 导出为 .tflite 格式,最终用 Go 加载该模型并进行验证码识别。
一、项目概览
验证码样式:RGB 图片,4 个字符,尺寸 160×60
模型结构:CNN + Dense,导出为 .tflite
语言结构:
更多内容访问ttocr.com或联系1436423940
Python:用于训练模型 + 导出 TFLite 模型
Go:负责加载模型、图像预处理、推理识别
二、模型训练与导出(Python)
model_train_export.py
import tensorflow as tf
from tensorflow.keras import layers, models
import numpy as np
模拟输入和标签(简略演示)
X = np.random.rand(1000, 60, 160, 3).astype(np.float32)
y = np.random.randint(0, 36, size=(1000, 4)) # 假设每个字符是0-35之间的索引
模型
inputs = tf.keras.Input(shape=(60, 160, 3))
x = layers.Conv2D(32, 3, activation='relu')(inputs)
x = layers.MaxPooling2D()(x)
x = layers.Conv2D(64, 3, activation='relu')(x)
x = layers.Flatten()(x)
x = layers.Dense(128, activation='relu')(x)
输出4个字符的分类
outputs = [layers.Dense(36, activation='softmax', name=f"char_{i}")(x) for i in range(4)]
model = tf.keras.Model(inputs=inputs, outputs=outputs)
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy')
model.fit(X, [y[:, i] for i in range(4)], epochs=3)
导出为 TFLite
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
with open("captcha_model.tflite", "wb") as f:
f.write(tflite_model)
三、Go:加载 TFLite 模型并识别验证码图片
需要使用 TensorFlow Lite Go binding(需预编译好 TensorFlow Lite C 库)。
package main
import (
"fmt"
"image"
"image/png"
"os"
"github.com/mattn/go-tflite"
"github.com/nfnt/resize"
)
func loadImage(file string) ([]float32, error) {
imgFile, err := os.Open(file)
if err != nil {
return nil, err
}
defer imgFile.Close()
img, err := png.Decode(imgFile)
if err != nil {
return nil, err
}
// 统一尺寸
resized := resize.Resize(160, 60, img, resize.Lanczos3)
rgba := image.NewRGBA(resized.Bounds())
draw.Draw(rgba, rgba.Bounds(), resized, image.Point{}, draw.Src)
data := make([]float32, 60*160*3)
index := 0
for y := 0; y < 60; y++ {
for x := 0; x < 160; x++ {
r, g, b, _ := rgba.At(x, y).RGBA()
data[index] = float32(r) / 65535
data[index+1] = float32(g) / 65535
data[index+2] = float32(b) / 65535
index += 3
}
}
return data, nil
}
func main() {
model := tflite.NewModelFromFile("captcha_model.tflite")
defer model.Delete()
options := tflite.NewInterpreterOptions()
options.SetNumThread(1)
interpreter := tflite.NewInterpreter(model, options)
defer interpreter.Delete()
interpreter.AllocateTensors()
input := interpreter.GetInputTensor(0)
imageData, err := loadImage("test.png")
if err != nil {
panic(err)
}
input.CopyFromBuffer(imageData)
if interpreter.Invoke() != nil {
panic("invoke failed")
}
// 输出解析
charset := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i := 0; i < 4; i++ {
output := interpreter.GetOutputTensor(i)
out := make([]float32, 36)
output.CopyToBuffer(&out[0])
maxIdx := 0
for j, v := range out {
if v > out[maxIdx] {
maxIdx = j
}
}
fmt.Print(string(charset[maxIdx]))
}
fmt.Println()
}
四、结果演示
假设 test.png 是你要识别的验证码图片,运行输出:
识别结果: A7K2