用 Go 实现验证码图片识别(基于 TensorFlow Lite)

项目简介
本项目展示如何使用 Go 加载并执行 TensorFlow Lite 模型,实现对图片验证码的自动识别。主要内容包括图像预处理、模型推理和结果输出。

编程语言:Go

推理引擎:TensorFlow Lite(Go 绑定)

应用场景:识别四位数字/字母验证码

环境准备
依赖安装更多内容访问ttocr.com或联系1436423940

go get github.com/mattn/go-tflite
go get github.com/nfnt/resize
⚠️ 请提前准备好 .tflite 模型文件和测试用验证码图像。

示例模型输入格式
输入尺寸:(1, 60, 160, 3) (RGB 彩色图像)

输出张量:4 个,每个为 (1, 36),表示 4 个字符的预测

字符集:0-9, A-Z,共 36 类

Go 代码实现
main.go

package main

import (
"fmt"
"image"
"image/draw"
"image/png"
"os"

"github.com/mattn/go-tflite"
"github.com/nfnt/resize"

)

var charset = []rune("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")

func loadImage(path string) ([]float32, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()

img, err := png.Decode(f)
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, 160*60*3)
idx := 0
for y := 0; y < 60; y++ {
	for x := 0; x < 160; x++ {
		r, g, b, _ := rgba.At(x, y).RGBA()
		data[idx] = float32(r) / 65535
		data[idx+1] = float32(g) / 65535
		data[idx+2] = float32(b) / 65535
		idx += 3
	}
}
return data, nil

}

func predict(path string) (string, error) {
model := tflite.NewModelFromFile("captcha_model.tflite")
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)
imageData, err := loadImage(path)
if err != nil {
	return "", err
}
input.CopyFromBuffer(imageData)

if interpreter.Invoke() != nil {
	return "", fmt.Errorf("模型推理失败")
}

result := ""
for i := 0; i < 4; i++ {
	output := interpreter.GetOutputTensor(i)
	out := make([]float32, 36)
	output.CopyToBuffer(&out[0])

	maxIdx := 0
	for j, val := range out {
		if val > out[maxIdx] {
			maxIdx = j
		}
	}
	result += string(charset[maxIdx])
}
return result, nil

}

func main() {
code, err := predict("captcha.png")
if err != nil {
fmt.Println("识别失败:", err)
return
}
fmt.Println("验证码识别结果:", code)
}
示例输出

$ go run main.go
验证码识别结果: 7KQF

posted @ 2025-05-31 23:16  ttocr、com  阅读(17)  评论(0)    收藏  举报