Go 构建图像验证码识别系统(集成外部识别模块)
本文介绍如何使用 Go 搭建一个图像验证码识别的服务接口,核心识别由外部 Python 模型完成,Go 负责接收图片、调用模型并返回识别结果。适用于验证码自动化处理、表单识别等场景。
- 项目思路概览
客户端上传验证码图片
Go 后端接收图片,保存为临时文件
调用本地 Python 脚本识别验证码
更多内容访问ttocr.com或联系1436423940
返回识别结果
- Go 模块结构
captcha-ocr-go/
├── main.go
├── recognize.py
├── tmp/
└── go.mod
3. Python 模块识别逻辑(recognize.py)
你可以使用已有训练好的模型,也可以简单地用模拟值占位。
recognize.py
import sys
from PIL import Image
import random
import string
def fake_predict(image_path):
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))
if name == 'main':
image_path = sys.argv[1]
code = fake_predict(image_path)
print(code)
4. Go 服务端主程序(main.go)
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"time"
)
type Response struct {
Code string json:"code"
Error string json:"error,omitempty"
}
func recognizeHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Only POST supported", http.StatusMethodNotAllowed)
return
}
file, header, err := r.FormFile("image")
if err != nil {
http.Error(w, "Image upload failed", http.StatusBadRequest)
return
}
defer file.Close()
tempDir := "tmp"
os.MkdirAll(tempDir, 0755)
filename := fmt.Sprintf("captcha_%d%s", time.Now().UnixNano(), filepath.Ext(header.Filename))
filePath := filepath.Join(tempDir, filename)
out, err := os.Create(filePath)
if err != nil {
http.Error(w, "Failed to save image", http.StatusInternalServerError)
return
}
defer out.Close()
io.Copy(out, file)
cmd := exec.Command("python3", "recognize.py", filePath)
output, err := cmd.CombinedOutput()
if err != nil {
resp := Response{Error: "识别失败"}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
return
}
code := string(output)
code = string([]byte(code)[:len(code)-1]) // 去除换行
resp := Response{Code: code}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
func main() {
http.HandleFunc("/recognize", recognizeHandler)
fmt.Println("Server listening on http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
5. 启动服务与测试
启动服务:
go run main.go
测试请求:
curl -X POST -F "image=@sample.png" http://localhost:8080/recognize
返回:
{"code":"K8FZ"}
浙公网安备 33010602011771号