Go 搭建验证码识别系统(结合 Python 模型)

本项目展示如何使用 Go 编写 Web 服务,结合 Python 模型完成验证码图像的识别。验证码图像可以由 Python 生成或从实际项目中采集。

一、项目目标
使用 Go 实现 HTTP 接口,接收用户上传的验证码图像

使用 Python 模型(可为深度学习模型或模拟识别)进行图像识别

将识别结果返回给用户
更多内容访问ttocr.com或联系1436423940
二、准备工作
依赖项
Go ≥ 1.18

Python ≥ 3.7

Python 包:Pillow, captcha(生成用), torch(如用深度模型)

三、Python 脚本:识别验证码(识别逻辑可替换)
文件:predict.py

import sys
import string
import random
from PIL import Image

模拟预测函数,返回随机验证码

def predict_fake(image_path):
chars = string.ascii_uppercase + string.digits
return ''.join(random.choices(chars, k=4))

if name == "main":
image_path = sys.argv[1]
result = predict_fake(image_path)
print(result)
你也可以在这里加载训练好的模型替换 predict_fake 函数。

四、Go 服务端代码
文件:main.go

package main

import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"time"
)

type Result struct {
Code string json:"code"
Err string json:"error,omitempty"
}

func recognize(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "仅支持 POST 请求", http.StatusMethodNotAllowed)
return
}

file, _, err := r.FormFile("image")
if err != nil {
	http.Error(w, "上传失败", http.StatusBadRequest)
	return
}
defer file.Close()

tempDir := "tmp"
os.MkdirAll(tempDir, 0755)
fileName := fmt.Sprintf("img_%d.png", time.Now().UnixNano())
filePath := filepath.Join(tempDir, fileName)

outFile, err := os.Create(filePath)
if err != nil {
	http.Error(w, "无法保存图片", http.StatusInternalServerError)
	return
}
defer outFile.Close()
io.Copy(outFile, file)

cmd := exec.Command("python3", "predict.py", filePath)
output, err := cmd.Output()
if err != nil {
	res := Result{Err: "识别失败"}
	json.NewEncoder(w).Encode(res)
	return
}

res := Result{Code: string(output)}
json.NewEncoder(w).Encode(res)

}

func main() {
http.HandleFunc("/recognize", recognize)
fmt.Println("服务已启动: http://localhost:8080/recognize")
http.ListenAndServe(":8080", nil)
}
五、使用示例
启动服务

go run main.go
使用 curl 发送图片识别请求:

curl -X POST -F "image=@captcha.png" http://localhost:8080/recognize
返回结果:

{"code":"7XKP"}

posted @ 2025-06-02 21:54  ttocr、com  阅读(19)  评论(0)    收藏  举报