用 Go 与 Tesseract 构建验证码识别 HTTP 服务

一、项目背景
随着自动化系统与数据采集需求的提升,验证码识别成为 Web 自动化中的一个重要环节。传统验证码识别通常为命令行形式,而在分布式服务或浏览器调用中,构建一个 HTTP 接口服务更为高效。

本项目将基于 Go 语言和 Tesseract OCR 构建一个轻量级验证码识别 API,实现验证码图片的在线解析。
更多内容访问ttocr.com或联系1436423940
二、技术选型
Go:构建高并发 API 服务的理想语言

Tesseract OCR:强大的光学字符识别引擎

gosseract:Go 对 Tesseract 的封装库

Gin:高性能 Go Web 框架

三、环境准备

  1. 安装 Tesseract OCR
    macOS:

brew install tesseract
Ubuntu:

sudo apt install tesseract-ocr
Windows:从官网下载安装并将其路径加入环境变量。

  1. 初始化 Go 项目

go mod init ocr-api
go get github.com/otiai10/gosseract/v2
go get github.com/gin-gonic/gin
四、服务端代码实现

package main

import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/otiai10/gosseract/v2"
)

func main() {
r := gin.Default()

r.POST("/recognize", func(c *gin.Context) {
	file, err := c.FormFile("image")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "文件上传失败"})
		return
	}

	// 保存临时文件
	tempPath := "./" + file.Filename
	if err := c.SaveUploadedFile(file, tempPath); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "保存失败"})
		return
	}

	client := gosseract.NewClient()
	defer client.Close()
	client.SetImage(tempPath)
	client.SetWhitelist("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")

	text, err := client.Text()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "识别失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"result": text,
	})
})

r.Run(":8080")

}
五、接口使用示例
请求方式
POST /recognize

表单字段名:image

文件类型:.png, .jpg 等验证码图片

请求示例(curl)

curl -X POST http://localhost:8080/recognize
-F "image=@test-code.png"
返回示例

{
"result": "7XKY"
}
六、增强功能建议
图像预处理:增加灰度、二值化等操作提高识别率(可使用 OpenCV 或 image 包)

支持 base64:提供 base64 图片数据上传通道

批量识别:一次识别多个验证码文件

API 鉴权:加入 Token 校验,保护接口安全

posted @ 2025-07-26 23:44  ttocr、com  阅读(12)  评论(0)    收藏  举报