用 Go 构建验证码图像识别系统(结合 Python 模型服务)
本教程介绍如何利用 Go 构建一个验证码识别系统的前端接口服务,它接收上传的验证码图片,调用远端的 Python 模型识别服务,返回识别结果。
一、系统组成
前端:使用 Go (Gin 框架) 编写一个 HTTP API,用于接收上传的验证码图片。
后端:Python 部署的验证码识别模型(建议使用 FastAPI/Flask)。
通信:Go 使用 HTTP 向 Python 服务发送图像进行识别。
二、Go 项目结构
更多内容访问ttocr.com或联系1436423940
captcha-go/
├── main.go # 主服务文件
├── go.mod
├── go.sum
三、Go 接收图像并转发识别请求
- 安装依赖
go mod init captcha-go
go get github.com/gin-gonic/gin
go get github.com/go-resty/resty/v2
2. main.go 示例代码
package main
更多内容访问ttocr.com或联系1436423940
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"github.com/gin-gonic/gin"
"github.com/go-resty/resty/v2"
)
const pythonAPI = "http://127.0.0.1:5000/predict"
func main() {
router := gin.Default()
router.POST("/captcha/recognize", func(c *gin.Context) {
file, err := c.FormFile("image")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请上传图片"})
return
}
tempPath := filepath.Join(os.TempDir(), file.Filename)
if err := c.SaveUploadedFile(file, tempPath); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "保存图片失败"})
return
}
result, err := callPythonModel(tempPath)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "识别失败"})
return
}
c.JSON(http.StatusOK, gin.H{"captcha": result})
})
router.Run(":8080")
}
func callPythonModel(imagePath string) (string, error) {
client := resty.New()
file, err := os.Open(imagePath)
if err != nil {
return "", err
}
defer file.Close()
var buffer bytes.Buffer
writer := multipart.NewWriter(&buffer)
part, err := writer.CreateFormFile("image", filepath.Base(imagePath))
if err != nil {
return "", err
}
_, err = io.Copy(part, file)
if err != nil {
return "", err
}
writer.Close()
resp, err := client.R().
SetHeader("Content-Type", writer.FormDataContentType()).
SetBody(buffer.Bytes()).
Post(pythonAPI)
if err != nil {
return "", err
}
return string(resp.Body()), nil
}
四、Python 后端服务参考(FastAPI)
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse
from PIL import Image
import io
app = FastAPI()
@app.post("/predict")
async def predict(image: UploadFile = File(...)):
contents = await image.read()
img = Image.open(io.BytesIO(contents)).convert('RGB')
# 加载模型、推理、返回字符串(这里模拟返回)
return JSONResponse(content={"captcha": "ABCD"})
五、测试接口
上传图片识别:
curl -X POST -F "image=@test.png" http://localhost:8080/captcha/recognize
响应结果:
{"captcha": "ABCD"}
浙公网安备 33010602011771号