20行代码教你如何批量提取图片中文字
2025.09.19 13:32浏览量:5简介:本文通过20行Python代码演示如何快速实现图片中文字的批量提取,结合OCR技术与自动化处理流程,提供从环境配置到结果优化的完整解决方案。
引言:OCR技术的现实需求
在数字化办公场景中,纸质文档扫描件、截图、证件照片等非结构化数据中的文字提取需求日益迫切。传统手动录入方式效率低下且易出错,而批量OCR(光学字符识别)技术可通过自动化处理显著提升效率。本文将以Python为工具,通过20行核心代码实现多图片文字的批量提取,覆盖从环境搭建到结果输出的全流程。
技术选型与工具链
核心库解析
- Pillow(PIL):图像处理基础库,支持格式转换、尺寸调整、二值化等预处理操作。
- pytesseract:Tesseract OCR的Python封装,提供多语言识别能力,支持中文需额外下载训练数据。
- os模块:系统文件操作,用于遍历目录、批量读取图片文件。
环境配置指南
# 安装依赖库pip install pillow pytesseract# 安装Tesseract OCR引擎(Windows需下载安装包,Linux可通过包管理器)# 下载中文训练数据(chi_sim.traineddata)并放入Tesseract的tessdata目录
20行核心代码实现
代码结构分解
import osfrom PIL import Imageimport pytesseractdef batch_ocr(image_dir, output_file, lang='chi_sim'):"""批量OCR处理函数Args:image_dir: 图片目录路径output_file: 结果输出文件路径lang: 识别语言(默认简体中文)"""with open(output_file, 'w', encoding='utf-8') as f:for filename in os.listdir(image_dir):if filename.lower().endswith(('.png', '.jpg', '.jpeg')):img_path = os.path.join(image_dir, filename)try:text = pytesseract.image_to_string(Image.open(img_path), lang=lang)f.write(f"=== {filename} ===\n{text}\n\n")except Exception as e:f.write(f"Error processing {filename}: {str(e)}\n\n")# 使用示例batch_ocr('input_images', 'output.txt')
代码逐行解析
- 导入模块:
os处理文件系统,PIL.Image加载图片,pytesseract执行OCR。 - 函数定义:
batch_ocr接收图片目录、输出文件路径和语言参数。 - 文件遍历:
os.listdir获取目录下所有文件,通过后缀名过滤图片。 - OCR处理:
Image.open加载图片后,pytesseract.image_to_string执行识别。 - 结果写入:按”文件名===识别内容”格式写入文本文件,异常情况记录错误信息。
完整实现方案
扩展功能代码(总行数约40行)
import osfrom PIL import Image, ImageOpsimport pytesseractdef preprocess_image(img_path):"""图像预处理:灰度化+二值化"""img = Image.open(img_path).convert('L') # 转为灰度图threshold = 140img = img.point(lambda x: 0 if x < threshold else 255) # 二值化return imgdef batch_ocr_advanced(image_dir, output_file, lang='chi_sim', preprocess=True):"""增强版批量OCR(含预处理)"""results = []for filename in os.listdir(image_dir):if filename.lower().endswith(('.png', '.jpg', '.jpeg')):img_path = os.path.join(image_dir, filename)try:img = Image.open(img_path)if preprocess:img = preprocess_image(img_path)text = pytesseract.image_to_string(img, lang=lang)results.append((filename, text))except Exception as e:results.append((filename, f"Error: {str(e)}"))# 格式化输出with open(output_file, 'w', encoding='utf-8') as f:for filename, text in results:f.write(f"=== {filename} ===\n{text}\n\n")# 使用示例batch_ocr_advanced('input_images', 'output_advanced.txt', preprocess=True)
关键优化策略
1. 图像预处理技术
- 灰度化:将RGB图像转为单通道,减少计算量。
- 二值化:通过阈值分割突出文字区域(示例代码中阈值设为140,可根据实际调整)。
- 降噪:可使用
ImageFilter.MedianFilter去除噪点(需从PIL导入)。
2. 识别参数调优
- 语言包选择:
lang='chi_sim'指定简体中文,其他可选eng(英文)、jpn(日文)等。 - PSM模式:通过
config='--psm 6'参数调整页面分割模式(6表示假设为统一文本块)。
3. 性能优化方案
- 多线程处理:使用
concurrent.futures并行处理图片。
```python
from concurrent.futures import ThreadPoolExecutor
def parallel_ocr(image_dir, output_file, max_workers=4):
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = []
for filename in os.listdir(image_dir):
if filename.lower().endswith((‘.png’, ‘.jpg’, ‘.jpeg’)):
img_path = os.path.join(image_dir, filename)
futures.append(executor.submit(
lambda p: (p, pytesseract.image_to_string(Image.open(p))),
img_path
))
results = [f.result() for f in futures]
# 后续写入逻辑...
### 常见问题解决方案#### 1. 识别准确率低- **原因**:图片质量差、字体复杂、背景干扰。- **对策**:- 调整二值化阈值(示例中为140,可尝试120-180范围)。- 使用`ImageOps.autocontrast`增强对比度。- 对倾斜图片使用`img.rotate`校正角度。#### 2. 中文识别失败- **原因**:未正确安装中文训练数据。- **解决步骤**:1. 下载`chi_sim.traineddata`(可从GitHub获取)。2. 放入Tesseract安装目录的`tessdata`子目录。3. 代码中显式指定`lang='chi_sim'`。#### 3. 大文件处理超时- **优化方法**:- 限制单张图片处理时间:`pytesseract.image_to_string(..., timeout=30)`。- 分批次处理:按文件数量或总大小拆分任务。### 实际应用场景扩展#### 1. 发票文字提取```python# 提取发票关键信息(示例)def extract_invoice_info(text):import repatterns = {'金额': r'金额[::]?\s*(\d+\.?\d*)','日期': r'日期[::]?\s*(\d{4}-\d{2}-\d{2})'}return {k: re.search(v, text).group(1) for k, v in patterns.items() if re.search(v, text)}
2. 表格图片转Excel
- 结合
camelot库提取表格结构:import camelotdef image_table_to_excel(img_path, output_xlsx):tables = camelot.read_pdf('temp.pdf') # 需先将图片转为PDFtables[0].to_excel(output_xlsx)
总结与建议
本文通过20行核心代码实现了图片文字的批量提取,扩展版本进一步整合了预处理、多线程等优化方案。实际应用中需注意:
- 环境依赖:确保Tesseract安装正确且语言包配置无误。
- 图片质量:优先处理300dpi以上的清晰图片。
- 异常处理:记录失败案例以便后续人工复核。
- 性能测试:建议先在小批量数据上验证效果。
对于企业级应用,可考虑将流程封装为API服务(使用FastAPI),或集成到RPA流程中实现全自动处理。后续可探索深度学习模型(如EasyOCR、PaddleOCR)以进一步提升复杂场景下的识别率。

发表评论
登录后可评论,请前往 登录 或 注册