用 Go 与 Tesseract 实现验证码识别服务

在这篇文章中,我们将构建一个使用 Go 编写的验证码识别工具,依赖开源 OCR 引擎 Tesseract 实现图像文字识别。该工具适用于数字、字母验证码的自动提取与解析任务。

一、核心技术
Go 语言:后端服务和逻辑实现
更多内容访问ttocr.com或联系1436423940
Tesseract OCR:图像文字识别引擎

Go-Tesseract 绑定:通过 CGo 调用 Tesseract API

二、环境准备
安装 Tesseract
根据操作系统选择安装方法:

Ubuntu / Debian

sudo apt update
sudo apt install tesseract-ocr
macOS (使用 Homebrew)

brew install tesseract
安装 Go 依赖

go get github.com/otiai10/gosseract/v2
三、项目结构

captcha-ocr-go/
├── main.go
├── sample.png // 测试验证码图片
四、Go 代码实现
文件:main.go

package main

import (
"fmt"
"log"
"net/http"
"os"

"github.com/otiai10/gosseract/v2"

)

func recognizeCaptcha(imagePath string) (string, error) {
client := gosseract.NewClient()
defer client.Close()

err := client.SetImage(imagePath)
if err != nil {
	return "", err
}

// 可选:限制识别字符集(如仅识别大写字母与数字)
client.SetWhitelist("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

text, err := client.Text()
if err != nil {
	return "", err
}

return text, nil

}

func handler(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()

tmpFile := "upload.png"
out, err := os.Create(tmpFile)
if err != nil {
	http.Error(w, "无法保存临时文件", http.StatusInternalServerError)
	return
}
defer out.Close()

_, err = out.ReadFrom(file)
if err != nil {
	http.Error(w, "文件写入失败", http.StatusInternalServerError)
	return
}

result, err := recognizeCaptcha(tmpFile)
if err != nil {
	http.Error(w, "识别失败", http.StatusInternalServerError)
	return
}

fmt.Fprintf(w, "识别结果: %s\n", result)

}

func main() {
http.HandleFunc("/recognize", handler)
fmt.Println("服务已启动:http://localhost:8080/recognize")
log.Fatal(http.ListenAndServe(":8080", nil))
}
五、测试服务
启动服务:

go run main.go
发送验证码图片:

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

识别结果: 7KF9

posted @ 2025-06-02 22:00  ttocr、com  阅读(27)  评论(0)    收藏  举报