[ PROMPT_NODE_25660 ]
PDF Processing Pro Ocr
[ SKILL_DOCUMENTATION ]
# PDF OCR 处理指南
从扫描的 PDF 和基于图像的文档中提取文本。
## 快速入门
python
import pytesseract
from pdf2image import convert_from_path
from PIL import Image
# 将 PDF 转换为图像
images = convert_from_path("scanned.pdf")
# 从每一页提取文本
for i, image in enumerate(images):
text = pytesseract.image_to_string(image)
print(f"第 {i+1} 页:n{text}n")
## 安装
### 安装 Tesseract
**macOS:**
bash
brew install tesseract
**Ubuntu/Debian:**
bash
sudo apt-get install tesseract-ocr
**Windows:**
下载地址: https://github.com/UB-Mannheim/tesseract/wiki
### 安装 Python 包
bash
pip install pytesseract pdf2image pillow
## 语言支持
python
# 英语 (默认)
text = pytesseract.image_to_string(image, lang="eng")
# 西班牙语
text = pytesseract.image_to_string(image, lang="spa")
# 多语言
text = pytesseract.image_to_string(image, lang="eng+spa+fra")
安装其他语言:
bash
# macOS
brew install tesseract-lang
# Ubuntu
sudo apt-get install tesseract-ocr-spa tesseract-ocr-fra
## 图像预处理
python
from PIL import Image, ImageEnhance, ImageFilter
def preprocess_for_ocr(image):
"""优化图像以提高 OCR 准确性。"""
# 转换为灰度图
image = image.convert("L")
# 增加对比度
enhancer = ImageEnhance.Contrast(image)
image = enhancer.enhance(2.0)
# 去噪
image = image.filter(ImageFilter.MedianFilter())
# 锐化
image = image.filter(ImageFilter.SHARPEN)
return image
# 用法
image = Image.open("scanned_page.png")
processed = preprocess_for_ocr(image)
text = pytesseract.image_to_string(processed)
## 最佳实践
1. **预处理图像**以获得更好的准确性
2. **使用合适的语言**模型
3. **批量处理**大型文档
4. **缓存结果**以避免重复处理
5. **验证输出** - OCR 并非 100% 准确
6. **考虑置信度分数**以进行质量检查
## 生产环境示例
python
import pytesseract
from pdf2image import convert_from_path
from PIL import Image
def ocr_pdf(pdf_path, output_path):
"""OCR PDF 并保存到文本文件。"""
# 转换为图像
images = convert_from_path(pdf_path, dpi=300)
full_text = []
for i, image in enumerate(images, 1):
print(f"正在处理第 {i}/{len(images)} 页")
# 预处理
processed = preprocess_for_ocr(image)
# OCR