用 Go 搭建验证码识别前端服务,结合 Python 深度学习模型识别验证码图片
本教程将演示如何:
用 Go 搭建前端 Web 上传页面
用户上传验证码图片
Go 后端将图像发送给 Python 模型识别接口
返回并展示识别结果
适合 Go 工程师在项目中集成图像识别功能。
一、准备 Python 验证码识别服务
使用你已训练好的 PyTorch 模型,在 serve.py 中部署为 REST API 服务:
from flask import Flask, request, jsonify
from PIL import Image
import torch
from torchvision import transforms
from model import CRNN
app = Flask(name)
model = CRNN()
model.load_state_dict(torch.load("crnn_model.pth", map_location="cpu"))
model.eval()
characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
transform = transforms.Compose([
transforms.Resize((60, 160)),
transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))
])
@app.route("/predict", methods=["POST"])
def predict():
image = Image.open(request.files['image']).convert("RGB")
x = transform(image).unsqueeze(0)
with torch.no_grad():
output = model(x)
pred = torch.argmax(output, dim=2)[0]
result = ''.join([characters[i] for i in pred])
return jsonify({"result": result})
if name == "main":
app.run(port=5002)
启动模型服务:
python serve.py
二、用 Go 编写前端上传页面 + 识别逻辑
创建静态 HTML 表单 index.html:
上传验证码图片
创建 Go 后端 main.go:package main
import (
"bytes"
"fmt"
"html/template"
"io"
"mime/multipart"
"net/http"
"os"
)
func main() {
http.HandleFunc("/", serveForm)
http.HandleFunc("/upload", handleUpload)
http.ListenAndServe(":8080", nil)
}
func serveForm(w http.ResponseWriter, r *http.Request) {
tmpl, _ := template.ParseFiles("index.html")
tmpl.Execute(w, nil)
}
func handleUpload(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(10 << 20)
file, _, err := r.FormFile("captcha")
if err != nil {
http.Error(w, "上传文件失败", http.StatusBadRequest)
return
}
defer file.Close()
// 发送到 Python 接口
var buf bytes.Buffer
writer := multipart.NewWriter(&buf)
part, _ := writer.CreateFormFile("image", "captcha.png")
io.Copy(part, file)
writer.Close()
resp, err := http.Post("http://localhost:5002/predict", writer.FormDataContentType(), &buf)
if err != nil {
http.Error(w, "识别请求失败", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
io.Copy(w, resp.Body)
}
启动 Go 服务:
更多内容访问ttocr.com或联系1436423940
go run main.go
访问浏览器:http://localhost:8080,上传验证码图片,即可看到识别结果。
浙公网安备 33010602011771号