跳转至正文内容

Tesseract OCR 技术开发手册

Tesseract OCR 是全球最流行且成熟的开源光学字符识别引擎,基于 LSTM 深度神经网络,支持识别 100 多种全球语言。

最新标准: 本手册完全基于搭载深度学习引擎的 Tesseract v5.3+ 进行编写。

安装指南

根据您的开发环境选择合适的操作系统安装指令:

macOS (Homebrew)

brew install tesseract
brew install tesseract-lang  # 安装全语言模型

Ubuntu / Debian

sudo apt update
sudo apt install tesseract-ocr tesseract-ocr-chi-sim tesseract-ocr-eng

Windows

winget install UB-Mannheim.TesseractOCR
# 或使用 Scoop:
scoop install tesseract

CLI 快速入门

基础文字提取命令示例:

# 从图片识别中英文并输出至终端 stdout
tesseract input.png stdout -l chi_sim+eng

# 输出保存为文本文件 (output.txt)
tesseract scan.jpg output -l chi_sim+eng

# 直接生成双层可搜索可复制 PDF
tesseract document.tif output_searchable -l chi_sim pdf

页面分割模式 (PSM)

使用 --psm <N> 参数指定版面分析策略:

PSM 模式说明 适用场景
0 仅方向和文字体系检测 (OSD) 旋转角度校正与语种识别
1 自动页面分割 + OSD 多语言混排复杂扫描件
3 全自动页面分割 (默认) 标准多段落普通文档
6 单个统一文本块 发票、收据、单一文字段落
7 单行文本 车牌号码、条形码下方文本
8 单个单词 验证码、独立词语

Python 快速集成 (pytesseract)

import pytesseract
from PIL import Image

# 读取图像
img = Image.open('receipt.jpg')

# 提取中英文文本
text = pytesseract.image_to_string(img, lang='chi_sim+eng', config='--psm 6')
print(text)

# 生成可搜索 PDF 二进制数据
pdf_bytes = pytesseract.image_to_pdf_or_hocr(img, extension='pdf', lang='chi_sim')
with open('output.pdf', 'wb') as f:
    f.write(pdf_bytes)

Node.js 与前端浏览器 (tesseract.js)

import { createWorker } from 'tesseract.js';

const worker = await createWorker('chi_sim');
const { data: { text, confidence } } = await worker.recognize('invoice.png');

console.log(`平均置信度: ${confidence}%`);
console.log(text);

await worker.terminate();

自定义模型微调训练 (tesstrain)

使用官方训练流水线工具 tesstrain 对特定生僻字、特殊字体或行业专业术语进行模型微调:

# 克隆官方训练工具库
git clone https://github.com/tesseract-ocr/tesstrain.git
cd tesstrain

# 执行微调训练
make training MODEL_NAME=chi_custom START_MODEL=chi_sim TESSDATA_PREFIX=/usr/share/tesseract-ocr/5/tessdata